opencode-agent-orchestration-kit 1.1.1 → 1.2.1

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.
@@ -550,6 +550,9 @@ test("orchestration catalog preserves approved behavior", async (t) => {
550
550
  }
551
551
  });
552
552
 
553
+ const kitScriptsDir = '"${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/scripts';
554
+ const loopStateCommand = `node ${kitScriptsDir}/loop-state.mjs"`;
555
+
553
556
  const validLoopCommand = `---
554
557
  description: Run a bounded and verifiable engineering loop.
555
558
  agent: lead
@@ -563,16 +566,17 @@ history_path: .opencode/loops/<slug>.history.jsonl
563
566
  lock_path: .opencode/loops/<slug>.lock
564
567
  human_view_path: .opencode/loops/<slug>.md
565
568
  worktree_mode: explicit_opt_in
569
+ state_runtime_missing: stop_and_report
566
570
 
567
571
  developer -> reviewer -> developer (state sync)
568
572
 
569
573
  ## Phase 1
570
574
 
571
- node scripts/loop-state.mjs inspect
575
+ ${loopStateCommand} inspect
572
576
 
573
577
  ## Phase 2
574
578
 
575
- node scripts/loop-state.mjs resume
579
+ ${loopStateCommand} resume
576
580
 
577
581
  ## Phase 3
578
582
  `;
