opencode-agent-harness 0.2.0 → 0.3.15

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.
@@ -12,7 +12,9 @@
12
12
  * (excluding `matrix.yaml`) is referenced by some journey (no orphan);
13
13
  * c. every flow is structurally well-formed: starts with `appId:`, contains at
14
14
  * least one `tapOn`/`assertVisible` command, and uses only known Maestro
15
- * command verbs at the top level;
15
+ * command verbs at the top level; every `runFlow: file:` include resolves
16
+ * (relative to the including file, recursively) with no missing path, no
17
+ * escape outside `flows/`, and no cycle;
16
18
  * d. every referenced screen resolves to a file under `mobile/`, and every
17
19
  * referenced testID resolves to a static `testID=` occurrence, an allowed
18
20
  * dynamic template literal (`testID={`prefix-${expr}`}`) in `mobile/`, or a
@@ -246,6 +248,10 @@ function walkFiles(dir, predicate, out) {
246
248
  * Collect the testIDs declared in `mobile/` source:
247
249
  *
248
250
  * - static: `testID="x"`, `testID={'x'}`, `testID={`x`}` → exact ids;
251
+ * - forwarded props: `phoneTestID="x"` / `submitTestID="x"` — this codebase
252
+ * passes the id into a shared field/button component as a `*TestID` prop,
253
+ * which lands on the element as `testID` at runtime (F-348; the shared
254
+ * session/subflow selectors live on these);
249
255
  * - dynamic: `testID={`prefix-${expr}`}` → the static prefix up to the first
250
256
  * interpolation (`prefix-`), so a flow may reference it either literally
251
257
  * (`prefix-…`) or with an `{id}` placeholder (`prefix-{id}`).
@@ -259,7 +265,7 @@ function collectMobileTestIds(mobileDir) {
259
265
  const dynamicPrefixes = new Set();
260
266
  const sources = [];
261
267
  walkFiles(mobileDir, (file) => /\.(ts|tsx)$/.test(file), sources);
262
- const staticPattern = /testID=\{?["'`]([^"'`${}]+)["'`]/g;
268
+ const staticPattern = /(?:testID|[A-Za-z]+TestID)=\{?["'`]([^"'`${}]+)["'`]/g;
263
269
  const dynamicPattern = /testID=\{\s*`([^`]*?)\$\{/g;
264
270
  sources.forEach((file) => {
265
271
  const content = readText(file);
@@ -359,6 +365,67 @@ function extractFlowTestIds(content) {
359
365
  return ids;
360
366
  }
361
367
 
368
+ function stripInlineComment(value) {
369
+ const text = String(value).trim();
370
+ const commentAt = text.search(/\s+#/);
371
+ return (commentAt === -1 ? text : text.slice(0, commentAt)).trim();
372
+ }
373
+
374
+ function unquote(value) {
375
+ return value.replace(/^["']|["']$/g, '');
376
+ }
377
+
378
+ /**
379
+ * Extract every `runFlow: file:` reference from a flow (F-348).
380
+ *
381
+ * Supports both Maestro shapes:
382
+ *
383
+ * - runFlow: _shared/session.yaml
384
+ * - runFlow:
385
+ * file: _shared/session.yaml
386
+ *
387
+ * Only the `file:` key that is a DIRECT child of `runFlow:` counts; a `file:`
388
+ * inside a `when:`/inline `commands:` block is a different command property and
389
+ * is ignored. A `runFlow:` with inline `commands:` (no `file:`) is not an
390
+ * include and yields nothing.
391
+ */
392
+ function extractRunFlowIncludes(content) {
393
+ const lines = content.split(/\r?\n/);
394
+ const includes = [];
395
+ lines.forEach((line, index) => {
396
+ const trimmed = line.trim();
397
+ if (trimmed === '' || trimmed.startsWith('#')) return;
398
+ const match = line.match(/^(\s*)-\s+runFlow:\s*(.*)$/);
399
+ if (!match) return;
400
+ const baseIndent = match[1].length;
401
+ const inlineValue = stripInlineComment(match[2]);
402
+ if (inlineValue && !inlineValue.startsWith('{') && !inlineValue.startsWith('|')) {
403
+ includes.push({ file: unquote(inlineValue), line: index + 1 });
404
+ return;
405
+ }
406
+
407
+ // Block form: the `file:` key is a direct child (first indentation level
408
+ // below the command), never a property of a nested `when:`/`commands:` map.
409
+ let childIndent = null;
410
+ for (let i = index + 1; i < lines.length; i += 1) {
411
+ const candidate = lines[i];
412
+ const candidateTrimmed = candidate.trim();
413
+ if (candidateTrimmed === '' || candidateTrimmed.startsWith('#')) continue;
414
+ const indent = candidate.match(/^(\s*)/)[1].length;
415
+ if (indent <= baseIndent) return;
416
+ if (childIndent === null) childIndent = indent;
417
+ if (indent !== childIndent) continue;
418
+ const fileMatch = candidate.match(/^\s*file:\s*(.*)$/);
419
+ if (fileMatch) {
420
+ const value = unquote(stripInlineComment(fileMatch[1]));
421
+ if (value) includes.push({ file: value, line: i + 1 });
422
+ return;
423
+ }
424
+ }
425
+ });
426
+ return includes;
427
+ }
428
+
362
429
  function validate() {
363
430
  const root = parseRootArg(process.argv.slice(2));
364
431
  const flowsDir = path.join(root, FLOWS_SUBPATH);
@@ -385,6 +452,54 @@ function validate() {
385
452
  const referencedFlows = new Set();
386
453
  const mobileTestIds = collectMobileTestIds(mobileDir);
387
454
 
455
+ // F-348 — `runFlow: file:` includes are part of the flow graph: their paths
456
+ // must resolve (relative to the including file, as Maestro does), they may
457
+ // nest, and their selectors are real coverage. Resolve the whole include graph
458
+ // once; a missing path, an escape outside `flows/`, a cycle, or a dangling
459
+ // testID inside a shared subflow is a violation, never a silent skip.
460
+ const flowTestIdsCache = new Map();
461
+ const includeStack = [];
462
+
463
+ function resolveFlowTestIds(flowAbs, displayName) {
464
+ if (flowTestIdsCache.has(flowAbs)) return flowTestIdsCache.get(flowAbs);
465
+ if (includeStack.includes(flowAbs)) {
466
+ const cycle = [...includeStack.slice(includeStack.indexOf(flowAbs)), flowAbs]
467
+ .map((entry) => path.relative(flowsDir, entry))
468
+ .join(' -> ');
469
+ violations.push(`flow "${displayName}": runFlow include cycle ${cycle}`);
470
+ return new Set();
471
+ }
472
+ const content = readText(flowAbs);
473
+ if (content === null) return new Set();
474
+
475
+ includeStack.push(flowAbs);
476
+ const ids = extractFlowTestIds(content);
477
+ extractRunFlowIncludes(content).forEach((include) => {
478
+ const label = `flow "${displayName}":${include.line}`;
479
+ const includeAbs = path.resolve(path.dirname(flowAbs), include.file);
480
+ if (includeAbs !== flowsDir && !includeAbs.startsWith(`${flowsDir}${path.sep}`)) {
481
+ violations.push(`${label}: runFlow file "${include.file}" escapes the flows directory`);
482
+ return;
483
+ }
484
+ if (!fs.existsSync(includeAbs)) {
485
+ violations.push(
486
+ `${label}: runFlow file "${include.file}" is missing (resolved to ${path.relative(root, includeAbs)})`
487
+ );
488
+ return;
489
+ }
490
+ const nested = readText(includeAbs);
491
+ if (nested === null || nested.trim() === '') {
492
+ violations.push(`${label}: runFlow file "${include.file}" is empty`);
493
+ return;
494
+ }
495
+ resolveFlowTestIds(includeAbs, path.relative(flowsDir, includeAbs)).forEach((id) => ids.add(id));
496
+ });
497
+ includeStack.pop();
498
+
499
+ flowTestIdsCache.set(flowAbs, ids);
500
+ return ids;
501
+ }
502
+
388
503
  parsed.journeys.forEach((journey) => {
389
504
  if (!journey.flow) return;
390
505
  referencedFlows.add(journey.flow);
@@ -401,7 +516,7 @@ function validate() {
401
516
 
402
517
  violations.push(...validateFlowStructure(journey.flow, content));
403
518
 
404
- const flowTestIds = extractFlowTestIds(content);
519
+ const flowTestIds = resolveFlowTestIds(flowFile, journey.flow);
405
520
  const declaredTestIds = new Set([...journey.testids, ...flowTestIds]);
406
521
  declaredTestIds.forEach((testId) => {
407
522
  if (!resolveMobileTestId(testId, mobileTestIds)) {
@@ -450,4 +565,4 @@ function main() {
450
565
 
451
566
  if (require.main === module) main();
452
567
 
453
- module.exports = { parseInlineList, parseMatrix, validate };
568
+ module.exports = { parseInlineList, parseMatrix, extractRunFlowIncludes, validate };
@@ -37,6 +37,7 @@ const PHASES = {
37
37
  ["test:governance"],
38
38
  ["test:concurrency"],
39
39
  ["test:capacity"],
40
+ ["test:worktrees"],
40
41
  ["test:ci-policy"],
41
42
  ["test:backlog"],
42
43
  ["test:wiring"],
@@ -0,0 +1,217 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * worktree-hygiene — one source of truth for "is this checkout closed out?".
5
+ *
6
+ * The failure this prevents: a session lands its feature worktree, then ends
7
+ * with "main is N commits behind and dirty" and "worktree <id> is still in
8
+ * place — prune it later". Both are invisible to every gate, so they
9
+ * accumulate: merged worktrees pile up, the main checkout drifts, and the next
10
+ * session works on top of unrelated uncommitted edits (which is exactly how
11
+ * two sessions collide in CHANGELOG.md / package.json / AGENTS.md).
12
+ *
13
+ * Everything here is read-only and cheap: `git worktree list --porcelain` plus
14
+ * one `git status` / `git rev-list` per worktree. Callers decide the policy:
15
+ *
16
+ * - finalize/ship: warn + converge the main checkout after a landing
17
+ * - check-worktrees: fail when a merged worktree is left behind or main is stale
18
+ * - orient: show the summary at session start
19
+ *
20
+ * Usage:
21
+ * node scripts/qa/worktree-hygiene.js [--root <dir>] [--base main] [--json]
22
+ */
23
+ const { spawnSync } = require("child_process");
24
+ const path = require("path");
25
+
26
+ function git(dir, args) {
27
+ const res = spawnSync("git", ["-C", dir, ...args], { encoding: "utf8" });
28
+ return {
29
+ ok: res.status === 0,
30
+ out: String(res.stdout || "").trim(),
31
+ err: String(res.stderr || "").trim(),
32
+ };
33
+ }
34
+
35
+ /* Parse `git worktree list --porcelain` into records. The first record is the
36
+ * main checkout (the only one without `worktree` pointing under .worktrees). */
37
+ function listWorktrees(root) {
38
+ const res = git(root, ["worktree", "list", "--porcelain"]);
39
+ if (!res.ok) return [];
40
+ const records = [];
41
+ let current = null;
42
+ for (const line of res.out.split(/\r?\n/)) {
43
+ if (line.startsWith("worktree ")) {
44
+ current = { path: line.slice("worktree ".length).trim(), head: null, branch: null, bare: false, detached: false, locked: false, prunable: false };
45
+ records.push(current);
46
+ } else if (!current) {
47
+ continue;
48
+ } else if (line.startsWith("HEAD ")) {
49
+ current.head = line.slice("HEAD ".length).trim();
50
+ } else if (line.startsWith("branch ")) {
51
+ const ref = line.slice("branch ".length).trim();
52
+ current.branch = ref.replace(/^refs\/heads\//, "");
53
+ } else if (line === "detached") {
54
+ current.detached = true;
55
+ } else if (line === "bare") {
56
+ current.bare = true;
57
+ } else if (line.startsWith("locked")) {
58
+ current.locked = true;
59
+ } else if (line.startsWith("prunable")) {
60
+ current.prunable = true;
61
+ }
62
+ }
63
+ return records;
64
+ }
65
+
66
+ /* Dirty entries, excluding ignored files. */
67
+ function statusEntries(dir) {
68
+ const res = git(dir, ["status", "--porcelain"]);
69
+ if (!res.ok) return [];
70
+ return res.out.split(/\r?\n/).filter((l) => l && !l.startsWith("!!"));
71
+ }
72
+
73
+ function revListCount(dir, range) {
74
+ const res = git(dir, ["rev-list", "--count", range]);
75
+ const n = Number(res.out);
76
+ return Number.isFinite(n) ? n : 0;
77
+ }
78
+
79
+ /* Is `ref` contained in `baseRef`? Callers fetch beforehand when they want a
80
+ * network-fresh answer; this function never touches the network. */
81
+ function isMerged(dir, ref, baseRef) {
82
+ if (!ref || !baseRef) return false;
83
+ return git(dir, ["merge-base", "--is-ancestor", ref, baseRef]).ok;
84
+ }
85
+
86
+ /**
87
+ * Summarise the repo's worktree hygiene.
88
+ *
89
+ * @param {string} root any path inside the repo (main or linked worktree)
90
+ * @param {string} base integration branch name (default "main")
91
+ * @param {string} [cwd] the caller's checkout, marked `current: true`
92
+ * @returns {object|null} null when `root` is not a git repo
93
+ */
94
+ function hygiene(root, base = "main", cwd = process.cwd()) {
95
+ const worktrees = listWorktrees(root);
96
+ if (!worktrees.length) return null;
97
+ const main = worktrees[0];
98
+ const currentPath = (() => {
99
+ const res = git(cwd, ["rev-parse", "--show-toplevel"]);
100
+ return res.ok ? res.out : path.resolve(cwd);
101
+ })();
102
+ const baseRef = `origin/${base}`;
103
+ const hasBase = git(root, ["rev-parse", "--verify", "--quiet", baseRef]).ok;
104
+ const mainBranch = main.branch || base;
105
+ const mainHead = main.head || git(main.path, ["rev-parse", "HEAD"]).out;
106
+
107
+ const records = worktrees.map((wt) => {
108
+ const dirty = statusEntries(wt.path);
109
+ const merged = wt.path === main.path ? false : hasBase && isMerged(wt.path, wt.head, baseRef);
110
+ return {
111
+ ...wt,
112
+ current: path.resolve(wt.path) === path.resolve(currentPath),
113
+ main: wt.path === main.path,
114
+ dirty: dirty.length,
115
+ dirtyEntries: dirty.slice(0, 20),
116
+ merged,
117
+ };
118
+ });
119
+
120
+ const linked = records.filter((r) => !r.main);
121
+ const mainDirty = records[0].dirtyEntries;
122
+ const mainAhead = hasBase ? revListCount(main.path, `${baseRef}..${mainHead}`) : 0;
123
+ const mainBehind = hasBase ? revListCount(main.path, `${mainHead}..${baseRef}`) : 0;
124
+
125
+ return {
126
+ base,
127
+ baseRef,
128
+ hasBase,
129
+ main: {
130
+ path: main.path,
131
+ branch: mainBranch,
132
+ head: mainHead,
133
+ dirty: mainDirty.length,
134
+ dirtyEntries: mainDirty,
135
+ ahead: mainAhead,
136
+ behind: mainBehind,
137
+ current: records[0].current,
138
+ },
139
+ worktrees: records,
140
+ linked,
141
+ // A linked worktree that is fully merged and clean is pure leftovers.
142
+ stale: linked.filter((w) => w.merged && w.dirty === 0),
143
+ // A merged worktree with uncommitted work cannot be pruned and will
144
+ // collide with whichever session edits the same files next.
145
+ mergedDirty: linked.filter((w) => w.merged && w.dirty > 0),
146
+ };
147
+ }
148
+
149
+ /* One-paragraph human summary, reused by finalize/ship/orient. */
150
+ function describe(h) {
151
+ if (!h) return "worktree hygiene: not a git repository";
152
+ const lines = [];
153
+ if (!h.hasBase) lines.push(`(no ${h.baseRef} yet — merge/behind counts skipped)`);
154
+ else if (h.main.behind > 0) lines.push(`main checkout is ${h.main.behind} commit(s) BEHIND ${h.baseRef}`);
155
+ else if (h.main.ahead > 0) lines.push(`main checkout is ${h.main.ahead} commit(s) AHEAD of ${h.baseRef} (unpushed)`);
156
+ else lines.push(`main checkout is in sync with ${h.baseRef}`);
157
+ if (h.main.dirty) lines.push(`main checkout has ${h.main.dirty} uncommitted entr${h.main.dirty === 1 ? "y" : "ies"}`);
158
+ if (h.stale.length) lines.push(`${h.stale.length} merged worktree(s) left on disk: ${h.stale.map((w) => w.branch || w.path).join(", ")}`);
159
+ if (h.mergedDirty.length)
160
+ lines.push(`${h.mergedDirty.length} merged worktree(s) still dirty (cannot prune): ${h.mergedDirty.map((w) => w.branch || w.path).join(", ")}`);
161
+ return lines.join("; ");
162
+ }
163
+
164
+ /* Close-out advice for a session that just landed a feature. */
165
+ function closeOutAdvice(h) {
166
+ const advice = [];
167
+ if (!h) return advice;
168
+ if (h.main.behind > 0) {
169
+ advice.push(
170
+ h.main.dirty
171
+ ? `main checkout is ${h.main.behind} behind and has uncommitted work — commit/stash it, then: git -C ${h.main.path} merge --ff-only ${h.baseRef}`
172
+ : `converge the main checkout: git -C ${h.main.path} merge --ff-only ${h.baseRef}`
173
+ );
174
+ }
175
+ if (h.stale.length) {
176
+ advice.push(`remove merged worktrees: node scripts/backlog.js worktree-prune`);
177
+ }
178
+ if (h.mergedDirty.length) {
179
+ advice.push(
180
+ `merged worktree(s) still dirty — commit or discard before pruning: ${h.mergedDirty
181
+ .map((w) => `${w.path} (${w.dirty} entries)`)
182
+ .join(", ")}`
183
+ );
184
+ }
185
+ return advice;
186
+ }
187
+
188
+ function main() {
189
+ const argv = process.argv.slice(2);
190
+ const args = { base: "main", json: false, root: process.cwd() };
191
+ for (let i = 0; i < argv.length; i++) {
192
+ const a = argv[i];
193
+ if (a === "--root") args.root = path.resolve(argv[++i]);
194
+ else if (a === "--base") args.base = argv[++i];
195
+ else if (a === "--json") args.json = true;
196
+ else if (a === "--help" || a === "-h") {
197
+ console.log("worktree-hygiene — report main-checkout drift and leftover merged worktrees\n\n node scripts/qa/worktree-hygiene.js [--root <dir>] [--base main] [--json]");
198
+ return;
199
+ }
200
+ }
201
+ const h = hygiene(args.root, args.base);
202
+ if (args.json) {
203
+ console.log(JSON.stringify(h, null, 2));
204
+ return;
205
+ }
206
+ console.log(`worktree hygiene (${h ? h.base : "n/a"})\n ${describe(h)}`);
207
+ for (const w of h ? h.linked : []) {
208
+ const flags = [w.merged ? "merged" : "unmerged", w.dirty ? `${w.dirty} dirty` : "clean", w.current ? "current" : null].filter(Boolean);
209
+ console.log(` - ${w.branch || "(detached)"} ${w.path} [${flags.join(", ")}]`);
210
+ }
211
+ const advice = closeOutAdvice(h);
212
+ if (advice.length) console.log("\nClose-out:\n" + advice.map((a) => ` - ${a}`).join("\n"));
213
+ }
214
+
215
+ if (require.main === module) main();
216
+
217
+ module.exports = { listWorktrees, statusEntries, isMerged, hygiene, describe, closeOutAdvice };
@@ -1,101 +1,101 @@
1
- param(
2
- [Parameter(Mandatory = $true)][string]$Target
3
- )
4
-
5
- $ErrorActionPreference = "Stop"
6
-
7
- $root = Split-Path -Parent $PSScriptRoot
8
-
9
- $aliases = @{
10
- "go" = "opencode-go/deepseek-v4.1-flash"
11
- "go-flash" = "opencode-go/deepseek-v4.1-flash"
12
- "go-deepseek" = "opencode-go/deepseek-v4.1-flash"
13
- "go-pro" = "opencode-go/deepseek-v4-pro"
14
- "deepseek" = "deepseek/deepseek-flash"
15
- "flash" = "deepseek/deepseek-flash"
16
- "deepseek-flash" = "deepseek/deepseek-flash"
17
- "direct" = "deepseek/deepseek-flash"
18
- "deepseek-pro" = "deepseek/deepseek-v4-pro"
19
- "deepseek-v4-pro" = "deepseek/deepseek-v4-pro"
20
- "pro" = "deepseek/deepseek-v4-pro"
21
- "nvidia" = "nvidia/moonshotai/kimi-k3"
22
- "kimi" = "nvidia/moonshotai/kimi-k3"
23
- "kimi-k3" = "nvidia/moonshotai/kimi-k3"
24
- "nemotron" = "nvidia/nemotron-3-ultra-550b-a55b:free"
25
- "nemotron-ultra" = "nvidia/nemotron-3-ultra-550b-a55b:free"
26
- "openrouter" = "openrouter/minimax/minimax-m3"
27
- "or" = "openrouter/minimax/minimax-m3"
28
- "minimax-m3" = "openrouter/minimax/minimax-m3"
29
- "m3" = "openrouter/minimax/minimax-m3"
30
- }
31
-
32
- $targetModel = $Target
33
- if ($aliases.ContainsKey($Target.ToLowerInvariant())) {
34
- $targetModel = $aliases[$Target.ToLowerInvariant()]
35
- }
36
- elseif (-not ($targetModel -match "^[a-zA-Z0-9._-]+/")) {
37
- $targetModel = "deepseek/$targetModel"
38
- }
39
-
40
- # The replace list is derived from the alias map so any model the script can
41
- # switch TO is also a model it can switch FROM. Without this, a value the user
42
- # hand-set (or set via a previous alias) but that is not in the find list is
43
- # invisible to the regex and the script silently reports "already set".
44
- $reasoningModels = @($aliases.Values | Sort-Object -Unique)
45
-
46
- $files = @(
47
- "opencode.json",
48
- ".opencode/agents/planner.md",
49
- ".opencode/agents/system-architect.md",
50
- ".opencode/agents/security-engineer.md",
51
- ".opencode/agents/diagnostics-expert.md",
52
- ".opencode/agents/product-manager.md",
53
- ".opencode/agents/qa-architect.md"
54
- )
55
-
56
- $changed = @()
57
- $skipped = @()
58
- foreach ($rel in $files) {
59
- $path = Join-Path $root $rel
60
- if (-not (Test-Path -LiteralPath $path)) {
61
- Write-Warning "missing: $rel"
62
- continue
63
- }
64
- $content = Get-Content -LiteralPath $path -Raw
65
- $new = $content
66
- $findHits = $false
67
- foreach ($m in $reasoningModels) {
68
- if ($m -eq $targetModel) { continue }
69
- if ($new -match [regex]::Escape($m)) { $findHits = $true }
70
- $new = $new -replace [regex]::Escape($m), $targetModel
71
- }
72
- if ($new -ne $content) {
73
- Set-Content -LiteralPath $path -Value $new -NoNewline
74
- $changed += $rel
75
- }
76
- elseif (-not $findHits -and $content -notmatch ([regex]::Escape($targetModel))) {
77
- # content != target, but the regex never matched — the current value is a
78
- # model id the script doesn't know how to replace. Surface it instead of
79
- # printing a misleading "already set".
80
- $current = ($content | Select-String -Pattern 'model:\s*"?([A-Za-z0-9._:\-/]+)"?' -AllMatches).Matches |
81
- ForEach-Object { $_.Groups[1].Value } |
82
- Where-Object { $_ -ne $targetModel -and $_ -notin $reasoningModels } |
83
- Select-Object -First 1
84
- $skipped += "$rel (current value `"$current`" not in replace list; edit by hand or add an alias)"
85
- }
86
- }
87
-
88
- Write-Output ("Switched reasoning-tier model -> {0}" -f $targetModel)
89
- if ($changed.Count -gt 0) {
90
- Write-Output "Updated:"
91
- $changed | ForEach-Object { Write-Output " - $_" }
92
- }
93
- if ($skipped.Count -gt 0) {
94
- Write-Warning "Skipped (current value not in replace list):"
95
- $skipped | ForEach-Object { Write-Warning " - $_" }
96
- Write-Warning "Add an alias to scripts/switch-reasoning-model.ps1 (or edit the file by hand)."
97
- }
98
- if ($changed.Count -eq 0 -and $skipped.Count -eq 0) {
99
- Write-Output "No files changed (already set)."
100
- }
101
- Write-Output "Restart opencode for the change to take effect."
1
+ param(
2
+ [Parameter(Mandatory = $true)][string]$Target
3
+ )
4
+
5
+ $ErrorActionPreference = "Stop"
6
+
7
+ $root = Split-Path -Parent $PSScriptRoot
8
+
9
+ $aliases = @{
10
+ "go" = "opencode-go/deepseek-v4.1-flash"
11
+ "go-flash" = "opencode-go/deepseek-v4.1-flash"
12
+ "go-deepseek" = "opencode-go/deepseek-v4.1-flash"
13
+ "go-pro" = "opencode-go/deepseek-v4-pro"
14
+ "deepseek" = "deepseek/deepseek-flash"
15
+ "flash" = "deepseek/deepseek-flash"
16
+ "deepseek-flash" = "deepseek/deepseek-flash"
17
+ "direct" = "deepseek/deepseek-flash"
18
+ "deepseek-pro" = "deepseek/deepseek-v4-pro"
19
+ "deepseek-v4-pro" = "deepseek/deepseek-v4-pro"
20
+ "pro" = "deepseek/deepseek-v4-pro"
21
+ "nvidia" = "nvidia/moonshotai/kimi-k3"
22
+ "kimi" = "nvidia/moonshotai/kimi-k3"
23
+ "kimi-k3" = "nvidia/moonshotai/kimi-k3"
24
+ "nemotron" = "nvidia/nemotron-3-ultra-550b-a55b:free"
25
+ "nemotron-ultra" = "nvidia/nemotron-3-ultra-550b-a55b:free"
26
+ "openrouter" = "openrouter/minimax/minimax-m3"
27
+ "or" = "openrouter/minimax/minimax-m3"
28
+ "minimax-m3" = "openrouter/minimax/minimax-m3"
29
+ "m3" = "openrouter/minimax/minimax-m3"
30
+ }
31
+
32
+ $targetModel = $Target
33
+ if ($aliases.ContainsKey($Target.ToLowerInvariant())) {
34
+ $targetModel = $aliases[$Target.ToLowerInvariant()]
35
+ }
36
+ elseif (-not ($targetModel -match "^[a-zA-Z0-9._-]+/")) {
37
+ $targetModel = "deepseek/$targetModel"
38
+ }
39
+
40
+ # The replace list is derived from the alias map so any model the script can
41
+ # switch TO is also a model it can switch FROM. Without this, a value the user
42
+ # hand-set (or set via a previous alias) but that is not in the find list is
43
+ # invisible to the regex and the script silently reports "already set".
44
+ $reasoningModels = @($aliases.Values | Sort-Object -Unique)
45
+
46
+ $files = @(
47
+ "opencode.json",
48
+ ".opencode/agents/planner.md",
49
+ ".opencode/agents/system-architect.md",
50
+ ".opencode/agents/security-engineer.md",
51
+ ".opencode/agents/diagnostics-expert.md",
52
+ ".opencode/agents/product-manager.md",
53
+ ".opencode/agents/qa-architect.md"
54
+ )
55
+
56
+ $changed = @()
57
+ $skipped = @()
58
+ foreach ($rel in $files) {
59
+ $path = Join-Path $root $rel
60
+ if (-not (Test-Path -LiteralPath $path)) {
61
+ Write-Warning "missing: $rel"
62
+ continue
63
+ }
64
+ $content = Get-Content -LiteralPath $path -Raw
65
+ $new = $content
66
+ $findHits = $false
67
+ foreach ($m in $reasoningModels) {
68
+ if ($m -eq $targetModel) { continue }
69
+ if ($new -match [regex]::Escape($m)) { $findHits = $true }
70
+ $new = $new -replace [regex]::Escape($m), $targetModel
71
+ }
72
+ if ($new -ne $content) {
73
+ Set-Content -LiteralPath $path -Value $new -NoNewline
74
+ $changed += $rel
75
+ }
76
+ elseif (-not $findHits -and $content -notmatch ([regex]::Escape($targetModel))) {
77
+ # content != target, but the regex never matched — the current value is a
78
+ # model id the script doesn't know how to replace. Surface it instead of
79
+ # printing a misleading "already set".
80
+ $current = ($content | Select-String -Pattern 'model:\s*"?([A-Za-z0-9._:\-/]+)"?' -AllMatches).Matches |
81
+ ForEach-Object { $_.Groups[1].Value } |
82
+ Where-Object { $_ -ne $targetModel -and $_ -notin $reasoningModels } |
83
+ Select-Object -First 1
84
+ $skipped += "$rel (current value `"$current`" not in replace list; edit by hand or add an alias)"
85
+ }
86
+ }
87
+
88
+ Write-Output ("Switched reasoning-tier model -> {0}" -f $targetModel)
89
+ if ($changed.Count -gt 0) {
90
+ Write-Output "Updated:"
91
+ $changed | ForEach-Object { Write-Output " - $_" }
92
+ }
93
+ if ($skipped.Count -gt 0) {
94
+ Write-Warning "Skipped (current value not in replace list):"
95
+ $skipped | ForEach-Object { Write-Warning " - $_" }
96
+ Write-Warning "Add an alias to scripts/switch-reasoning-model.ps1 (or edit the file by hand)."
97
+ }
98
+ if ($changed.Count -eq 0 -and $skipped.Count -eq 0) {
99
+ Write-Output "No files changed (already set)."
100
+ }
101
+ Write-Output "Restart opencode for the change to take effect."