opencode-agent-orchestration-kit 1.0.29 → 1.0.30

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,1454 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import test from "node:test";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
11
+ const root = path.dirname(scriptDir);
12
+ const runnerPath = path.join(root, "scripts/replay-routing.mjs");
13
+ const corpusPath = path.join(
14
+ root,
15
+ "docs/ai/evolution/benchmarks/router-scenarios.jsonl",
16
+ );
17
+ const fixturesPath = path.join(
18
+ root,
19
+ "docs/ai/evolution/benchmarks/replay-fixtures.jsonl",
20
+ );
21
+ const coverageChannels = [
22
+ "session_events",
23
+ "skill_events",
24
+ "tool_events",
25
+ "review_events",
26
+ "stop_events",
27
+ ];
28
+ const assertionIds = [
29
+ "observation-integrity",
30
+ "root-agent",
31
+ "required-agents",
32
+ "forbidden-agents",
33
+ "skills",
34
+ "write-before-spec",
35
+ "review-policy",
36
+ "stop-condition",
37
+ "delegation-budget",
38
+ ];
39
+
40
+ const eventKeys = {
41
+ session_started: ["sequence", "type", "session_id", "parent_session_id", "agent"],
42
+ session_completed: ["sequence", "type", "session_id", "agent"],
43
+ skill_selected: ["sequence", "type", "session_id", "agent", "skill"],
44
+ tool_call_completed: ["sequence", "type", "session_id", "agent", "tool", "mutation"],
45
+ review_completed: ["sequence", "type", "session_id", "agent", "verdict"],
46
+ stop_observed: ["sequence", "type", "condition"],
47
+ run_error: ["sequence", "type", "code"],
48
+ };
49
+
50
+ function readJsonl(file) {
51
+ return fs
52
+ .readFileSync(file, "utf8")
53
+ .trimEnd()
54
+ .split("\n")
55
+ .map((line, index) => {
56
+ try {
57
+ return JSON.parse(line);
58
+ } catch (error) {
59
+ throw new Error(`${file}: line ${index + 1} invalid JSON: ${error.message}`);
60
+ }
61
+ });
62
+ }
63
+
64
+ function writeJsonl(file, records) {
65
+ fs.writeFileSync(file, `${records.map((record) => JSON.stringify(record)).join("\n")}\n`);
66
+ }
67
+
68
+ function clone(value) {
69
+ return structuredClone(value);
70
+ }
71
+
72
+ function makeReplayCopy() {
73
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-routing-replay-"));
74
+ const corpus = path.join(cwd, "router-scenarios.jsonl");
75
+ const fixtures = path.join(cwd, "replay-fixtures.jsonl");
76
+ fs.copyFileSync(corpusPath, corpus);
77
+ fs.copyFileSync(fixturesPath, fixtures);
78
+ return { cwd, corpus, fixtures, report: path.join(cwd, "routing-replay-report.json") };
79
+ }
80
+
81
+ function runReplay(copy) {
82
+ const result = spawnSync(
83
+ process.execPath,
84
+ [
85
+ runnerPath,
86
+ "--corpus",
87
+ copy.corpus,
88
+ "--fixtures",
89
+ copy.fixtures,
90
+ "--output",
91
+ copy.report,
92
+ ],
93
+ { cwd: copy.cwd, encoding: "utf8" },
94
+ );
95
+ const report = fs.existsSync(copy.report)
96
+ ? JSON.parse(fs.readFileSync(copy.report, "utf8"))
97
+ : null;
98
+ return { ...result, report };
99
+ }
100
+
101
+ function runReplayWithoutOutput(copy) {
102
+ return spawnSync(
103
+ process.execPath,
104
+ [
105
+ runnerPath,
106
+ "--corpus",
107
+ copy.corpus,
108
+ "--fixtures",
109
+ copy.fixtures,
110
+ ],
111
+ { cwd: copy.cwd, encoding: "utf8" },
112
+ );
113
+ }
114
+
115
+ function runReplayWithOutput(copy, output) {
116
+ return spawnSync(
117
+ process.execPath,
118
+ [
119
+ runnerPath,
120
+ "--corpus",
121
+ copy.corpus,
122
+ "--fixtures",
123
+ copy.fixtures,
124
+ "--output",
125
+ output,
126
+ ],
127
+ { cwd: copy.cwd, encoding: "utf8" },
128
+ );
129
+ }
130
+
131
+ function withReplayCopy(callback) {
132
+ const copy = makeReplayCopy();
133
+ try {
134
+ return callback(copy);
135
+ } finally {
136
+ fs.rmSync(copy.cwd, { recursive: true, force: true });
137
+ }
138
+ }
139
+
140
+ function mutateFixture(copy, scenarioId, mutate) {
141
+ const fixtures = readJsonl(copy.fixtures);
142
+ const fixture = fixtureFor(fixtures, scenarioId);
143
+ mutate(fixture, fixtures);
144
+ writeJsonl(copy.fixtures, fixtures);
145
+ }
146
+
147
+ function fixtureFor(fixtures, scenarioId) {
148
+ const fixture = fixtures.find((candidate) => candidate.scenario_id === scenarioId);
149
+ assert.ok(fixture, `missing fixture ${scenarioId}`);
150
+ return fixture;
151
+ }
152
+
153
+ function scenarioIdsFromCorpus(corpus) {
154
+ return readJsonl(corpus)
155
+ .map((scenario) => scenario.id)
156
+ .sort();
157
+ }
158
+
159
+ function mutateScenario(copy, scenarioId, mutate) {
160
+ const scenarios = readJsonl(copy.corpus);
161
+ const scenario = scenarios.find((candidate) => candidate.id === scenarioId);
162
+ assert.ok(scenario, `missing scenario ${scenarioId}`);
163
+ mutate(scenario, scenarios);
164
+ writeJsonl(copy.corpus, scenarios);
165
+ }
166
+
167
+ function resequence(events) {
168
+ for (const [index, event] of events.entries()) event.sequence = index + 1;
169
+ }
170
+
171
+ function insertBeforeStop(fixture, event) {
172
+ const stopIndex = fixture.events.findIndex((candidate) => candidate.type === "stop_observed");
173
+ assert.notEqual(stopIndex, -1, "fixture has no stop event");
174
+ fixture.events.splice(stopIndex, 0, event);
175
+ resequence(fixture.events);
176
+ }
177
+
178
+ function addSession(fixture, { sessionId, agent }) {
179
+ insertBeforeStop(fixture, {
180
+ sequence: 0,
181
+ type: "session_started",
182
+ session_id: sessionId,
183
+ parent_session_id: "root",
184
+ agent,
185
+ });
186
+ }
187
+
188
+ function removeAgentEvents(fixture, agent) {
189
+ const removedIds = new Set(
190
+ fixture.events
191
+ .filter((event) => event.type === "session_started" && event.agent === agent)
192
+ .map((event) => event.session_id),
193
+ );
194
+ fixture.events = fixture.events.filter(
195
+ (event) => event.agent !== agent && !removedIds.has(event.session_id),
196
+ );
197
+ resequence(fixture.events);
198
+ }
199
+
200
+ function assertionFor(report, scenarioId, assertionId) {
201
+ assert.ok(report, "runner did not write a report");
202
+ const scenario = report.scenario_results.find(
203
+ (candidate) => candidate.scenario_id === scenarioId,
204
+ );
205
+ assert.ok(scenario, `missing result ${scenarioId}`);
206
+ const assertion = scenario.assertions.find((candidate) => candidate.id === assertionId);
207
+ assert.ok(assertion, `missing assertion ${assertionId}`);
208
+ return assertion;
209
+ }
210
+
211
+ function assertCompleteScenarioResults(report, corpus) {
212
+ assert.ok(Array.isArray(report.scenario_results), "report has no scenario_results");
213
+ const expectedIds = scenarioIdsFromCorpus(corpus);
214
+ const actualIds = report.scenario_results.map((scenario) => scenario.scenario_id);
215
+
216
+ assert.equal(actualIds.length, expectedIds.length, "report has a truncated scenario batch");
217
+ assert.equal(new Set(actualIds).size, actualIds.length, "report has duplicate scenario IDs");
218
+ assert.deepEqual(actualIds, expectedIds, "report scenario IDs differ from the corpus");
219
+
220
+ for (const scenario of report.scenario_results) {
221
+ assert.deepEqual(
222
+ scenario.assertions.map((assertion) => assertion.id),
223
+ assertionIds,
224
+ `${scenario.scenario_id} has an incomplete assertion contract`,
225
+ );
226
+ }
227
+
228
+ return report.scenario_results;
229
+ }
230
+
231
+ function expectVerdict(copy, {
232
+ exitCode,
233
+ overallStatus,
234
+ scenarioId,
235
+ assertionId,
236
+ assertionStatus,
237
+ reasonCode,
238
+ }) {
239
+ const result = runReplay(copy);
240
+ assert.equal(result.status, exitCode, result.stderr);
241
+ assert.ok(result.report, result.stderr);
242
+ assert.equal(result.report.status, overallStatus);
243
+ const scenarioResults = assertCompleteScenarioResults(result.report, copy.corpus);
244
+ const mutatedScenario = scenarioResults.find(
245
+ (scenario) => scenario.scenario_id === scenarioId,
246
+ );
247
+ assert.ok(mutatedScenario, `missing result ${scenarioId}`);
248
+ assert.equal(mutatedScenario.status, overallStatus);
249
+
250
+ const untouchedScenarios = scenarioResults.filter(
251
+ (scenario) => scenario.scenario_id !== scenarioId,
252
+ );
253
+ assert.ok(untouchedScenarios.length > 0, "verdict helper needs an untouched control");
254
+ for (const scenario of untouchedScenarios) {
255
+ assert.equal(scenario.status, "pass", `${scenario.scenario_id} was unexpectedly affected`);
256
+ assert.ok(
257
+ scenario.assertions.every((assertion) => assertion.status === "pass"),
258
+ `${scenario.scenario_id} contains a non-pass assertion`,
259
+ );
260
+ }
261
+ assert.deepEqual(
262
+ scenarioResults
263
+ .filter((scenario) => scenario.status !== "pass")
264
+ .map((scenario) => scenario.scenario_id),
265
+ [scenarioId],
266
+ "report must contain exactly one affected scenario",
267
+ );
268
+
269
+ const assertion = assertionFor(result.report, scenarioId, assertionId);
270
+ assert.equal(assertion.status, assertionStatus);
271
+ assert.equal(assertion.reason_code, reasonCode);
272
+ }
273
+
274
+ function expectInputError(copy, line, field, reason) {
275
+ const result = runReplay(copy);
276
+ assert.equal(result.status, 2, result.stderr);
277
+ assert.equal(result.report, null, "invalid input produced a canonical report");
278
+ assert.match(
279
+ result.stderr,
280
+ new RegExp(
281
+ `${escapeRegExp(copy.fixtures)}: line ${line} ${escapeRegExp(field)} ${escapeRegExp(reason)}`,
282
+ ),
283
+ );
284
+ }
285
+
286
+ function escapeRegExp(value) {
287
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
288
+ }
289
+
290
+ test("canonical fixtures cover the corpus exactly and have closed complete shape", () => {
291
+ const scenarios = readJsonl(corpusPath);
292
+ const fixtures = readJsonl(fixturesPath);
293
+ const expectedIds = scenarios.map((scenario) => scenario.id).sort();
294
+ const actualIds = fixtures.map((fixture) => fixture.scenario_id).sort();
295
+
296
+ assert.equal(fixtures.length, expectedIds.length);
297
+ assert.deepEqual(actualIds, expectedIds);
298
+ assert.equal(new Set(actualIds).size, actualIds.length);
299
+
300
+ for (const fixture of fixtures) {
301
+ assert.deepEqual(
302
+ Object.keys(fixture).sort(),
303
+ ["events", "git_snapshot", "observation_coverage", "scenario_id", "schema_version"],
304
+ );
305
+ assert.equal(fixture.schema_version, 1);
306
+ assert.deepEqual(Object.keys(fixture.observation_coverage).sort(), coverageChannels.toSorted());
307
+ assert.deepEqual(
308
+ Object.values(fixture.observation_coverage),
309
+ Array(coverageChannels.length).fill("complete"),
310
+ );
311
+ assert.ok(["clean", "changed"].includes(fixture.git_snapshot));
312
+ assert.ok(Array.isArray(fixture.events));
313
+ assert.ok(fixture.events.length > 0);
314
+
315
+ let previousSequence = 0;
316
+ const sessions = new Map();
317
+ for (const event of fixture.events) {
318
+ assert.deepEqual(Object.keys(event).sort(), eventKeys[event.type]?.toSorted());
319
+ assert.ok(Number.isInteger(event.sequence) && event.sequence > previousSequence);
320
+ previousSequence = event.sequence;
321
+ if (event.type === "session_started") {
322
+ assert.ok(!sessions.has(event.session_id));
323
+ if (event.parent_session_id === null) {
324
+ assert.equal(sessions.size, 0);
325
+ } else {
326
+ assert.ok(sessions.has(event.parent_session_id));
327
+ }
328
+ sessions.set(event.session_id, event.agent);
329
+ } else if ("session_id" in event) {
330
+ assert.equal(sessions.get(event.session_id), event.agent);
331
+ }
332
+ }
333
+ }
334
+
335
+ const changed = fixtures.filter((fixture) => fixture.git_snapshot === "changed");
336
+ assert.deepEqual(changed.map((fixture) => fixture.scenario_id), [
337
+ "public-sync-private-boundary",
338
+ ]);
339
+ });
340
+
341
+ test("canonical replay exits 0 and reports pass for every corpus scenario", () => {
342
+ withReplayCopy((copy) => {
343
+ const result = runReplay(copy);
344
+ assert.equal(result.status, 0, result.stderr);
345
+ assert.ok(result.report, result.stderr);
346
+ assert.equal(result.report.schema_version, 1);
347
+ assert.equal(result.report.mode, "deterministic");
348
+ assert.equal(result.report.operational_status, "ok");
349
+ assert.equal(result.report.status, "pass");
350
+ const scenarioResults = assertCompleteScenarioResults(result.report, copy.corpus);
351
+ assert.equal(scenarioResults.length, readJsonl(copy.corpus).length);
352
+ for (const scenario of scenarioResults) {
353
+ assert.equal(scenario.status, "pass");
354
+ assert.ok(scenario.assertions.every((assertion) => assertion.status === "pass"));
355
+ }
356
+ });
357
+ });
358
+
359
+ test("routing replay exposes pure evaluation and canonical serialization", async () => {
360
+ const replayModule = await import("./replay-routing.mjs");
361
+ assert.equal(typeof replayModule.evaluateReplay, "function");
362
+ assert.equal(typeof replayModule.serializeReport, "function");
363
+
364
+ const report = replayModule.evaluateReplay({
365
+ scenarios: readJsonl(corpusPath),
366
+ observations: readJsonl(fixturesPath),
367
+ });
368
+ assert.equal(report.status, "pass");
369
+ assert.equal(
370
+ replayModule.serializeReport(report),
371
+ `${JSON.stringify(report, null, 2)}\n`,
372
+ );
373
+ });
374
+
375
+ test("routing replay emits the exact stable sanitized report contract", () => {
376
+ withReplayCopy((copy) => {
377
+ const first = runReplayWithoutOutput(copy);
378
+ const second = runReplayWithoutOutput(copy);
379
+ assert.equal(first.status, 0, first.stderr);
380
+ assert.equal(second.status, 0, second.stderr);
381
+ assert.equal(first.stdout, second.stdout);
382
+ assert.equal(first.stderr, "");
383
+ assert.equal(second.stderr, "");
384
+
385
+ const report = JSON.parse(first.stdout);
386
+ assert.deepEqual(Object.keys(report), [
387
+ "schema_version",
388
+ "corpus_digest",
389
+ "mode",
390
+ "operational_status",
391
+ "status",
392
+ "scenario_results",
393
+ ]);
394
+ assert.doesNotMatch(first.stdout, /timestamp/i);
395
+ assert.doesNotMatch(first.stdout, /\/Users\//);
396
+ assert.deepEqual(
397
+ report.scenario_results.map((result) => result.scenario_id),
398
+ report.scenario_results.map((result) => result.scenario_id).toSorted(),
399
+ );
400
+
401
+ for (const result of report.scenario_results) {
402
+ assert.deepEqual(Object.keys(result), [
403
+ "scenario_id",
404
+ "status",
405
+ "assertions",
406
+ "observed_agents",
407
+ "delegation_count",
408
+ "writes",
409
+ "review_sequence",
410
+ "observed_stop_condition",
411
+ "limitations",
412
+ ]);
413
+ assert.deepEqual(
414
+ result.assertions.map((item) => item.id),
415
+ assertionIds,
416
+ );
417
+ for (const item of result.assertions) {
418
+ assert.deepEqual(Object.keys(item), [
419
+ "id",
420
+ "status",
421
+ "reason_code",
422
+ "evidence_sequences",
423
+ ]);
424
+ assert.deepEqual(item.evidence_sequences, item.evidence_sequences.toSorted(
425
+ (left, right) => left - right,
426
+ ));
427
+ }
428
+ for (const write of result.writes) {
429
+ assert.deepEqual(Object.keys(write), ["sequence", "agent", "tool"]);
430
+ }
431
+ for (const review of result.review_sequence) {
432
+ assert.deepEqual(Object.keys(review), ["sequence", "agent", "verdict"]);
433
+ }
434
+ for (const limitation of result.limitations) {
435
+ assert.deepEqual(Object.keys(limitation), ["code", "channels"]);
436
+ assert.deepEqual(
437
+ limitation.channels,
438
+ coverageChannels.filter((channel) => limitation.channels.includes(channel)),
439
+ );
440
+ }
441
+ }
442
+
443
+ const observed = report.scenario_results.find(
444
+ (result) => result.scenario_id === "feature-technical-research",
445
+ );
446
+ assert.deepEqual(
447
+ observed.observed_agents,
448
+ ["lead", "researcher", "specifier", "developer", "reviewer"],
449
+ );
450
+ });
451
+ });
452
+
453
+ test("routing replay digest and report bytes are independent of corpus record order", () => {
454
+ withReplayCopy((copy) => {
455
+ const canonical = runReplayWithoutOutput(copy);
456
+ assert.equal(canonical.status, 0, canonical.stderr);
457
+
458
+ const scenarios = readJsonl(copy.corpus).reverse();
459
+ writeJsonl(copy.corpus, scenarios);
460
+ const reordered = runReplayWithoutOutput(copy);
461
+
462
+ assert.equal(reordered.status, 0, reordered.stderr);
463
+ assert.equal(reordered.stdout, canonical.stdout);
464
+ const canonicalCorpus = `${scenarios
465
+ .slice()
466
+ .sort((left, right) => left.id.localeCompare(right.id))
467
+ .map((scenario) => JSON.stringify(scenario))
468
+ .join("\n")}\n`;
469
+ assert.equal(
470
+ JSON.parse(reordered.stdout).corpus_digest,
471
+ `sha256:${createHash("sha256").update(canonicalCorpus).digest("hex")}`,
472
+ );
473
+ });
474
+ });
475
+
476
+ test("routing replay removes sensitive canaries from report and diagnostics", () => {
477
+ withReplayCopy((copy) => {
478
+ const canaries = [
479
+ "/private-owner/",
480
+ "provider-secret",
481
+ "model-secret",
482
+ "https://private.invalid",
483
+ "sk-secret",
484
+ "full private prompt",
485
+ "thinking secret",
486
+ ];
487
+ mutateScenario(copy, "public-sync-private-boundary", (scenario) => {
488
+ scenario.prompt = canaries.join(" ");
489
+ scenario.expected_root_agent = "model-secret";
490
+ scenario.required_agents[0] = "https://private.invalid";
491
+ scenario.expected_stop_condition = "thinking secret";
492
+ });
493
+ mutateFixture(copy, "public-sync-private-boundary", (fixture) => {
494
+ for (const event of fixture.events) {
495
+ if (event.session_id === "root") event.session_id = "/private-owner/";
496
+ if (event.parent_session_id === "root") {
497
+ event.parent_session_id = "/private-owner/";
498
+ }
499
+ if (event.agent === "lead") event.agent = "model-secret";
500
+ if (event.session_id === "s1") event.session_id = "sk-secret";
501
+ if (event.agent === "developer") event.agent = "https://private.invalid";
502
+ if (event.type === "stop_observed") event.condition = "thinking secret";
503
+ }
504
+ const write = fixture.events.find(
505
+ (event) => event.type === "tool_call_completed" && event.mutation === "write",
506
+ );
507
+ assert.ok(write, "fixture must contain a write");
508
+ write.tool = "provider-secret";
509
+ });
510
+
511
+ const result = runReplayWithoutOutput(copy);
512
+ assert.equal(result.status, 0, result.stderr);
513
+ const combined = `${result.stdout}\n${result.stderr}`;
514
+ for (const canary of canaries) {
515
+ assert.doesNotMatch(combined, new RegExp(escapeRegExp(canary), "i"));
516
+ }
517
+ });
518
+ });
519
+
520
+ test("routing replay emits limitations with only portable ordered fields", () => {
521
+ withReplayCopy((copy) => {
522
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
523
+ fixture.observation_coverage.skill_events = "partial";
524
+ fixture.observation_coverage.review_events = "unavailable";
525
+ insertBeforeStop(fixture, {
526
+ sequence: 0,
527
+ type: "run_error",
528
+ code: "capture-incomplete",
529
+ });
530
+ });
531
+
532
+ const result = runReplayWithoutOutput(copy);
533
+ assert.equal(result.status, 3, result.stderr);
534
+ const report = JSON.parse(result.stdout);
535
+ const scenario = report.scenario_results.find(
536
+ (candidate) => candidate.scenario_id === "freeform-tiny-direct-fix",
537
+ );
538
+ assert.deepEqual(scenario.limitations, [
539
+ {
540
+ code: "capture-incomplete",
541
+ channels: ["skill_events", "review_events"],
542
+ },
543
+ ]);
544
+ });
545
+ });
546
+
547
+ test("routing replay pseudonymizes sensitive scenario IDs and limitation codes", () => {
548
+ withReplayCopy((copy) => {
549
+ const originalId = "freeform-tiny-direct-fix";
550
+ const sensitiveId = "/private-owner/scenario";
551
+ mutateScenario(copy, originalId, (scenario) => {
552
+ scenario.id = sensitiveId;
553
+ });
554
+ mutateFixture(copy, originalId, (fixture) => {
555
+ fixture.scenario_id = sensitiveId;
556
+ fixture.observation_coverage.stop_events = "partial";
557
+ insertBeforeStop(fixture, {
558
+ sequence: 0,
559
+ type: "run_error",
560
+ code: "provider-secret",
561
+ });
562
+ });
563
+
564
+ const result = runReplayWithoutOutput(copy);
565
+ assert.equal(result.status, 3, result.stderr);
566
+ assert.doesNotMatch(result.stdout, /\/private-owner\/scenario|provider-secret/i);
567
+ const report = JSON.parse(result.stdout);
568
+ assert.deepEqual(
569
+ report.scenario_results.map((scenario) => scenario.scenario_id),
570
+ report.scenario_results.map((scenario) => scenario.scenario_id).toSorted(),
571
+ );
572
+ const redacted = report.scenario_results.find(
573
+ (scenario) => scenario.limitations.length > 0,
574
+ );
575
+ assert.match(redacted.scenario_id, /^redacted-scenario-\d+$/);
576
+ assert.match(redacted.limitations[0].code, /^redacted-code-\d+$/);
577
+ assert.ok(
578
+ report.scenario_results.some(
579
+ (scenario) => scenario.scenario_id === "freeform-ambiguous-clarify",
580
+ ),
581
+ "normal scenario IDs must remain unchanged",
582
+ );
583
+ });
584
+ });
585
+
586
+ test("routing replay preserves distinct sensitive agent identities in first-seen order", () => {
587
+ withReplayCopy((copy) => {
588
+ const firstAgent = "/private-owner/agent-a";
589
+ const secondAgent = "https://private.invalid/agent-b";
590
+ mutateScenario(copy, "freeform-tiny-direct-fix", (scenario) => {
591
+ scenario.required_agents = [firstAgent, secondAgent];
592
+ scenario.maximum_delegation_budget = 3;
593
+ });
594
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
595
+ for (const event of fixture.events) {
596
+ if (event.agent === "developer") event.agent = firstAgent;
597
+ }
598
+ addSession(fixture, { sessionId: "s2", agent: secondAgent });
599
+ addSession(fixture, { sessionId: "s3", agent: firstAgent });
600
+ insertBeforeStop(fixture, {
601
+ sequence: 0,
602
+ type: "tool_call_completed",
603
+ session_id: "s1",
604
+ agent: firstAgent,
605
+ tool: "apply_patch",
606
+ mutation: "write",
607
+ });
608
+ });
609
+
610
+ const result = runReplayWithoutOutput(copy);
611
+ const repeated = runReplayWithoutOutput(copy);
612
+ assert.equal(result.status, 0, result.stderr);
613
+ assert.equal(repeated.status, 0, repeated.stderr);
614
+ assert.equal(repeated.stdout, result.stdout);
615
+ assert.doesNotMatch(result.stdout, /private-owner|private\.invalid/i);
616
+ const report = JSON.parse(result.stdout);
617
+ const scenario = report.scenario_results.find(
618
+ (candidate) => candidate.scenario_id === "freeform-tiny-direct-fix",
619
+ );
620
+ assert.equal(new Set(scenario.observed_agents).size, scenario.observed_agents.length);
621
+ assert.equal(scenario.observed_agents[0], "lead");
622
+ assert.match(scenario.observed_agents[1], /^redacted-agent-\d+$/);
623
+ assert.match(scenario.observed_agents[2], /^redacted-agent-\d+$/);
624
+ assert.notEqual(scenario.observed_agents[1], scenario.observed_agents[2]);
625
+ assert.equal(scenario.writes[0].agent, scenario.observed_agents[1]);
626
+ });
627
+ });
628
+
629
+ test("routing replay writes --output as a regular mode-0600 file", () => {
630
+ withReplayCopy((copy) => {
631
+ const result = runReplayWithOutput(copy, copy.report);
632
+ assert.equal(result.status, 0, result.stderr);
633
+ const stat = fs.lstatSync(copy.report);
634
+ assert.ok(stat.isFile());
635
+ assert.equal(stat.mode & 0o777, 0o600);
636
+ assert.equal(fs.readFileSync(copy.report, "utf8"), result.stdout);
637
+ });
638
+ });
639
+
640
+ test("routing replay CLI executes from a script path containing spaces", () => {
641
+ withReplayCopy((copy) => {
642
+ const spacedDirectory = path.join(copy.cwd, "runner with spaces");
643
+ const spacedRunner = path.join(spacedDirectory, "replay routing.mjs");
644
+ fs.mkdirSync(spacedDirectory);
645
+ fs.copyFileSync(runnerPath, spacedRunner);
646
+
647
+ const result = spawnSync(
648
+ process.execPath,
649
+ [
650
+ spacedRunner,
651
+ "--corpus",
652
+ copy.corpus,
653
+ "--fixtures",
654
+ copy.fixtures,
655
+ ],
656
+ { cwd: copy.cwd, encoding: "utf8" },
657
+ );
658
+
659
+ assert.equal(result.status, 0, result.stderr);
660
+ assert.equal(JSON.parse(result.stdout).status, "pass");
661
+ });
662
+ });
663
+
664
+ test("routing replay rejects a symlink --output without touching its target", () => {
665
+ withReplayCopy((copy) => {
666
+ const target = path.join(copy.cwd, "target.json");
667
+ fs.writeFileSync(target, "sentinel\n", { mode: 0o600 });
668
+ fs.symlinkSync(target, copy.report);
669
+
670
+ const result = runReplayWithOutput(copy, copy.report);
671
+ assert.equal(result.status, 2, result.stderr);
672
+ assert.equal(result.stdout, "");
673
+ assert.equal(fs.readFileSync(target, "utf8"), "sentinel\n");
674
+ assert.match(result.stderr, /ReplayInputError: output: line 1 path must not be a symlink/);
675
+ assert.doesNotMatch(result.stderr, /runner internal error|node:internal|\n\s+at /);
676
+ });
677
+ });
678
+
679
+ test("routing replay rejects --output whose parent does not exist", () => {
680
+ withReplayCopy((copy) => {
681
+ const output = path.join(copy.cwd, "missing", "report.json");
682
+ const result = runReplayWithOutput(copy, output);
683
+ assert.equal(result.status, 2, result.stderr);
684
+ assert.equal(result.stdout, "");
685
+ assert.ok(!fs.existsSync(output));
686
+ assert.match(
687
+ result.stderr,
688
+ /ReplayInputError: output: line 1 parent must be an existing directory/,
689
+ );
690
+ assert.doesNotMatch(result.stderr, /runner internal error|node:internal|\n\s+at /);
691
+ });
692
+ });
693
+
694
+ test("routing replay rejects a non-regular --output path", () => {
695
+ withReplayCopy((copy) => {
696
+ fs.mkdirSync(copy.report);
697
+ const result = runReplayWithOutput(copy, copy.report);
698
+ assert.equal(result.status, 2, result.stderr);
699
+ assert.equal(result.stdout, "");
700
+ assert.match(
701
+ result.stderr,
702
+ /ReplayInputError: output: line 1 path must be a regular file/,
703
+ );
704
+ assert.doesNotMatch(result.stderr, /runner internal error|node:internal|\n\s+at /);
705
+ });
706
+ });
707
+
708
+ test("routing replay leaves no partial report when input fails before results", () => {
709
+ withReplayCopy((copy) => {
710
+ fs.writeFileSync(copy.report, "previous-report\n", { mode: 0o600 });
711
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
712
+ fixture.extra = true;
713
+ });
714
+
715
+ const result = runReplayWithOutput(copy, copy.report);
716
+ assert.equal(result.status, 2, result.stderr);
717
+ assert.equal(result.stdout, "");
718
+ assert.equal(fs.readFileSync(copy.report, "utf8"), "previous-report\n");
719
+ assert.doesNotMatch(result.stderr, /runner internal error|node:internal|\n\s+at /);
720
+ });
721
+ });
722
+
723
+ const shapeCases = [
724
+ {
725
+ name: "missing required top-level fixture key",
726
+ scenarioId: "freeform-tiny-direct-fix",
727
+ field: "git_snapshot",
728
+ reason: "missing field",
729
+ mutate(fixture) {
730
+ delete fixture.git_snapshot;
731
+ },
732
+ },
733
+ {
734
+ name: "unknown top-level fixture key",
735
+ scenarioId: "freeform-tiny-direct-fix",
736
+ field: "extra",
737
+ reason: "unknown field",
738
+ mutate(fixture) {
739
+ fixture.extra = true;
740
+ },
741
+ },
742
+ {
743
+ name: "missing coverage channel",
744
+ scenarioId: "freeform-tiny-direct-fix",
745
+ field: "observation_coverage.stop_events",
746
+ reason: "missing field",
747
+ mutate(fixture) {
748
+ delete fixture.observation_coverage.stop_events;
749
+ },
750
+ },
751
+ {
752
+ name: "unknown coverage enum",
753
+ scenarioId: "freeform-tiny-direct-fix",
754
+ field: "observation_coverage.stop_events",
755
+ reason: "unknown value",
756
+ mutate(fixture) {
757
+ fixture.observation_coverage.stop_events = "opaque";
758
+ },
759
+ },
760
+ {
761
+ name: "duplicate scenario_id",
762
+ scenarioId: "freeform-ambiguous-clarify",
763
+ field: "scenario_id",
764
+ reason: "duplicate value freeform-tiny-direct-fix",
765
+ mutate(fixture, fixtures) {
766
+ fixture.scenario_id = fixtureFor(fixtures, "freeform-tiny-direct-fix").scenario_id;
767
+ },
768
+ },
769
+ {
770
+ name: "unknown scenario_id",
771
+ scenarioId: "freeform-tiny-direct-fix",
772
+ field: "scenario_id",
773
+ reason: "unknown value unknown-scenario",
774
+ mutate(fixture) {
775
+ fixture.scenario_id = "unknown-scenario";
776
+ },
777
+ },
778
+ {
779
+ name: "missing scenario_id from fixture set",
780
+ scenarioId: "optional-integration-unavailable",
781
+ field: "scenario_id",
782
+ reason: "missing value optional-integration-unavailable",
783
+ missingSetEntry: true,
784
+ mutate(fixture, fixtures) {
785
+ fixtures.splice(fixtures.findIndex((candidate) => candidate === fixture), 1);
786
+ },
787
+ },
788
+ {
789
+ name: "duplicate event sequence",
790
+ scenarioId: "freeform-tiny-direct-fix",
791
+ field: "events[1].sequence",
792
+ reason: "must be strictly increasing",
793
+ mutate(fixture) {
794
+ fixture.events[1].sequence = fixture.events[0].sequence;
795
+ },
796
+ },
797
+ {
798
+ name: "non-increasing event sequence",
799
+ scenarioId: "freeform-tiny-direct-fix",
800
+ field: "events[2].sequence",
801
+ reason: "must be strictly increasing",
802
+ mutate(fixture) {
803
+ fixture.events[2].sequence = 1;
804
+ },
805
+ },
806
+ {
807
+ name: "unknown deterministic event type",
808
+ scenarioId: "freeform-tiny-direct-fix",
809
+ field: "events[1].type",
810
+ reason: "unknown value mystery_event",
811
+ mutate(fixture) {
812
+ fixture.events[1].type = "mystery_event";
813
+ },
814
+ },
815
+ {
816
+ name: "unknown deterministic event key",
817
+ scenarioId: "freeform-tiny-direct-fix",
818
+ field: "events[0].private",
819
+ reason: "unknown field",
820
+ mutate(fixture) {
821
+ fixture.events[0].private = true;
822
+ },
823
+ },
824
+ {
825
+ name: "missing required event key",
826
+ scenarioId: "freeform-tiny-direct-fix",
827
+ field: "events[0].agent",
828
+ reason: "missing field",
829
+ mutate(fixture) {
830
+ delete fixture.events[0].agent;
831
+ },
832
+ },
833
+ {
834
+ name: "missing parent session",
835
+ scenarioId: "freeform-tiny-direct-fix",
836
+ field: "events[1].parent_session_id",
837
+ reason: "unknown session missing-parent",
838
+ mutate(fixture) {
839
+ fixture.events[1].parent_session_id = "missing-parent";
840
+ },
841
+ },
842
+ {
843
+ name: "duplicate session",
844
+ scenarioId: "freeform-tiny-direct-fix",
845
+ field: "events[2].session_id",
846
+ reason: "duplicate session s1",
847
+ mutate(fixture) {
848
+ fixture.events.splice(2, 0, clone(fixture.events[1]));
849
+ resequence(fixture.events);
850
+ },
851
+ },
852
+ {
853
+ name: "completed-agent mismatch",
854
+ scenarioId: "freeform-tiny-direct-fix",
855
+ field: "events[2].agent",
856
+ reason: "does not match started agent developer",
857
+ mutate(fixture) {
858
+ fixture.events[2].agent = "reviewer";
859
+ },
860
+ },
861
+ ];
862
+
863
+ for (const shapeCase of shapeCases) {
864
+ test(`runner rejects ${shapeCase.name} with a stable diagnostic`, () => {
865
+ withReplayCopy((copy) => {
866
+ const fixtures = readJsonl(copy.fixtures);
867
+ const fixture = fixtureFor(fixtures, shapeCase.scenarioId);
868
+ shapeCase.mutate(fixture, fixtures);
869
+ const line = shapeCase.missingSetEntry
870
+ ? fixtures.length + 1
871
+ : fixtures.findIndex((candidate) => candidate === fixture) + 1;
872
+ assert.ok(line > 0, `cannot locate mutated fixture ${shapeCase.scenarioId}`);
873
+ writeJsonl(copy.fixtures, fixtures);
874
+ expectInputError(copy, line, shapeCase.field, shapeCase.reason);
875
+ });
876
+ });
877
+ }
878
+
879
+ for (const malformed of [
880
+ { name: "primitive", value: 7 },
881
+ { name: "null", value: null },
882
+ { name: "array", value: [] },
883
+ ]) {
884
+ test(`runner rejects a JSONL ${malformed.name} record`, () => {
885
+ withReplayCopy((copy) => {
886
+ const fixtures = readJsonl(copy.fixtures);
887
+ const fixture = fixtureFor(fixtures, "freeform-tiny-direct-fix");
888
+ const line = fixtures.findIndex((candidate) => candidate === fixture) + 1;
889
+ const lines = fs.readFileSync(copy.fixtures, "utf8").trimEnd().split("\n");
890
+ lines[line - 1] = JSON.stringify(malformed.value);
891
+ fs.writeFileSync(copy.fixtures, `${lines.join("\n")}\n`);
892
+ expectInputError(copy, line, "record", "must be an object");
893
+ });
894
+ });
895
+ }
896
+
897
+ test("runner rejects malformed JSONL syntax", () => {
898
+ withReplayCopy((copy) => {
899
+ const fixtures = readJsonl(copy.fixtures);
900
+ const fixture = fixtureFor(fixtures, "freeform-tiny-direct-fix");
901
+ const line = fixtures.findIndex((candidate) => candidate === fixture) + 1;
902
+ const lines = fs.readFileSync(copy.fixtures, "utf8").trimEnd().split("\n");
903
+ lines[line - 1] = '{"schema_version":1';
904
+ fs.writeFileSync(copy.fixtures, `${lines.join("\n")}\n`);
905
+ expectInputError(copy, line, "record", "invalid JSON");
906
+ });
907
+ });
908
+
909
+ test("runner rejects non-portable run_error.code without echoing its value", () => {
910
+ withReplayCopy((copy) => {
911
+ const sensitiveCode = "/private-user/session-secret";
912
+ const fixtures = readJsonl(copy.fixtures);
913
+ const fixture = fixtureFor(fixtures, "freeform-tiny-direct-fix");
914
+ const line = fixtures.findIndex((candidate) => candidate === fixture) + 1;
915
+ insertBeforeStop(fixture, {
916
+ sequence: 0,
917
+ type: "run_error",
918
+ code: sensitiveCode,
919
+ });
920
+ const eventIndex = fixture.events.findIndex(
921
+ (event) => event.type === "run_error",
922
+ );
923
+ writeJsonl(copy.fixtures, fixtures);
924
+
925
+ const result = runReplay(copy);
926
+ assert.equal(result.status, 2, result.stderr);
927
+ assert.equal(result.report, null);
928
+ assert.match(
929
+ result.stderr,
930
+ new RegExp(
931
+ `${escapeRegExp(copy.fixtures)}: line ${line} `
932
+ + `events\\[${eventIndex}\\]\\.code invalid portable identifier`,
933
+ ),
934
+ );
935
+ assert.doesNotMatch(result.stdout, new RegExp(escapeRegExp(sensitiveCode)));
936
+ assert.doesNotMatch(result.stderr, new RegExp(escapeRegExp(sensitiveCode)));
937
+ });
938
+ });
939
+
940
+ test("runner reports an unreadable corpus as a ReplayInputError", () => {
941
+ withReplayCopy((copy) => {
942
+ fs.rmSync(copy.corpus);
943
+ const result = runReplay(copy);
944
+
945
+ assert.equal(result.status, 2, result.stderr);
946
+ assert.equal(result.report, null);
947
+ assert.match(
948
+ result.stderr,
949
+ new RegExp(`${escapeRegExp(copy.corpus)}: line 1 record unable to read`),
950
+ );
951
+ assert.doesNotMatch(result.stderr, /runner internal error|at file:|node:internal/);
952
+ });
953
+ });
954
+
955
+ const verdictCases = [
956
+ {
957
+ name: "wrong root",
958
+ scenarioId: "freeform-tiny-direct-fix",
959
+ assertionId: "root-agent",
960
+ reasonCode: "unexpected-root-agent",
961
+ mutate(copy) {
962
+ mutateFixture(copy, this.scenarioId, (fixture) => {
963
+ fixture.events[0].agent = "developer";
964
+ });
965
+ },
966
+ },
967
+ {
968
+ name: "missing required agent",
969
+ scenarioId: "feature-technical-research",
970
+ assertionId: "required-agents",
971
+ reasonCode: "required-agent-missing",
972
+ mutate(copy) {
973
+ mutateFixture(copy, this.scenarioId, (fixture) => removeAgentEvents(fixture, "researcher"));
974
+ },
975
+ },
976
+ {
977
+ name: "out-of-order required agents",
978
+ scenarioId: "feature-technical-research",
979
+ assertionId: "required-agents",
980
+ reasonCode: "required-agent-order-mismatch",
981
+ mutate(copy) {
982
+ mutateFixture(copy, this.scenarioId, (fixture) => {
983
+ for (const event of fixture.events) {
984
+ if (event.agent === "researcher") event.agent = "specifier";
985
+ else if (event.agent === "specifier") event.agent = "researcher";
986
+ }
987
+ });
988
+ },
989
+ },
990
+ {
991
+ name: "forbidden agent",
992
+ scenarioId: "freeform-tiny-direct-fix",
993
+ assertionId: "forbidden-agents",
994
+ reasonCode: "forbidden-agent-observed",
995
+ mutate(copy) {
996
+ mutateFixture(copy, this.scenarioId, (fixture) => {
997
+ addSession(fixture, { sessionId: "s2", agent: "evolver" });
998
+ });
999
+ },
1000
+ },
1001
+ {
1002
+ name: "forbidden skill",
1003
+ scenarioId: "freeform-tiny-direct-fix",
1004
+ assertionId: "skills",
1005
+ reasonCode: "forbidden-skill-observed",
1006
+ mutate(copy) {
1007
+ mutateScenario(copy, this.scenarioId, (scenario) => {
1008
+ scenario.forbidden_skills = ["danger-skill"];
1009
+ });
1010
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1011
+ insertBeforeStop(fixture, {
1012
+ sequence: 0,
1013
+ type: "skill_selected",
1014
+ session_id: "root",
1015
+ agent: "lead",
1016
+ skill: "danger-skill",
1017
+ });
1018
+ });
1019
+ },
1020
+ },
1021
+ {
1022
+ name: "skill outside allowlist",
1023
+ scenarioId: "public-sync-private-boundary",
1024
+ assertionId: "skills",
1025
+ reasonCode: "skill-not-allowed",
1026
+ mutate(copy) {
1027
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1028
+ insertBeforeStop(fixture, {
1029
+ sequence: 0,
1030
+ type: "skill_selected",
1031
+ session_id: "root",
1032
+ agent: "lead",
1033
+ skill: "unlisted-skill",
1034
+ });
1035
+ });
1036
+ },
1037
+ },
1038
+ {
1039
+ name: "skill when allowlist is empty",
1040
+ scenarioId: "freeform-tiny-direct-fix",
1041
+ assertionId: "skills",
1042
+ reasonCode: "skill-not-allowed",
1043
+ mutate(copy) {
1044
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1045
+ insertBeforeStop(fixture, {
1046
+ sequence: 0,
1047
+ type: "skill_selected",
1048
+ session_id: "root",
1049
+ agent: "lead",
1050
+ skill: "unexpected-skill",
1051
+ });
1052
+ });
1053
+ },
1054
+ },
1055
+ {
1056
+ name: "premature write",
1057
+ scenarioId: "feature-technical-research",
1058
+ assertionId: "write-before-spec",
1059
+ reasonCode: "write-before-spec-completed",
1060
+ mutate(copy) {
1061
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1062
+ fixture.events.splice(2, 0, {
1063
+ sequence: 0,
1064
+ type: "tool_call_completed",
1065
+ session_id: "s1",
1066
+ agent: "researcher",
1067
+ tool: "apply_patch",
1068
+ mutation: "write",
1069
+ });
1070
+ resequence(fixture.events);
1071
+ });
1072
+ },
1073
+ },
1074
+ {
1075
+ name: "write in not-applicable scenario",
1076
+ scenarioId: "validation-failure-blocks-close",
1077
+ assertionId: "write-before-spec",
1078
+ reasonCode: "write-observed-when-not-applicable",
1079
+ mutate(copy) {
1080
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1081
+ insertBeforeStop(fixture, {
1082
+ sequence: 0,
1083
+ type: "tool_call_completed",
1084
+ session_id: "s1",
1085
+ agent: "debugger",
1086
+ tool: "apply_patch",
1087
+ mutation: "write",
1088
+ });
1089
+ });
1090
+ },
1091
+ },
1092
+ {
1093
+ name: "required review absent",
1094
+ scenarioId: "plan-ambiguous-task-contract",
1095
+ assertionId: "review-policy",
1096
+ reasonCode: "required-review-missing",
1097
+ mutate(copy) {
1098
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1099
+ fixture.events = fixture.events.filter((event) => event.type !== "review_completed");
1100
+ resequence(fixture.events);
1101
+ });
1102
+ },
1103
+ },
1104
+ {
1105
+ name: "write after review",
1106
+ scenarioId: "public-sync-private-boundary",
1107
+ assertionId: "review-policy",
1108
+ reasonCode: "write-after-review",
1109
+ mutate(copy) {
1110
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1111
+ insertBeforeStop(fixture, {
1112
+ sequence: 0,
1113
+ type: "tool_call_completed",
1114
+ session_id: "root",
1115
+ agent: "lead",
1116
+ tool: "apply_patch",
1117
+ mutation: "write",
1118
+ });
1119
+ });
1120
+ },
1121
+ },
1122
+ {
1123
+ name: "reviewer when forbidden",
1124
+ scenarioId: "freeform-ambiguous-clarify",
1125
+ assertionId: "review-policy",
1126
+ reasonCode: "reviewer-forbidden",
1127
+ mutate(copy) {
1128
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1129
+ addSession(fixture, { sessionId: "s1", agent: "reviewer" });
1130
+ });
1131
+ },
1132
+ },
1133
+ {
1134
+ name: "delegation budget exceeded by repeated sessions",
1135
+ scenarioId: "freeform-tiny-direct-fix",
1136
+ assertionId: "delegation-budget",
1137
+ reasonCode: "delegation-budget-exceeded",
1138
+ mutate(copy) {
1139
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1140
+ addSession(fixture, { sessionId: "s2", agent: "developer" });
1141
+ });
1142
+ },
1143
+ },
1144
+ {
1145
+ name: "wrong stop",
1146
+ scenarioId: "freeform-tiny-direct-fix",
1147
+ assertionId: "stop-condition",
1148
+ reasonCode: "unexpected-stop-condition",
1149
+ mutate(copy) {
1150
+ mutateFixture(copy, this.scenarioId, (fixture) => {
1151
+ fixture.events.at(-1).condition = "clarification-required";
1152
+ });
1153
+ },
1154
+ },
1155
+ ];
1156
+
1157
+ for (const verdictCase of verdictCases) {
1158
+ test(`observable violation: ${verdictCase.name}`, () => {
1159
+ withReplayCopy((copy) => {
1160
+ verdictCase.mutate(copy);
1161
+ expectVerdict(copy, {
1162
+ exitCode: 1,
1163
+ overallStatus: "fail",
1164
+ scenarioId: verdictCase.scenarioId,
1165
+ assertionId: verdictCase.assertionId,
1166
+ assertionStatus: "fail",
1167
+ reasonCode: verdictCase.reasonCode,
1168
+ });
1169
+ });
1170
+ });
1171
+ }
1172
+
1173
+ test("multiple stops report the first wrong stop before an expected stop", () => {
1174
+ withReplayCopy((copy) => {
1175
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
1176
+ const expectedIndex = fixture.events.findIndex(
1177
+ (event) => event.type === "stop_observed",
1178
+ );
1179
+ fixture.events.splice(expectedIndex, 0, {
1180
+ sequence: 0,
1181
+ type: "stop_observed",
1182
+ condition: "clarification-required",
1183
+ });
1184
+ resequence(fixture.events);
1185
+ });
1186
+
1187
+ const result = runReplay(copy);
1188
+ assert.equal(result.status, 1, result.stderr);
1189
+ const scenario = result.report.scenario_results.find(
1190
+ (candidate) => candidate.scenario_id === "freeform-tiny-direct-fix",
1191
+ );
1192
+ const stopAssertion = scenario.assertions.find(
1193
+ (assertion) => assertion.id === "stop-condition",
1194
+ );
1195
+ assert.equal(scenario.observed_stop_condition, "clarification-required");
1196
+ assert.equal(stopAssertion.status, "fail");
1197
+ assert.equal(stopAssertion.reason_code, "unexpected-stop-condition");
1198
+ assert.deepEqual(stopAssertion.evidence_sequences, [4]);
1199
+ });
1200
+ });
1201
+
1202
+ test("multiple stops report the first expected stop before a later wrong stop", () => {
1203
+ withReplayCopy((copy) => {
1204
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
1205
+ fixture.events.push({
1206
+ sequence: 0,
1207
+ type: "stop_observed",
1208
+ condition: "clarification-required",
1209
+ });
1210
+ resequence(fixture.events);
1211
+ });
1212
+
1213
+ const result = runReplay(copy);
1214
+ assert.equal(result.status, 1, result.stderr);
1215
+ const scenario = result.report.scenario_results.find(
1216
+ (candidate) => candidate.scenario_id === "freeform-tiny-direct-fix",
1217
+ );
1218
+ const stopAssertion = scenario.assertions.find(
1219
+ (assertion) => assertion.id === "stop-condition",
1220
+ );
1221
+ assert.equal(scenario.observed_stop_condition, "task-completed");
1222
+ assert.equal(stopAssertion.status, "fail");
1223
+ assert.equal(stopAssertion.reason_code, "unexpected-stop-condition");
1224
+ assert.deepEqual(stopAssertion.evidence_sequences, [5]);
1225
+ });
1226
+ });
1227
+
1228
+ const reviewOrderingCases = [
1229
+ {
1230
+ name: "required review with unknown mutation after review",
1231
+ policy: "required",
1232
+ mutation: "unknown-after",
1233
+ exitCode: 3,
1234
+ status: "inconclusive",
1235
+ reasonCode: "write-order-unknown-after-review",
1236
+ },
1237
+ {
1238
+ name: "optional review with unknown mutation after review",
1239
+ policy: "optional",
1240
+ mutation: "unknown-after",
1241
+ exitCode: 3,
1242
+ status: "inconclusive",
1243
+ reasonCode: "write-order-unknown-after-review",
1244
+ },
1245
+ {
1246
+ name: "required review with unknown mutation before review",
1247
+ policy: "required",
1248
+ mutation: "unknown-before",
1249
+ exitCode: 0,
1250
+ status: "pass",
1251
+ reasonCode: "required-review-completed",
1252
+ },
1253
+ {
1254
+ name: "optional review with unknown mutation before review",
1255
+ policy: "optional",
1256
+ mutation: "unknown-before",
1257
+ exitCode: 0,
1258
+ status: "pass",
1259
+ reasonCode: "optional-review-order-satisfied",
1260
+ },
1261
+ {
1262
+ name: "required review with unsequenced Git mutation",
1263
+ policy: "required",
1264
+ mutation: "git-changed",
1265
+ exitCode: 3,
1266
+ status: "inconclusive",
1267
+ reasonCode: "git-write-unsequenced",
1268
+ },
1269
+ {
1270
+ name: "optional review with unsequenced Git mutation",
1271
+ policy: "optional",
1272
+ mutation: "git-changed",
1273
+ exitCode: 3,
1274
+ status: "inconclusive",
1275
+ reasonCode: "git-write-unsequenced",
1276
+ },
1277
+ {
1278
+ name: "optional write after review with partial review evidence",
1279
+ policy: "optional",
1280
+ mutation: "write-after",
1281
+ reviewCoverage: "partial",
1282
+ exitCode: 3,
1283
+ status: "inconclusive",
1284
+ reasonCode: "review-events-incomplete",
1285
+ },
1286
+ {
1287
+ name: "optional write after review with complete review evidence",
1288
+ policy: "optional",
1289
+ mutation: "write-after",
1290
+ reviewCoverage: "complete",
1291
+ exitCode: 1,
1292
+ status: "fail",
1293
+ reasonCode: "write-after-review",
1294
+ },
1295
+ {
1296
+ name: "required write after review with partial review evidence",
1297
+ policy: "required",
1298
+ mutation: "write-after",
1299
+ reviewCoverage: "partial",
1300
+ exitCode: 3,
1301
+ status: "inconclusive",
1302
+ reasonCode: "review-or-tool-events-incomplete",
1303
+ },
1304
+ {
1305
+ name: "required write after review with complete review evidence",
1306
+ policy: "required",
1307
+ mutation: "write-after",
1308
+ reviewCoverage: "complete",
1309
+ exitCode: 1,
1310
+ status: "fail",
1311
+ reasonCode: "write-after-review",
1312
+ },
1313
+ ];
1314
+
1315
+ for (const reviewCase of reviewOrderingCases) {
1316
+ test(`review ordering: ${reviewCase.name}`, () => {
1317
+ withReplayCopy((copy) => {
1318
+ mutateScenario(copy, "plan-ambiguous-task-contract", (scenario) => {
1319
+ scenario.review_policy = reviewCase.policy;
1320
+ scenario.write_before_spec_policy = "allowed";
1321
+ });
1322
+ mutateFixture(copy, "plan-ambiguous-task-contract", (fixture) => {
1323
+ if (reviewCase.reviewCoverage !== undefined) {
1324
+ fixture.observation_coverage.review_events = reviewCase.reviewCoverage;
1325
+ }
1326
+ if (reviewCase.mutation === "git-changed") {
1327
+ fixture.git_snapshot = "changed";
1328
+ return;
1329
+ }
1330
+ const reviewIndex = fixture.events.findIndex(
1331
+ (event) => event.type === "review_completed",
1332
+ );
1333
+ const event = {
1334
+ sequence: 0,
1335
+ type: "tool_call_completed",
1336
+ session_id: "s3",
1337
+ agent: "reviewer",
1338
+ tool: "apply_patch",
1339
+ mutation: reviewCase.mutation === "write-after" ? "write" : "unknown",
1340
+ };
1341
+ const insertionIndex = reviewCase.mutation === "unknown-before"
1342
+ ? reviewIndex
1343
+ : reviewIndex + 1;
1344
+ fixture.events.splice(insertionIndex, 0, event);
1345
+ resequence(fixture.events);
1346
+ });
1347
+
1348
+ const result = runReplay(copy);
1349
+ assert.equal(result.status, reviewCase.exitCode, result.stderr);
1350
+ const scenario = result.report.scenario_results.find(
1351
+ (candidate) => candidate.scenario_id === "plan-ambiguous-task-contract",
1352
+ );
1353
+ const reviewAssertion = scenario.assertions.find(
1354
+ (assertion) => assertion.id === "review-policy",
1355
+ );
1356
+ assert.equal(scenario.status, reviewCase.status);
1357
+ assert.equal(reviewAssertion.status, reviewCase.status);
1358
+ assert.equal(reviewAssertion.reason_code, reviewCase.reasonCode);
1359
+ });
1360
+ });
1361
+ }
1362
+
1363
+ test("missing required-agent evidence is inconclusive", () => {
1364
+ withReplayCopy((copy) => {
1365
+ mutateFixture(copy, "feature-technical-research", (fixture) => {
1366
+ removeAgentEvents(fixture, "researcher");
1367
+ fixture.observation_coverage.session_events = "partial";
1368
+ });
1369
+ expectVerdict(copy, {
1370
+ exitCode: 3,
1371
+ overallStatus: "inconclusive",
1372
+ scenarioId: "feature-technical-research",
1373
+ assertionId: "required-agents",
1374
+ assertionStatus: "inconclusive",
1375
+ reasonCode: "session-events-incomplete",
1376
+ });
1377
+ });
1378
+ });
1379
+
1380
+ for (const coverage of ["partial", "unavailable"]) {
1381
+ test(`wrong root with ${coverage} session evidence is inconclusive`, () => {
1382
+ withReplayCopy((copy) => {
1383
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
1384
+ fixture.events[0].agent = "developer";
1385
+ fixture.observation_coverage.session_events = coverage;
1386
+ });
1387
+ expectVerdict(copy, {
1388
+ exitCode: 3,
1389
+ overallStatus: "inconclusive",
1390
+ scenarioId: "freeform-tiny-direct-fix",
1391
+ assertionId: "root-agent",
1392
+ assertionStatus: "inconclusive",
1393
+ reasonCode: "session-events-incomplete",
1394
+ });
1395
+ });
1396
+ });
1397
+ }
1398
+
1399
+ test("unobservable skill selection is inconclusive", () => {
1400
+ withReplayCopy((copy) => {
1401
+ mutateFixture(copy, "public-sync-private-boundary", (fixture) => {
1402
+ fixture.observation_coverage.skill_events = "partial";
1403
+ });
1404
+ expectVerdict(copy, {
1405
+ exitCode: 3,
1406
+ overallStatus: "inconclusive",
1407
+ scenarioId: "public-sync-private-boundary",
1408
+ assertionId: "skills",
1409
+ assertionStatus: "inconclusive",
1410
+ reasonCode: "skill-events-incomplete",
1411
+ });
1412
+ });
1413
+ });
1414
+
1415
+ test("unknown relevant mutation is inconclusive", () => {
1416
+ withReplayCopy((copy) => {
1417
+ mutateFixture(copy, "feature-technical-research", (fixture) => {
1418
+ fixture.events.splice(2, 0, {
1419
+ sequence: 0,
1420
+ type: "tool_call_completed",
1421
+ session_id: "s1",
1422
+ agent: "researcher",
1423
+ tool: "unknown-tool",
1424
+ mutation: "unknown",
1425
+ });
1426
+ resequence(fixture.events);
1427
+ });
1428
+ expectVerdict(copy, {
1429
+ exitCode: 3,
1430
+ overallStatus: "inconclusive",
1431
+ scenarioId: "feature-technical-research",
1432
+ assertionId: "write-before-spec",
1433
+ assertionStatus: "inconclusive",
1434
+ reasonCode: "write-mutation-unknown",
1435
+ });
1436
+ });
1437
+ });
1438
+
1439
+ test("missing stop evidence is inconclusive", () => {
1440
+ withReplayCopy((copy) => {
1441
+ mutateFixture(copy, "freeform-tiny-direct-fix", (fixture) => {
1442
+ fixture.events = fixture.events.filter((event) => event.type !== "stop_observed");
1443
+ resequence(fixture.events);
1444
+ });
1445
+ expectVerdict(copy, {
1446
+ exitCode: 3,
1447
+ overallStatus: "inconclusive",
1448
+ scenarioId: "freeform-tiny-direct-fix",
1449
+ assertionId: "stop-condition",
1450
+ assertionStatus: "inconclusive",
1451
+ reasonCode: "stop-not-observed",
1452
+ });
1453
+ });
1454
+ });