@@ -1021,8 +1025,8 @@ test("harness rejects loop resume writes before approval", () => {
1021
1025
  writeLoopFixture(
1022
1026
  cwd,
1023
1027
  validLoopCommand.replace(
1024
- "node scripts/loop-state.mjs inspect",
1025
- "node scripts/loop-state.mjs resume",
1028
+ `${loopStateCommand} inspect`,
1029
+ `${loopStateCommand} resume`,
1026
1030
  ),
1027
1031
  );
1028
1032
 
@@ -1041,6 +1045,80 @@ test("harness rejects loop resume writes before approval", () => {
1041
1045
  }
1042
1046
  });
1043
1047
 
1048
+ test("harness rejects a project-relative loop-state call", () => {
1049
+ const cwd = makeFixture();
1050
+ try {
1051
+ writeLoopFixture(
1052
+ cwd,
1053
+ validLoopCommand.replace(`${loopStateCommand} resume`, "node scripts/loop-state.mjs resume"),
1054
+ );
1055
+
1056
+ const result = runHarness(cwd);
1057
+ assert.notEqual(result.status, 0, "checker accepted a project-relative loop-state call");
1058
+ assert.match(
1059
+ result.stderr,
1060
+ /commands\/loop\.md: loop-state must run from the config directory, not project-relative scripts\//,
1061
+ );
1062
+ } finally {
1063
+ fs.rmSync(cwd, { recursive: true, force: true });
1064
+ }
1065
+ });
1066
+
1067
+ test("harness rejects a loop command without the fail-closed runtime rule", () => {
1068
+ const cwd = makeFixture();
1069
+ try {
1070
+ writeLoopFixture(cwd, validLoopCommand.replace("state_runtime_missing: stop_and_report\n", ""));
1071
+
1072
+ const result = runHarness(cwd);
1073
+ assert.notEqual(result.status, 0, "checker accepted a loop without the fail-closed rule");
1074
+ assert.match(result.stderr, /commands\/loop\.md: missing state_runtime_missing: stop_and_report/);
1075
+ } finally {
1076
+ fs.rmSync(cwd, { recursive: true, force: true });
1077
+ }
1078
+ });
1079
+
1080
+ test("harness rejects a project-relative mission-status call", () => {
1081
+ const cwd = makeFixture();
1082
+ try {
1083
+ const loopStatus = fs.readFileSync(path.join(cwd, "commands/loop-status.md"), "utf8");
1084
+ write(
1085
+ "commands/loop-status.md",
1086
+ loopStatus.replaceAll(`node ${kitScriptsDir}/mission-status.mjs"`, "node scripts/mission-status.mjs"),
1087
+ cwd,
1088
+ );
1089
+
1090
+ const result = runHarness(cwd);
1091
+ assert.notEqual(result.status, 0, "checker accepted a project-relative mission-status call");
1092
+ assert.match(
1093
+ result.stderr,
1094
+ /commands\/loop-status\.md: mission-status must run from the config directory/,
1095
+ );
1096
+ } finally {
1097
+ fs.rmSync(cwd, { recursive: true, force: true });
1098
+ }
1099
+ });
1100
+
1101
+ test("harness rejects a lead allowlist that only matches project-relative loop-state", () => {
1102
+ const cwd = makeFixture();
1103
+ try {
1104
+ const lead = fs.readFileSync(path.join(cwd, "agents/lead.md"), "utf8");
1105
+ write(
1106
+ "agents/lead.md",
1107
+ lead.replace('"node *scripts/loop-state.mjs inspect*"', '"node scripts/loop-state.mjs inspect*"'),
1108
+ cwd,
1109
+ );
1110
+
1111
+ const result = runHarness(cwd);
1112
+ assert.notEqual(result.status, 0, "checker accepted a lead allowlist that denies the kit runtime");
1113
+ assert.match(
1114
+ result.stderr,
1115
+ /agents\/lead\.md: missing bash allow "node \*scripts\/loop-state\.mjs inspect\*": allow/,
1116
+ );
1117
+ } finally {
1118
+ fs.rmSync(cwd, { recursive: true, force: true });
1119
+ }
1120
+ });
1121
+
1044
1122
  test("harness rejects evolve flow when evaluator/debugger/evolver order is inverted", () => {
1045
1123
  const cwd = makeFixture();
1046
1124
  try {
@@ -62,7 +62,7 @@ have no reason to suspect.
62
62
 
63
63
  ## Stage 3 Dimensions
64
64
 
65
- Attack each reviewed file along these nine dimensions:
65
+ Attack each reviewed file along these eleven dimensions:
66
66
 
67
67
  1. **Assumptions.** Does the code assume a value exists, is non-empty, is
68
68
  unique, is ordered or arrives only once?
@@ -78,6 +78,33 @@ Attack each reviewed file along these nine dimensions:
78
78
  8. **Conventions.** Consistency with the conventions the repository documents.
79
79
  9. **Architecture.** Conformance with the project's own declared rules only,
80
80
  never with rules you would prefer.
81
+ 10. **A weakened bar.** Faced with a red check, the cheapest road to green
82
+ ends with the check passing and nothing fixed. Read the removed lines as
83
+ carefully as the added ones; that is where these show:
84
+ - **A test got easier.** A skip or focus marker added, a test file
85
+ deleted, an assertion removed or loosened in a test that stayed, an
86
+ expected value rewritten to match what the code now returns.
87
+ - **A checker got silenced.** A new suppression comment (`@ts-ignore`,
88
+ `eslint-disable`, `# noqa`, `# type: ignore`, `#[allow]`,
89
+ `@SuppressWarnings`) or one that drops code from coverage.
90
+ - **A threshold moved.** A coverage or performance budget lowered, a lint
91
+ rule turned off or down a severity, a step removed from the project's
92
+ validation gate or CI.
93
+ - **Work is unfinished.** A stub that throws "not implemented", an empty
94
+ `catch` that turns a failure into silence, a `TODO` where the
95
+ implementation should be.
96
+
97
+ None of these is wrong by itself: a test may change when the spec did.
98
+ Each one is a defect of at least medium severity that breaks safe
99
+ operation, so under the review policy it is **blocking** unless the task artifacts or the Verification
100
+ Envelope name it and quote the requirement behind it. Tightening the bar
101
+ needs no justification; loosening it always does.
102
+ 11. **Tests that prove nothing new.** A new test that re-proves what an
103
+ existing one asserts, the same rule tested again at a slower layer, a
104
+ table of near-identical cases, or anything "Which Tests to Write" in
105
+ `test-driven-development` says not to test. Name the existing test it
106
+ duplicates or the rule it breaks. It is **Should fix**: it does not make
107
+ the change wrong, it makes every later task slower.
81
108
 
82
109
  A finding that spans files is filed against a changed file.
83
110
 
@@ -96,15 +123,48 @@ parameter that is accepted but unused.
96
123
  Disagreeing with the fix, being unable to confirm the finding, or a wrong line
97
124
  number are not grounds to drop it. Correct the citation instead.
98
125
 
126
+ ## Stage 5 Rounds
127
+
128
+ A review that ends `not_safe_to_commit` sends the change back for a fix, and
129
+ then it is reviewed again. Each pass is a **round**.
130
+
131
+ - **Round 1 reviews the whole change.** Record the commit it reviewed
132
+ (`git log -1 --format=%H`) and whether the tree had uncommitted changes.
133
+ - **Every later round reads the previous report first.** It is a review, not
134
+ the author's reasoning, so the context boundary does not apply to it. Close
135
+ each of its findings as **resolved**, **still open** or **dismissed with a
136
+ reason**. A finding the fix did not resolve is still open, not new; one
137
+ dismissed with a reason stays dismissed unless the diff contradicts the
138
+ reason.
139
+ - **Then review only what changed since that round**: `git diff` against the
140
+ commit it recorded, plus any file that did not exist then. If that round
141
+ reviewed uncommitted changes, there is no commit to diff against: review the
142
+ whole change again, and do not raise again what the previous report raised.
143
+ - **Name the class, not only the instance.** When a finding is one case of a
144
+ pattern (a missing bound, an unchecked error, the same assumption in three
145
+ callers), name the pattern and list every instance, so one round fixes all
146
+ of them.
147
+ - **Three rounds is the cap.** If the third round still has a Blocking
148
+ finding, stop reviewing: the verdict is `not_safe_to_commit`, and the report
149
+ says the approach needs reconsidering. That decision is the human's.
150
+ - **An approval ends the series.** A correction reviewed after it, such as a
151
+ CI fix, starts a new series at round 1 on that correction's diff.
152
+
99
153
  ## Output
100
154
 
101
155
  1. The coverage line comes first:
102
- `coverage: files_in_change=<n> reviewed=<n> skipped=<n>`, followed by each
103
- skipped file and its reason.
104
- 2. Findings grouped as **Blocking**, **Should fix** and **Nit**. Each has
105
- `file:line`, what breaks, the exact trigger and why the existing tests miss
106
- it. Findings keep the canonical fields of the reviewer policy.
107
- 3. A verdict: `safe_to_commit` or `not_safe_to_commit`.
156
+ `coverage: round=<n> files_in_change=<n> reviewed=<n> skipped=<n>`,
157
+ followed by each skipped file and its reason. From round 2, the files are
158
+ the ones that round reviewed.
159
+ 2. From round 2, the previous report's findings with their closure.
160
+ 3. Findings grouped as **Blocking**, **Should fix** and **Nit**, and
161
+ **Pre-existing** apart from them. Each has `file:line`, what breaks, the
162
+ exact trigger and why the existing tests miss it. Findings keep the
163
+ canonical fields of the reviewer policy. A pre-existing finding is a defect
164
+ the change did not write, modify or make newly reachable: it never blocks
165
+ and is never counted as blocking or unresolved. If the change makes it
166
+ worse, it is the change's, at its real severity.
167
+ 4. A verdict: `safe_to_commit` or `not_safe_to_commit`.
108
168
 
109
169
  Never invent findings to look thorough. An empty Blocking group is a valid
110
170
  result.
@@ -112,7 +172,8 @@ result.
112
172
  Return the full report in the review output under the heading
113
173
  `Adversarial coverage`. The reviewer is read-only, so the workflow's state-sync
114
174
  step copies it verbatim to `docs/ai/runs/<YYYY-MM-DD>-<slug>/oak-adversarial-review.md`
115
- when a run folder exists. Never leave the report only in the session.
175
+ when a run folder exists, appending each round under a `## Round <n>` heading so
176
+ the file keeps every round. Never leave the report only in the session.
116
177
 
117
178
  ## Mapping to OAK verdicts
118
179
 
@@ -122,6 +183,7 @@ when a run folder exists. Never leave the report only in the session.
122
183
  | `safe_to_commit`, with Should fix or Nit | `pass_with_observations` |
123
184
  | `not_safe_to_commit` | `needs_changes` |
124
185
  | `not_safe_to_commit` because evidence is missing | `blocked` |
186
+ | `not_safe_to_commit` after the third round | `blocked` |
125
187
 
126
188
  The canonical verdict is the one the reviewer returns.
127
189
 
@@ -131,8 +193,8 @@ When a run is open, end the report with these counts. The state-sync step, not
131
193
  the reviewer, records them:
132
194
 
133
195
  ```bash
134
- oak run event --type review review=adversarial files_in_change=<n> files_reviewed=<n> files_skipped=<n> blocking=<n> should_fix=<n> nit=<n> verdict=<safe_to_commit|not_safe_to_commit>
196
+ oak run event --type review review=adversarial round=<n> files_in_change=<n> files_reviewed=<n> files_skipped=<n> blocking=<n> should_fix=<n> nit=<n> pre_existing=<n> verdict=<safe_to_commit|not_safe_to_commit>
135
197
  ```
136
198
 
137
- After a correction pass, emit it again with `unresolved=<n>`. The last event is
138
- authoritative.
199
+ From round 2, add `unresolved=<n>`: the previous findings still open. The last
200
+ event is authoritative.
@@ -100,7 +100,7 @@ Run tests after every refactor step to confirm nothing broke.
100
100
 
101
101
  ## The Prove-It Pattern (Bug Fixes)
102
102
 
103
- When a bug is reported, **do not start by trying to fix it.** Start by writing a test that reproduces it.
103
+ When a bug is reported, **do not start by trying to fix it.** Start by writing a test that reproduces it. Prefer tightening an existing test that should have caught it; add a new one only when none can (see [Which Tests to Write](#which-tests-to-write)).
104
104
 
105
105
  ```
106
106
  Bug report arrives
@@ -190,6 +190,21 @@ Is it a critical user flow that must work end-to-end?
190
190
  → E2E test (large) — limit these to critical paths
191
191
  ```
192
192
 
193
+ ## Which Tests to Write
194
+
195
+ Every test is paid for on every task: the validation gate runs it, CI runs it, and a suite that grows "just in case" becomes the slowest stage of the loop. The question for every new test is **what real bug would reach users that no existing test catches?** If the answer is none, or a cosmetic one, do not write it.
196
+
197
+ - **Search before you write.** Find the test that already covers the behavior (search for the function, the error code, the message) and extend it. A new test is for what nothing asserts yet.
198
+ - **One test per rule, at the cheapest layer that proves it**, usually a unit test in the module that owns the behavior. Do not prove the same rule again at another layer. A slower test covers the wiring once per path, and only when the details are already unit-tested.
199
+ - **One representative case plus the edges that genuinely differ**: a boundary, an error path. No table of near-identical inputs, and no variant per button, per wording or per runtime when the code path is shared.
200
+ - **Do not test** constructors, getters, equality, copies or one-line delegation; that a constant, a type or an export exists; what the type system or a static check already enforces; the language, a library or the framework; copy, colors, layout or the shape of a view tree; the contents of documentation; or the implementation mirrored line by line. Never write a test that asserts other test files exist.
201
+ - **Tests live with the module they test.** A task, a phase or a bug does not get its own test file. Prefer extending an existing file: many runners pay a per-file cost that can dominate the run.
202
+ - **A bug fix adds at most one regression test**, and only when no existing test can be tightened to catch it.
203
+ - **Slow tests are the exception.** Real processes, real network and real timers only when nothing faster can prove the behavior. Never a fixed sleep: fake the clock, or poll with a timeout.
204
+ - **Always kept:** security, secrets, credentials, permissions, refusals, money, data-transforming migrations and data loss each need a test at their enforcement point. Remove a test there only when the change names the test that still proves the same thing.
205
+
206
+ The project's own test policy in its `AGENTS.md`, where it has one, wins over this list.
207
+
193
208
  ## Writing Good Tests
194
209
 
195
210
  ### Test State, Not Interactions
@@ -396,7 +411,7 @@ For detailed testing patterns, examples, and anti-patterns across frameworks, se
396
411
 
397
412
  After completing any implementation:
398
413
 
399
- - [ ] Every new behavior has a corresponding test
414
+ - [ ] Every new behavior that [Which Tests to Write](#which-tests-to-write) calls for has a corresponding test
400
415
  - [ ] All tests pass: `npm test`
401
416
  - [ ] Bug fixes include a reproduction test that failed before the fix
402
417
  - [ ] Test names describe the behavior being verified
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-agent-orchestration-kit",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "private": false,
5
5
  "description": "Open-source multi-agent orchestration harness for OpenCode with specialized agents, durable workflows, review gates, and reproducible software-engineering processes.",
6
6
  "keywords": [
@@ -143,7 +143,7 @@ async function benchmarkFixture(fixture, iterations, temporaryRoot) {
143
143
  const result = await createInstallationManager({
144
144
  sourceRoot: fixture.sourceRoot,
145
145
  repositoryRoot: fixture.root,
146
- versionProvider: () => "1.1.1",
146
+ versionProvider: () => "1.2.1",
147
147
  }).run("install", { targetRoot });
148
148
  if (result.exitCode !== 0) throw invalid(`installation benchmark failed for ${fixture.id}`);
149
149
  } finally {
@@ -32,7 +32,7 @@ const PRIVATE_MARKERS = [
32
32
 
33
33
  function walk(directory, root = directory, files = []) {
34
34
  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
35
- if ([".git", "node_modules"].includes(entry.name)) continue;
35
+ if ([".git", ".codegraph", "node_modules"].includes(entry.name)) continue;
36
36
  if ([".gitignore", "check.sh"].includes(entry.name)) continue;
37
37
  const full = path.join(directory, entry.name);
38
38
  if (entry.isDirectory()) walk(full, root, files);
@@ -22,6 +22,18 @@ test("the boundary scan reports a private marker without echoing its value", ()
22
22
  }
23
23
  });
24
24
 
25
+ test("the boundary scan skips the local CodeGraph index", () => {
26
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "public-boundary-codegraph-"));
27
+ try {
28
+ const leaked = ["/", "Users", "example", "secret"].join("/");
29
+ fs.mkdirSync(path.join(root, ".codegraph"));
30
+ fs.writeFileSync(path.join(root, ".codegraph", "daemon.log"), leaked);
31
+ assert.deepEqual(scanPublicLeaks(root), []);
32
+ } finally {
33
+ fs.rmSync(root, { recursive: true, force: true });
34
+ }
35
+ });
36
+
25
37
  test("missing boundary documentation fails closed", () => {
26
38
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "public-boundary-missing-"));
27
39
  try {
@@ -22,7 +22,7 @@ const EXACT_KEYS = {
22
22
  commit: ["commit"],
23
23
  image: ["tag", "digest"],
24
24
  version: ["version"],
25
- overrides: ["@babel/core", "brace-expansion", "uuid"],
25
+ overrides: ["@babel/core", "brace-expansion", "effect", "glob", "seroval", "seroval-plugins", "zod"],
26
26
  };
27
27
 
28
28
  const COMMIT = /^[0-9a-f]{40}$/;
@@ -106,7 +106,11 @@ export function validateSupplyChainData(data) {
106
106
  data.npm_overrides["brace-expansion"],
107
107
  "npm_overrides.brace-expansion",
108
108
  );
109
- assertStableVersion(data.npm_overrides.uuid, "npm_overrides.uuid");
109
+ assertStableVersion(data.npm_overrides.effect, "npm_overrides.effect");
110
+ assertStableVersion(data.npm_overrides.glob, "npm_overrides.glob");
111
+ assertStableVersion(data.npm_overrides.seroval, "npm_overrides.seroval");
112
+ assertStableVersion(data.npm_overrides["seroval-plugins"], "npm_overrides.seroval-plugins");
113
+ assertStableVersion(data.npm_overrides.zod, "npm_overrides.zod");
110
114
  return data;
111
115
  }
112
116
 
@@ -497,7 +501,11 @@ function canonicalDocumentationPinBlock(data) {
497
501
  | opencode-ai | ${data.external_refs.opencode_ai.version} | exact version |
498
502
  | @babel/core override | ${data.npm_overrides["@babel/core"]} | exact version |
499
503
  | brace-expansion override | ${data.npm_overrides["brace-expansion"]} | exact version |
500
- | uuid override | ${data.npm_overrides.uuid} | exact version |
504
+ | effect override | ${data.npm_overrides.effect} | exact version |
505
+ | glob override | ${data.npm_overrides.glob} | exact version |
506
+ | seroval override | ${data.npm_overrides.seroval} | exact version |
507
+ | seroval-plugins override | ${data.npm_overrides["seroval-plugins"]} | exact version |
508
+ | zod override | ${data.npm_overrides.zod} | exact version |
501
509
  <!-- supply-chain-pins:end -->`;
502
510
  }
503
511
 
@@ -524,7 +532,11 @@ function validateDocumentation(root, data, fsOps) {
524
532
  "| opencode-ai |",
525
533
  "| @babel/core override |",
526
534
  "| brace-expansion override |",
527
- "| uuid override |",
535
+ "| effect override |",
536
+ "| glob override |",
537
+ "| seroval override |",
538
+ "| seroval-plugins override |",
539
+ "| zod override |",
528
540
  ].map((row) => actualBlock.indexOf(row));
529
541
  const rowsAreOrdered = rowPositions.every(
530
542
  (position, index) => position >= 0 && (index === 0 || position > rowPositions[index - 1]),
@@ -43,8 +43,12 @@ const VALID = {
43
43
  },
44
44
  npm_overrides: {
45
45
  "@babel/core": "7.29.7",
46
- "brace-expansion": "5.0.9",
47
- uuid: "14.0.0",
46
+ "brace-expansion": "5.0.12",
47
+ effect: "4.0.7",
48
+ glob: "14.0.2",
49
+ seroval: "1.6.12",
50
+ "seroval-plugins": "1.6.12",
51
+ zod: "4.6.7",
48
52
  },
49
53
  };
50
54
 
@@ -88,7 +92,11 @@ function canonicalPolicy() {
88
92
  | opencode-ai | ${VALID.external_refs.opencode_ai.version} | exact version |
89
93
  | @babel/core override | ${VALID.npm_overrides["@babel/core"]} | exact version |
90
94
  | brace-expansion override | ${VALID.npm_overrides["brace-expansion"]} | exact version |
91
- | uuid override | ${VALID.npm_overrides.uuid} | exact version |
95
+ | effect override | ${VALID.npm_overrides.effect} | exact version |
96
+ | glob override | ${VALID.npm_overrides.glob} | exact version |
97
+ | seroval override | ${VALID.npm_overrides.seroval} | exact version |
98
+ | seroval-plugins override | ${VALID.npm_overrides["seroval-plugins"]} | exact version |
99
+ | zod override | ${VALID.npm_overrides.zod} | exact version |
92
100
  <!-- supply-chain-pins:end -->
93
101
 
94
102
  Automated installs with intact shipped manifests use \`npm ci --ignore-scripts\`.
@@ -193,13 +201,33 @@ function withSurfaceFixture(callback) {
193
201
  },
194
202
  "node_modules/brace-expansion": {
195
203
  version: VALID.npm_overrides["brace-expansion"],
196
- resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
204
+ resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
197
205
  integrity: "sha512-braceexpansion",
198
206
  },
199
- "node_modules/uuid": {
200
- version: VALID.npm_overrides.uuid,
201
- resolved: "https://registry.npmjs.org/uuid/-/uuid-14.0.0.tgz",
202
- integrity: "sha512-uuid",
207
+ "node_modules/effect": {
208
+ version: VALID.npm_overrides.effect,
209
+ resolved: "https://registry.npmjs.org/effect/-/effect-4.0.7.tgz",
210
+ integrity: "sha512-effect",
211
+ },
212
+ "node_modules/glob": {
213
+ version: VALID.npm_overrides.glob,
214
+ resolved: "https://registry.npmjs.org/glob/-/glob-14.0.2.tgz",
215
+ integrity: "sha512-glob",
216
+ },
217
+ "node_modules/seroval": {
218
+ version: VALID.npm_overrides.seroval,
219
+ resolved: "https://registry.npmjs.org/seroval/-/seroval-1.6.12.tgz",
220
+ integrity: "sha512-seroval",
221
+ },
222
+ "node_modules/seroval-plugins": {
223
+ version: VALID.npm_overrides["seroval-plugins"],
224
+ resolved: "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.6.12.tgz",
225
+ integrity: "sha512-serovalplugins",
226
+ },
227
+ "node_modules/zod": {
228
+ version: VALID.npm_overrides.zod,
229
+ resolved: "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
230
+ integrity: "sha512-zod",
203
231
  },
204
232
  "node_modules/example": {
205
233
  version: "1.2.3",
@@ -269,7 +297,7 @@ test("rejects missing and unknown keys at every schema level", () => {
269
297
  expectInvalid((data) => { data.external_refs.unknown = {}; }, "external_refs keys");
270
298
  expectInvalid((data) => delete data.external_refs.actions_checkout.commit, "external_refs.actions_checkout keys");
271
299
  expectInvalid((data) => { data.external_refs.node_image.unknown = true; }, "external_refs.node_image keys");
272
- expectInvalid((data) => delete data.npm_overrides.uuid, "npm_overrides keys");
300
+ expectInvalid((data) => delete data.npm_overrides.effect, "npm_overrides keys");
273
301
  expectInvalid((data) => { data.npm_overrides.extra = "1.0.0"; }, "npm_overrides keys");
274
302
  });
275
303
 
@@ -328,8 +356,12 @@ test("requires exact canonical versions without ranges", () => {
328
356
  "npm_overrides.brace-expansion",
329
357
  );
330
358
  expectInvalid(
331
- (data) => { data.npm_overrides.uuid = "14.0"; },
332
- "npm_overrides.uuid",
359
+ (data) => { data.npm_overrides.glob = "^14.0.2"; },
360
+ "npm_overrides.glob",
361
+ );
362
+ expectInvalid(
363
+ (data) => { data.npm_overrides.effect = "4.0"; },
364
+ "npm_overrides.effect",
333
365
  );
334
366
  });
335
367
 
@@ -586,7 +618,8 @@ for (const [label, current, replacement] of [
586
618
  ["opencode-ai", `| opencode-ai | ${VALID.external_refs.opencode_ai.version} |`, "| opencode-ai | DRIFTED |"],
587
619
  ["Babel override", `| @babel/core override | ${VALID.npm_overrides["@babel/core"]} |`, "| @babel/core override | DRIFTED |"],
588
620
  ["brace-expansion override", `| brace-expansion override | ${VALID.npm_overrides["brace-expansion"]} |`, "| brace-expansion override | DRIFTED |"],
589
- ["uuid override", `| uuid override | ${VALID.npm_overrides.uuid} |`, "| uuid override | DRIFTED |"],
621
+ ["glob override", `| glob override | ${VALID.npm_overrides.glob} |`, "| glob override | DRIFTED |"],
622
+ ["effect override", `| effect override | ${VALID.npm_overrides.effect} |`, "| effect override | DRIFTED |"],
590
623
  ]) {
591
624
  test(`documentation validation rejects a drifted ${label} pin`, () => {
592
625
  withSurfaceFixture((root) => {
@@ -674,9 +707,12 @@ for (const [dependency, mutation] of [
674
707
  ["brace-expansion", (packageData) => { delete packageData.overrides["brace-expansion"]; }],
675
708
  ["brace-expansion range", (packageData) => { packageData.overrides["brace-expansion"] = "^5.0.9"; }],
676
709
  ["brace-expansion wrong version", (packageData) => { packageData.overrides["brace-expansion"] = "5.0.7"; }],
677
- ["uuid", (packageData) => { delete packageData.overrides.uuid; }],
678
- ["uuid range", (packageData) => { packageData.overrides.uuid = "^14.0.0"; }],
679
- ["uuid wrong version", (packageData) => { packageData.overrides.uuid = "13.0.0"; }],
710
+ ["glob", (packageData) => { delete packageData.overrides.glob; }],
711
+ ["glob range", (packageData) => { packageData.overrides.glob = "^14.0.2"; }],
712
+ ["glob wrong version", (packageData) => { packageData.overrides.glob = "14.0.1"; }],
713
+ ["effect", (packageData) => { delete packageData.overrides.effect; }],
714
+ ["effect range", (packageData) => { packageData.overrides.effect = "^4.0.7"; }],
715
+ ["effect wrong version", (packageData) => { packageData.overrides.effect = "4.0.6"; }],
680
716
  ]) {
681
717
  test(`surface validation rejects absent, ranged, or wrong ${dependency} override`, () => {
682
718
  withSurfaceFixture((root) => {
@@ -720,7 +756,7 @@ test("surface validation rejects a lockfile not regenerated to the brace-expansi
720
756
  fs.writeFileSync(path.join(root, relative), `${JSON.stringify(lock)}\n`);
721
757
  assert.throws(
722
758
  () => checkSupplyChain(root),
723
- /package-lock\.json brace-expansion must resolve to 5\.0\.9/,
759
+ /package-lock\.json brace-expansion must resolve to 5\.0\.12/,
724
760
  );
725
761
  });
726
762
  });
package/scripts/check.sh CHANGED
@@ -268,8 +268,8 @@ if (opencodePackage.dependencies?.['@opentui/solid'] !== '0.2.5') {
268
268
  if (opencodePackage.dependencies?.['solid-js'] !== '1.9.12') {
269
269
  throw new Error('opencode/package.json must pin solid-js to 1.9.12')
270
270
  }
271
- if (opencodePackage.overrides?.['brace-expansion'] !== '5.0.9') {
272
- throw new Error('opencode/package.json must override brace-expansion to 5.0.9')
271
+ if (opencodePackage.overrides?.['brace-expansion'] !== '5.0.12') {
272
+ throw new Error('opencode/package.json must override brace-expansion to 5.0.12')
273
273
  }
274
274
  NODE
275
275
 
@@ -69,6 +69,11 @@ export function parseOpenCodeModelList(stdout) {
69
69
  return grouped;
70
70
  }
71
71
 
72
+ export function parseOpenCodeMajorVersion(stdout) {
73
+ const match = String(stdout).match(/(\d+)\.\d+\.\d+/);
74
+ return match ? Number(match[1]) : undefined;
75
+ }
76
+
72
77
  export function parseOpenCodeAuthProviders(stdout) {
73
78
  if (typeof stdout !== "string") throw new Error("auth stdout must be a string");
74
79
  const providers = [];
@@ -232,9 +237,17 @@ function shellRcPath({ homeDir, shell }) {
232
237
  throw new Error("oc-switch supports zsh and bash startup files");
233
238
  }
234
239
 
240
+ function modelEnvironment(state) {
241
+ return {
242
+ OPENCODE_MODEL: state.defaultModel,
243
+ OPENCODE_SMALL_MODEL: state.smallModel,
244
+ ...Object.fromEntries(AGENT_IDS.map((agent) => [agentEnvKey(agent), state.agents[agent]])),
245
+ };
246
+ }
247
+
235
248
  function updateShellRc(contents, state) {
236
- const managed = [SHELL_START, `export OPENCODE_MODEL=${shellQuote(state.defaultModel)}`, `export OPENCODE_SMALL_MODEL=${shellQuote(state.smallModel)}`,
237
- ...AGENT_IDS.map((agent) => `export ${agentEnvKey(agent)}=${shellQuote(state.agents[agent])}`), SHELL_END].join("\n");
249
+ const managed = [SHELL_START,
250
+ ...Object.entries(modelEnvironment(state)).map(([key, value]) => `export ${key}=${shellQuote(value)}`), SHELL_END].join("\n");
238
251
  const block = new RegExp(`${SHELL_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${SHELL_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\r?\\n?`, "g");
239
252
  return `${contents.replace(block, "").trimEnd()}\n\n${managed}\n`;
240
253
  }
@@ -280,9 +293,9 @@ function resolveBinary({ signal } = {}) {
280
293
  });
281
294
  }
282
295
 
283
- function runCommand(args, { signal } = {}) {
296
+ function runCommand(args, { signal, env } = {}) {
284
297
  return new Promise((resolve, reject) => {
285
- const child = spawn(args[0], args.slice(1), { shell: false, stdio: ["ignore", "pipe", "pipe"] });
298
+ const child = spawn(args[0], args.slice(1), { shell: false, stdio: ["ignore", "pipe", "pipe"], env });
286
299
  let stdout = "";
287
300
  const abort = () => child.kill("SIGTERM");
288
301
  signal?.addEventListener("abort", abort, { once: true });
@@ -306,17 +319,38 @@ function frame(screen, first, previousLineCount) {
306
319
  export function createOcSwitcher({ homeDir = os.homedir(), env = process.env, shell = env.SHELL, now = () => new Date().toISOString(), resolve = resolveBinary, command = runCommand } = {}) {
307
320
  const filePath = statePath({ homeDir, env });
308
321
  const read = () => readState(filePath, env, now);
309
- const save = (state) => {
322
+ let majorVersion;
323
+ const openCodeMajor = async (binary, signal) => {
324
+ if (majorVersion === undefined) {
325
+ try { majorVersion = parseOpenCodeMajorVersion(await command([binary, "--version"], { signal })) ?? 1; } catch { majorVersion = 1; }
326
+ }
327
+ return majorVersion;
328
+ };
329
+ const save = async (state) => {
310
330
  const normalized = { ...state, schemaVersion: STATE_VERSION, updatedAt: now() };
311
331
  atomicWrite(filePath, `${JSON.stringify(normalized, null, 2)}\n`);
312
332
  const rcPath = shellRcPath({ homeDir, shell });
313
333
  let contents = "";
314
334
  try { contents = fs.readFileSync(rcPath, "utf8"); } catch (cause) { if (cause?.code !== "ENOENT") throw cause; }
315
335
  atomicWrite(rcPath, updateShellRc(contents, normalized));
336
+ const binary = await resolve();
337
+ // OpenCode 2 runs prompts through a background service that keeps the
338
+ // environment it started with, so new model variables need a restart.
339
+ if (await openCodeMajor(binary) >= 2) {
340
+ try {
341
+ await command([binary, "service", "restart"], { env: { ...env, ...modelEnvironment(normalized) } });
342
+ } catch {
343
+ throw Object.assign(new Error("Saved. Run `opencode service restart` to apply the new models."), { saved: true });
344
+ }
345
+ }
316
346
  return normalized;
317
347
  };
318
348
  const refresh = async ({ signal, forceRefresh = false } = {}) => {
319
349
  const binary = await resolve({ signal });
350
+ // OpenCode 2 removed --pure/--refresh and only lists providers with credentials.
351
+ if (await openCodeMajor(binary, signal) >= 2) {
352
+ return Object.values(parseOpenCodeModelList(await command([binary, "models"], { signal }))).flat();
353
+ }
320
354
  const providers = configuredProviderIds({ homeDir, env });
321
355
  try {
322
356
  const auth = await command([binary, "auth", "list"], { signal });
@@ -360,7 +394,19 @@ export async function runTerminalOcSwitcher({ input = process.stdin, output = pr
360
394
  previousLineCount = screenText.split("\n").length;
361
395
  };
362
396
  const finish = (nextResult) => { finished = true; result = nextResult; controller.abort(); };
363
- const persist = async () => { state = await saveState(state); dirty = false; status = "Guardado."; };
397
+ let saveWarning;
398
+ const persist = async () => {
399
+ try {
400
+ state = await saveState(state);
401
+ saveWarning = undefined;
402
+ status = "Guardado.";
403
+ } catch (error) {
404
+ if (!error?.saved) throw error;
405
+ saveWarning = error.message;
406
+ status = error.message;
407
+ }
408
+ dirty = false;
409
+ };
364
410
  const startRefresh = (first = false) => {
365
411
  catalogFresh = false;
366
412
  status = "Loading models...";
@@ -401,7 +447,7 @@ export async function runTerminalOcSwitcher({ input = process.stdin, output = pr
401
447
  }
402
448
  } else if (name === "r") startRefresh();
403
449
  else if (name === "s") persist().catch(() => { status = "Save failed."; });
404
- else if (name === "q") persist().then(() => finish({ status: "saved", state })).catch(() => finish({ status: "error", error: "Save failed." }));
450
+ else if (name === "q") persist().then(() => finish({ status: "saved", state, ...(saveWarning ? { warning: saveWarning } : {}) })).catch(() => finish({ status: "error", error: "Save failed." }));
405
451
  else if (name === "escape") selectedAgents.clear();
406
452
  } else {
407
453
  const available = filtered();
@@ -470,4 +516,5 @@ export function isDirectExecution({
470
516
  if (isDirectExecution()) {
471
517
  const result = await runInteractive();
472
518
  if (result.status === "error") { process.stderr.write(`${result.error}\n`); process.exitCode = 1; }
519
+ if (result.warning) process.stderr.write(`${result.warning}\n`);
473
520
  }