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.
@@ -35,6 +35,35 @@ function write(rel, content, cwd) {
35
35
  fs.writeFileSync(path.join(cwd, rel), content);
36
36
  }
37
37
 
38
+ function canonicalRouterScenario(overrides = {}) {
39
+ return {
40
+ schema_version: 1,
41
+ id: "test-router-scenario",
42
+ category: "trivial",
43
+ prompt: "Apply a small direct fix.",
44
+ command_path: "freeform",
45
+ expected_root_agent: "lead",
46
+ required_agents: ["developer"],
47
+ forbidden_agents: ["evolver"],
48
+ allowed_skills: [],
49
+ forbidden_skills: [],
50
+ write_before_spec_policy: "allowed",
51
+ review_policy: "optional",
52
+ expected_stop_condition: "task-completed",
53
+ maximum_delegation_budget: 1,
54
+ required_evidence: ["static_contract"],
55
+ ...overrides,
56
+ };
57
+ }
58
+
59
+ function writeRouterScenarios(cwd, scenarios) {
60
+ write(
61
+ "docs/ai/evolution/benchmarks/router-scenarios.jsonl",
62
+ `${scenarios.map((scenario) => JSON.stringify(scenario)).join("\n")}\n`,
63
+ cwd,
64
+ );
65
+ }
66
+
38
67
  const validLoopCommand = `---
39
68
  description: Run a bounded and verifiable engineering loop.
40
69
  agent: lead
@@ -65,6 +94,98 @@ test("harness accepts prose evidence that mentions markdown filenames", () => {
65
94
  }
66
95
  });
67
96
 
97
+ test("routing replay surface rejects a missing deterministic runner", () => {
98
+ const cwd = makeFixture();
99
+ try {
100
+ fs.rmSync(path.join(cwd, "scripts/replay-routing.mjs"));
101
+ const result = runHarness(cwd);
102
+ assert.notEqual(result.status, 0, "checker accepted a missing replay runner");
103
+ assert.match(result.stderr, /scripts\/replay-routing\.mjs: missing regular file/);
104
+ } finally {
105
+ fs.rmSync(cwd, { recursive: true, force: true });
106
+ }
107
+ });
108
+
109
+ test("routing replay surface rejects a missing metrics aggregator", () => {
110
+ const cwd = makeFixture();
111
+ try {
112
+ fs.rmSync(path.join(cwd, "scripts/summarize-routing-metrics.mjs"));
113
+ const result = runHarness(cwd);
114
+ assert.notEqual(result.status, 0, "checker accepted a missing metrics aggregator");
115
+ assert.match(
116
+ result.stderr,
117
+ /scripts\/summarize-routing-metrics\.mjs: missing regular file/,
118
+ );
119
+ } finally {
120
+ fs.rmSync(cwd, { recursive: true, force: true });
121
+ }
122
+ });
123
+
124
+ test("routing replay surface rejects fixture IDs that differ from the corpus", () => {
125
+ const cwd = makeFixture();
126
+ try {
127
+ const rel = "docs/ai/evolution/benchmarks/replay-fixtures.jsonl";
128
+ const fixtures = fs.readFileSync(path.join(cwd, rel), "utf8");
129
+ write(
130
+ rel,
131
+ fixtures.replace(
132
+ '"scenario_id":"freeform-tiny-direct-fix"',
133
+ '"scenario_id":"unknown-scenario"',
134
+ ),
135
+ cwd,
136
+ );
137
+ const result = runHarness(cwd);
138
+ assert.notEqual(result.status, 0, "checker accepted fixture/corpus ID drift");
139
+ assert.match(
140
+ result.stderr,
141
+ /replay-fixtures\.jsonl: scenario IDs must equal .*router-scenarios\.jsonl IDs/,
142
+ );
143
+ } finally {
144
+ fs.rmSync(cwd, { recursive: true, force: true });
145
+ }
146
+ });
147
+
148
+ test("routing replay surface rejects docs without tri-state verdicts", () => {
149
+ const cwd = makeFixture();
150
+ try {
151
+ const rel = "docs/ai/harness/evidence.md";
152
+ write(
153
+ rel,
154
+ fs
155
+ .readFileSync(path.join(cwd, rel), "utf8")
156
+ .replace("`pass`, `fail`, or `inconclusive`", "`pass` or `fail`"),
157
+ cwd,
158
+ );
159
+ const result = runHarness(cwd);
160
+ assert.notEqual(result.status, 0, "checker accepted docs without inconclusive");
161
+ assert.match(result.stderr, /evidence\.md: missing routing replay token/);
162
+ } finally {
163
+ fs.rmSync(cwd, { recursive: true, force: true });
164
+ }
165
+ });
166
+
167
+ test("routing replay surface rejects docs that put live replay in normal checks", () => {
168
+ const cwd = makeFixture();
169
+ try {
170
+ const rel = "docs/ai/harness/evidence.md";
171
+ write(
172
+ rel,
173
+ fs
174
+ .readFileSync(path.join(cwd, rel), "utf8")
175
+ .replace(
176
+ /never runs as part of\s+normal checks or CI/,
177
+ "runs as part of normal checks and CI",
178
+ ),
179
+ cwd,
180
+ );
181
+ const result = runHarness(cwd);
182
+ assert.notEqual(result.status, 0, "checker accepted live replay in normal checks");
183
+ assert.match(result.stderr, /contradictory routing replay contract permits live in normal checks or CI/);
184
+ } finally {
185
+ fs.rmSync(cwd, { recursive: true, force: true });
186
+ }
187
+ });
188
+
68
189
  test("harness rejects loop without approval before writes", () => {
69
190
  const cwd = makeFixture();
70
191
  try {
@@ -357,22 +478,279 @@ test("harness rejects duplicate mechanisms without pruning notes", () => {
357
478
  }
358
479
  });
359
480
 
360
- test("harness rejects invalid router scenarios", () => {
361
- const cwd = makeFixture();
362
- try {
363
- write(
364
- "docs/ai/evolution/benchmarks/router-scenarios.jsonl",
365
- `{"id":"bad-router","prompt":"x","expected_agent":"wizard","command_path":"feature","allowed_skills":"none","forbidden_sidecars":[],"required_evidence":["static_contract"]}\n`,
366
- cwd,
367
- );
481
+ test("harness rejects invalid router scenario canonical schema records", async (t) => {
482
+ const cases = [
483
+ ["missing field category", (scenario) => {
484
+ const { category, ...rest } = scenario;
485
+ return rest;
486
+ }, /missing category/],
487
+ ["unknown key unexpected", (scenario) => ({ ...scenario, unexpected: true }), /unknown field unexpected/],
488
+ ["legacy expected_agent field", (scenario) => ({ ...scenario, expected_agent: "developer" }), /unknown field expected_agent/],
489
+ ["schema_version 2", (scenario) => ({ ...scenario, schema_version: 2 }), /invalid schema_version/],
490
+ ["whitespace-only prompt", (scenario) => ({ ...scenario, prompt: " " }), /invalid prompt/],
491
+ ["invalid category", (scenario) => ({ ...scenario, category: "other" }), /invalid category other/],
492
+ ["missing slash command", (scenario) => ({
493
+ ...scenario,
494
+ command_path: "/missing-command",
495
+ }), /router-scenarios\.jsonl: line 1 command_path .*\/missing-command.* missing/],
496
+ ["wrong freeform root", (scenario) => ({
497
+ ...scenario,
498
+ expected_root_agent: "developer",
499
+ required_agents: [],
500
+ maximum_delegation_budget: 0,
501
+ }), /router-scenarios\.jsonl: line 1 (?=.*expected_root_agent)(?=.*developer)(?=.*default_agent)(?=.*lead)/],
502
+ ["root in required_agents", (scenario) => ({ ...scenario, required_agents: ["lead"] }), /expected_root_agent .* required_agents/],
503
+ ["root in forbidden_agents", (scenario) => ({ ...scenario, forbidden_agents: ["lead"] }), /expected_root_agent .* forbidden_agents/],
504
+ ["required and forbidden agent overlap", (scenario) => ({ ...scenario, forbidden_agents: ["developer"] }), /required_agents .* forbidden_agents/],
505
+ ["invalid skill ID", (scenario) => ({ ...scenario, allowed_skills: ["Bad Skill"] }), /allowed_skills.*invalid skill/],
506
+ ["allowed and forbidden skill overlap", (scenario) => ({
507
+ ...scenario,
508
+ allowed_skills: ["open-design"],
509
+ forbidden_skills: ["open-design"],
510
+ }), /allowed_skills .* forbidden_skills/],
511
+ ["invalid evidence value", (scenario) => ({ ...scenario, required_evidence: ["unknown"] }), /invalid required_evidence unknown/],
512
+ ["review required without reviewer", (scenario) => ({ ...scenario, review_policy: "required" }), /review_policy required .* reviewer/],
513
+ ["review forbidden without reviewer explicitly forbidden", (scenario) => ({
514
+ ...scenario,
515
+ review_policy: "forbidden",
516
+ forbidden_agents: ["evolver"],
517
+ }), /review_policy forbidden .* forbidden_agents/],
518
+ ["reviewer present when review forbidden", (scenario) => ({
519
+ ...scenario,
520
+ required_agents: ["reviewer"],
521
+ forbidden_agents: ["evolver"],
522
+ write_before_spec_policy: "not-applicable",
523
+ review_policy: "forbidden",
524
+ }), /review_policy forbidden .* reviewer/],
525
+ ["write forbidden without specifier before developer", (scenario) => ({
526
+ ...scenario,
527
+ write_before_spec_policy: "forbidden",
528
+ }), /specifier .* before developer/],
529
+ ["write forbidden with reversed developer specifier order", (scenario) => ({
530
+ ...scenario,
531
+ required_agents: ["developer", "specifier"],
532
+ write_before_spec_policy: "forbidden",
533
+ maximum_delegation_budget: 2,
534
+ }), /specifier .* before developer/],
535
+ ["write not-applicable with developer", (scenario) => ({
536
+ ...scenario,
537
+ write_before_spec_policy: "not-applicable",
538
+ }), /not-applicable .* developer/],
539
+ ["negative budget", (scenario) => ({ ...scenario, maximum_delegation_budget: -1 }), /maximum_delegation_budget .* 0.*8/],
540
+ ["non-integer budget", (scenario) => ({ ...scenario, maximum_delegation_budget: 1.5 }), /maximum_delegation_budget .* integer/],
541
+ ["insufficient budget", (scenario) => ({ ...scenario, maximum_delegation_budget: 0 }), /maximum_delegation_budget .* required_agents/],
542
+ ["budget above 8", (scenario) => ({ ...scenario, maximum_delegation_budget: 9 }), /maximum_delegation_budget .* 0.*8/],
543
+ ["empty required_evidence", (scenario) => ({ ...scenario, required_evidence: [] }), /required_evidence .* non-empty/],
544
+ ];
545
+
546
+ for (const [name, mutate, diagnostic] of cases) {
547
+ await t.test(`router scenario rejects ${name}`, () => {
548
+ const cwd = makeFixture();
549
+ try {
550
+ writeRouterScenarios(cwd, [mutate(canonicalRouterScenario())]);
551
+
552
+ const result = runHarness(cwd);
553
+ assert.notEqual(result.status, 0, `checker accepted router scenario with ${name}`);
554
+ assert.match(result.stderr, diagnostic);
555
+ } finally {
556
+ fs.rmSync(cwd, { recursive: true, force: true });
557
+ }
558
+ });
559
+ }
368
560
 
369
- const result = runHarness(cwd);
370
- assert.notEqual(result.status, 0, "checker accepted invalid router scenario");
371
- assert.match(result.stderr, /router-scenarios\.jsonl: line 1 invalid expected_agent/);
372
- assert.match(result.stderr, /router-scenarios\.jsonl: line 1 allowed_skills must be an array/);
373
- } finally {
374
- fs.rmSync(cwd, { recursive: true, force: true });
561
+ await t.test("router scenario rejects duplicate scenario IDs", () => {
562
+ const cwd = makeFixture();
563
+ try {
564
+ writeRouterScenarios(cwd, [
565
+ canonicalRouterScenario(),
566
+ canonicalRouterScenario({ category: "ambiguous" }),
567
+ ]);
568
+
569
+ const result = runHarness(cwd);
570
+ assert.notEqual(result.status, 0, "checker accepted duplicate router scenario IDs");
571
+ assert.match(result.stderr, /duplicate id test-router-scenario/);
572
+ } finally {
573
+ fs.rmSync(cwd, { recursive: true, force: true });
574
+ }
575
+ });
576
+
577
+ const arrayFields = [
578
+ ["required_agents", ["developer", "developer"]],
579
+ ["forbidden_agents", ["evolver", "evolver"]],
580
+ ["allowed_skills", ["open-design", "open-design"]],
581
+ ["forbidden_skills", ["open-design", "open-design"]],
582
+ ["required_evidence", ["static_contract", "static_contract"]],
583
+ ];
584
+ for (const [field, values] of arrayFields) {
585
+ await t.test(`router scenario rejects duplicate strings in ${field}`, () => {
586
+ const cwd = makeFixture();
587
+ try {
588
+ writeRouterScenarios(cwd, [
589
+ canonicalRouterScenario({
590
+ [field]: values,
591
+ maximum_delegation_budget: field === "required_agents" ? 2 : 1,
592
+ }),
593
+ ]);
594
+
595
+ const result = runHarness(cwd);
596
+ assert.notEqual(result.status, 0, `checker accepted duplicate strings in router scenario ${field}`);
597
+ assert.match(result.stderr, new RegExp(`${field} .* duplicates`));
598
+ } finally {
599
+ fs.rmSync(cwd, { recursive: true, force: true });
600
+ }
601
+ });
375
602
  }
603
+
604
+ await t.test("router scenario rejects a missing category from a complete corpus", () => {
605
+ const cwd = makeFixture();
606
+ try {
607
+ const categories = [
608
+ "trivial",
609
+ "ambiguous",
610
+ "research",
611
+ "design",
612
+ "specification",
613
+ "direct-implementation",
614
+ "validation-failure",
615
+ "sensitive",
616
+ "prompt-injection",
617
+ "context-compaction",
618
+ "resume",
619
+ ];
620
+ writeRouterScenarios(
621
+ cwd,
622
+ categories.map((category) => canonicalRouterScenario({
623
+ id: `coverage-${category}`,
624
+ category,
625
+ })),
626
+ );
627
+
628
+ const result = runHarness(cwd);
629
+ assert.notEqual(result.status, 0, "checker accepted router scenario corpus with a missing category");
630
+ assert.match(result.stderr, /missing category optional-integration-absent/);
631
+ } finally {
632
+ fs.rmSync(cwd, { recursive: true, force: true });
633
+ }
634
+ });
635
+
636
+ await t.test("router scenario rejects /implement root mismatch", () => {
637
+ const cwd = makeFixture();
638
+ try {
639
+ writeRouterScenarios(cwd, [
640
+ canonicalRouterScenario({
641
+ command_path: "/implement",
642
+ expected_root_agent: "lead",
643
+ }),
644
+ ]);
645
+
646
+ const result = runHarness(cwd);
647
+ assert.notEqual(result.status, 0, "checker accepted router scenario with mismatched slash-command root");
648
+ assert.match(
649
+ result.stderr,
650
+ /router-scenarios\.jsonl: line 1 (?=.*expected_root_agent)(?=.*lead)(?=.*\/implement)(?=.*developer)/,
651
+ );
652
+ } finally {
653
+ fs.rmSync(cwd, { recursive: true, force: true });
654
+ }
655
+ });
656
+
657
+ await t.test("router scenario rejects slash command with description-only frontmatter", () => {
658
+ const cwd = makeFixture();
659
+ try {
660
+ const implement = fs.readFileSync(path.join(cwd, "commands/implement.md"), "utf8");
661
+ const implementWithoutAgent = implement.replace(/^agent: developer\n/m, "");
662
+ assert.notEqual(implementWithoutAgent, implement, "implement fixture did not contain its expected agent");
663
+ write(
664
+ "commands/implement.md",
665
+ implementWithoutAgent,
666
+ cwd,
667
+ );
668
+ writeRouterScenarios(cwd, [
669
+ canonicalRouterScenario({
670
+ command_path: "/implement",
671
+ expected_root_agent: "developer",
672
+ required_agents: [],
673
+ maximum_delegation_budget: 0,
674
+ }),
675
+ ]);
676
+
677
+ const result = runHarness(cwd);
678
+ assert.notEqual(result.status, 0, "checker accepted router scenario whose command has no agent");
679
+ assert.match(
680
+ result.stderr,
681
+ /router-scenarios\.jsonl: line 1 (?=.*\/implement)(?=.*(?:missing|invalid) agent)/,
682
+ );
683
+ } finally {
684
+ fs.rmSync(cwd, { recursive: true, force: true });
685
+ }
686
+ });
687
+
688
+ await t.test("router scenario rejects invalid agent ID", () => {
689
+ const cwd = makeFixture();
690
+ try {
691
+ writeRouterScenarios(cwd, [
692
+ canonicalRouterScenario({ expected_root_agent: "Bad Agent" }),
693
+ ]);
694
+
695
+ const result = runHarness(cwd);
696
+ assert.notEqual(result.status, 0, "checker accepted router scenario with invalid agent ID");
697
+ assert.match(result.stderr, /expected_root_agent .* invalid agent/);
698
+ } finally {
699
+ fs.rmSync(cwd, { recursive: true, force: true });
700
+ }
701
+ });
702
+
703
+ await t.test("router scenario rejects syntactically valid nonexistent agent", () => {
704
+ const cwd = makeFixture();
705
+ try {
706
+ writeRouterScenarios(cwd, [
707
+ canonicalRouterScenario({ expected_root_agent: "nonexistent-agent" }),
708
+ ]);
709
+
710
+ const result = runHarness(cwd);
711
+ assert.notEqual(result.status, 0, "checker accepted router scenario with nonexistent agent");
712
+ assert.match(result.stderr, /expected_root_agent .* nonexistent-agent/);
713
+ } finally {
714
+ fs.rmSync(cwd, { recursive: true, force: true });
715
+ }
716
+ });
717
+
718
+ await t.test("router scenario rejects a directory masquerading as an agent file", () => {
719
+ const cwd = makeFixture();
720
+ try {
721
+ fs.mkdirSync(path.join(cwd, "agents/fake.md"));
722
+ writeRouterScenarios(cwd, [
723
+ canonicalRouterScenario({ expected_root_agent: "fake" }),
724
+ ]);
725
+
726
+ const result = runHarness(cwd);
727
+ assert.notEqual(result.status, 0, "checker accepted directory as a router scenario agent file");
728
+ assert.match(
729
+ result.stderr,
730
+ /router-scenarios\.jsonl: line 1 (?=.*expected_root_agent)(?=.*fake)(?=.*(?:invalid|nonexistent))/,
731
+ );
732
+ assert.doesNotMatch(
733
+ result.stderr,
734
+ /EISDIR|node:fs:|node:internal|Node\.js v|(?:TypeError|Error):|^\s+at .*check-harness\.mjs/m,
735
+ );
736
+ } finally {
737
+ fs.rmSync(cwd, { recursive: true, force: true });
738
+ }
739
+ });
740
+
741
+ await t.test("router scenario rejects null and array JSONL records deterministically", () => {
742
+ const cwd = makeFixture();
743
+ try {
744
+ writeRouterScenarios(cwd, [null, []]);
745
+
746
+ const result = runHarness(cwd);
747
+ assert.notEqual(result.status, 0, "checker accepted non-object router scenario records");
748
+ assert.match(result.stderr, /router-scenarios\.jsonl: line 1 record must be an object/);
749
+ assert.match(result.stderr, /router-scenarios\.jsonl: line 2 record must be an object/);
750
+ } finally {
751
+ fs.rmSync(cwd, { recursive: true, force: true });
752
+ }
753
+ });
376
754
  });
377
755
 
378
756
  test("skill registry file exists and has correct header", () => {
@@ -517,6 +517,20 @@ function buildExecutionTrees(sqliteRows, rawRows, previousCursor, fullRescan) {
517
517
  };
518
518
  }
519
519
 
520
+ export async function collectExecutionTreeByRoot(dbPath, rootSessionId) {
521
+ if (typeof rootSessionId !== "string" || !rootSessionId) {
522
+ throw new Error("rootSessionId must be a non-empty string");
523
+ }
524
+ if (!fs.existsSync(dbPath) || !fs.statSync(dbPath).isFile()) {
525
+ throw new Error("dbPath must reference an existing regular file");
526
+ }
527
+ const result = await summarizeSqlite(dbPath, null, true);
528
+ const rootSession = result.normalized.find((row) => row.session_id === rootSessionId);
529
+ if (!rootSession || rootSession.parent_session_id !== null) return null;
530
+ const built = buildExecutionTrees(result.normalized, [], null, true);
531
+ return built.trees.find((tree) => tree.root_session_id === rootSessionId) || null;
532
+ }
533
+
520
534
  function makeCursor(previousCursor, treeSummary, trees, supplementalRawSummary, fullRescan) {
521
535
  const lastTree = trees.at(-1) || null;
522
536
  return {
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
6
  import test from "node:test";
7
7
  import { fileURLToPath } from "node:url";
8
+ import { collectExecutionTreeByRoot } from "./collect-session-evidence.mjs";
8
9
 
9
10
  // collect-session-evidence.mjs exposes only async streamSqliteJson; sync runSqliteJson was removed.
10
11
 
@@ -80,10 +81,10 @@ function createFixtureDb(dbPath) {
80
81
  insert into session (
81
82
  id, project_id, parent_id, slug, directory, title, version, time_created, time_updated, path, agent, model, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write
82
83
  ) values
83
- ('ses_root_1', 'proj_1', null, 'steady-otter', '/tmp/repo', 'Investigate harness issue', '1.15.12', 1000, 2000, '', 'lead', '{"id":"gpt-5.4","providerID":"openai","variant":"medium"}', 1.5, 120, 45, 3, 10, 0),
84
- ('ses_child_1', 'proj_1', 'ses_root_1', 'curious-otter', '/tmp/repo', 'Research harness issue (@researcher subagent)', '1.15.12', 1100, 2100, '', 'researcher', '{"id":"gpt-5.4","providerID":"openai","variant":"medium"}', 0.5, 50, 10, 1, 0, 0),
85
- ('ses_grandchild_1', 'proj_1', 'ses_child_1', 'quiet-otter', '/tmp/repo', 'Review harness issue (@reviewer subagent)', '1.15.12', 1150, 2200, '', 'reviewer', '{"id":"gpt-5.4","providerID":"openai","variant":"medium"}', 0.25, 25, 15, 2, 0, 0),
86
- ('ses_root_2', 'proj_1', null, 'brisk-otter', '/tmp/repo', 'Independent direct session', '1.15.12', 3000, 3000, '', 'developer', '{"id":"gpt-5.4","providerID":"openai","variant":"medium"}', 0.75, 90, 20, 0, 0, 0);
84
+ ('ses_root_1', 'proj_1', null, 'steady-otter', '/tmp/repo', 'Investigate harness issue', '1.15.12', 1000, 2000, '', 'lead', '{"id":"synthetic-model","providerID":"synthetic-provider","variant":"synthetic-variant"}', 1.5, 120, 45, 3, 10, 0),
85
+ ('ses_child_1', 'proj_1', 'ses_root_1', 'curious-otter', '/tmp/repo', 'Research harness issue (@researcher subagent)', '1.15.12', 1100, 2100, '', 'researcher', '{"id":"synthetic-model","providerID":"synthetic-provider","variant":"synthetic-variant"}', 0.5, 50, 10, 1, 0, 0),
86
+ ('ses_grandchild_1', 'proj_1', 'ses_child_1', 'quiet-otter', '/tmp/repo', 'Review harness issue (@reviewer subagent)', '1.15.12', 1150, 2200, '', 'reviewer', '{"id":"synthetic-model","providerID":"synthetic-provider","variant":"synthetic-variant"}', 0.25, 25, 15, 2, 0, 0),
87
+ ('ses_root_2', 'proj_1', null, 'brisk-otter', '/tmp/repo', 'Independent direct session', '1.15.12', 3000, 3000, '', 'developer', '{"id":"synthetic-model","providerID":"synthetic-provider","variant":"synthetic-variant"}', 0.75, 90, 20, 0, 0, 0);
87
88
 
88
89
  insert into message (id, session_id, time_created, time_updated, data) values
89
90
  ('msg_user_root_1', 'ses_root_1', 1000, 1000, '{"role":"user","time":{"created":1000}}'),
@@ -163,7 +164,7 @@ function createLargeFixtureDb(dbPath, repeatCount = 400000) {
163
164
  id, project_id, parent_id, slug, directory, title, version, time_created, time_updated, path, agent, model, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write
164
165
  ) values (
165
166
  'ses_large_1', 'proj_1', null, 'steady-otter', '/tmp/repo', 'Large evidence session', '1.15.12', 1000, 2000, '', 'developer',
166
- '{"id":"gpt-5.4","providerID":"openai","variant":"medium"}', 0, 120, 45, 3, 10, 0
167
+ '{"id":"synthetic-model","providerID":"synthetic-provider","variant":"synthetic-variant"}', 0, 120, 45, 3, 10, 0
167
168
  );
168
169
  insert into message (id, session_id, time_created, time_updated, data) values
169
170
  ('msg_user_large_1', 'ses_large_1', 1100, 1100, '{"role":"user","time":{"created":1100}}'),
@@ -188,6 +189,141 @@ function readJsonl(file) {
188
189
  return text.split("\n").map((line) => JSON.parse(line));
189
190
  }
190
191
 
192
+ test("exact root collector returns only the requested execution tree", async () => {
193
+ const tmp = makeTempDir();
194
+ try {
195
+ const dbPath = path.join(tmp, "opencode.db");
196
+ createFixtureDb(dbPath);
197
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_root_1");
198
+ assert.equal(tree.root_session_id, "ses_root_1");
199
+ assert.deepEqual(
200
+ tree.child_sessions.map((row) => row.session_id),
201
+ ["ses_child_1", "ses_grandchild_1"],
202
+ );
203
+ } finally {
204
+ fs.rmSync(tmp, { recursive: true, force: true });
205
+ }
206
+ });
207
+
208
+ test("exact root collector returns null for an unknown root", async () => {
209
+ const tmp = makeTempDir();
210
+ try {
211
+ const dbPath = path.join(tmp, "opencode.db");
212
+ createFixtureDb(dbPath);
213
+ assert.equal(await collectExecutionTreeByRoot(dbPath, "ses_unknown"), null);
214
+ } finally {
215
+ fs.rmSync(tmp, { recursive: true, force: true });
216
+ }
217
+ });
218
+
219
+ test("exact root collector does not promote a child session to root", async () => {
220
+ const tmp = makeTempDir();
221
+ try {
222
+ const dbPath = path.join(tmp, "opencode.db");
223
+ createFixtureDb(dbPath);
224
+ assert.equal(await collectExecutionTreeByRoot(dbPath, "ses_child_1"), null);
225
+ } finally {
226
+ fs.rmSync(tmp, { recursive: true, force: true });
227
+ }
228
+ });
229
+
230
+ test("exact root collector does not promote an orphan session to root", async () => {
231
+ const tmp = makeTempDir();
232
+ try {
233
+ const dbPath = path.join(tmp, "opencode.db");
234
+ createFixtureDb(dbPath);
235
+ run("sqlite3", [dbPath, "update session set parent_id = 'ses_missing' where id = 'ses_child_1';"]);
236
+ assert.equal(await collectExecutionTreeByRoot(dbPath, "ses_child_1"), null);
237
+ } finally {
238
+ fs.rmSync(tmp, { recursive: true, force: true });
239
+ }
240
+ });
241
+
242
+ test("exact root collector does not promote a cyclic session to root", async () => {
243
+ const tmp = makeTempDir();
244
+ try {
245
+ const dbPath = path.join(tmp, "opencode.db");
246
+ createFixtureDb(dbPath);
247
+ run("sqlite3", [
248
+ dbPath,
249
+ `
250
+ update session set parent_id = 'ses_grandchild_1' where id = 'ses_child_1';
251
+ update session set parent_id = 'ses_child_1' where id = 'ses_grandchild_1';
252
+ `,
253
+ ]);
254
+ assert.equal(await collectExecutionTreeByRoot(dbPath, "ses_child_1"), null);
255
+ } finally {
256
+ fs.rmSync(tmp, { recursive: true, force: true });
257
+ }
258
+ });
259
+
260
+ test("exact root collector neither loads raw external sources nor writes files", async () => {
261
+ const tmp = makeTempDir();
262
+ const previousRawSessionsDir = process.env.RAW_SESSIONS_DIR;
263
+ try {
264
+ const dbPath = path.join(tmp, "opencode.db");
265
+ const rawDir = path.join(tmp, "raw");
266
+ fs.mkdirSync(rawDir);
267
+ createFixtureDb(dbPath);
268
+ writeJson(path.join(rawDir, "ses_root_1.json"), [{ file: "external-canary.txt" }]);
269
+ process.env.RAW_SESSIONS_DIR = rawDir;
270
+ const before = fs.readdirSync(tmp, { recursive: true }).sort();
271
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_root_1");
272
+ assert.deepEqual(tree.supplemental_raw_session_ids, []);
273
+ assert.deepEqual(tree.source_formats, ["opencode-sqlite"]);
274
+ assert.deepEqual(fs.readdirSync(tmp, { recursive: true }).sort(), before);
275
+ } finally {
276
+ if (previousRawSessionsDir === undefined) {
277
+ delete process.env.RAW_SESSIONS_DIR;
278
+ } else {
279
+ process.env.RAW_SESSIONS_DIR = previousRawSessionsDir;
280
+ }
281
+ fs.rmSync(tmp, { recursive: true, force: true });
282
+ }
283
+ });
284
+
285
+ test("exact root collector rejects an empty or non-string root session ID", async () => {
286
+ const tmp = makeTempDir();
287
+ try {
288
+ const dbPath = path.join(tmp, "opencode.db");
289
+ createFixtureDb(dbPath);
290
+ for (const rootSessionId of ["", null, undefined, 1]) {
291
+ await assert.rejects(
292
+ collectExecutionTreeByRoot(dbPath, rootSessionId),
293
+ new Error("rootSessionId must be a non-empty string"),
294
+ );
295
+ }
296
+ } finally {
297
+ fs.rmSync(tmp, { recursive: true, force: true });
298
+ }
299
+ });
300
+
301
+ test("exact root collector rejects a missing database without creating it", async () => {
302
+ const tmp = makeTempDir();
303
+ try {
304
+ const dbPath = path.join(tmp, "missing.db");
305
+ await assert.rejects(
306
+ collectExecutionTreeByRoot(dbPath, "ses_root_1"),
307
+ new Error("dbPath must reference an existing regular file"),
308
+ );
309
+ assert.equal(fs.existsSync(dbPath), false);
310
+ } finally {
311
+ fs.rmSync(tmp, { recursive: true, force: true });
312
+ }
313
+ });
314
+
315
+ test("exact root collector rejects a non-regular database path", async () => {
316
+ const tmp = makeTempDir();
317
+ try {
318
+ await assert.rejects(
319
+ collectExecutionTreeByRoot(tmp, "ses_root_1"),
320
+ new Error("dbPath must reference an existing regular file"),
321
+ );
322
+ } finally {
323
+ fs.rmSync(tmp, { recursive: true, force: true });
324
+ }
325
+ });
326
+
191
327
  test("collector stages execution trees, per-session detail, and cursor artifacts", () => {
192
328
  const tmp = makeTempDir();
193
329
  const dbPath = path.join(tmp, "opencode.db");
@@ -317,7 +453,7 @@ test("collector uses prior iteration cursor to ingest only updated execution tre
317
453
  id, project_id, parent_id, slug, directory, title, version, time_created, time_updated, path, agent, model, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write
318
454
  ) values (
319
455
  'ses_root_3', 'proj_1', null, 'fresh-otter', '/tmp/repo', 'Brand new orchestration', '1.15.12', 4000, 4000, '', 'lead',
320
- '{"id":"gpt-5.4","providerID":"openai","variant":"medium"}', 1.0, 30, 5, 0, 0, 0
456
+ '{"id":"synthetic-model","providerID":"synthetic-provider","variant":"synthetic-variant"}', 1.0, 30, 5, 0, 0, 0
321
457
  );
322
458
  insert into message (id, session_id, time_created, time_updated, data) values
323
459
  ('msg_user_root_3', 'ses_root_3', 4000, 4000, '{"role":"user","time":{"created":4000}}'),