pantheon-opencode 1.6.1 → 1.6.2-beta.10

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.
Files changed (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
@@ -1,6 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import * as clack from '@clack/prompts'
4
+ import {
5
+ createDecisionRouterConfig,
6
+ DECISION_ROUTER_PROVIDERS,
7
+ DEFAULT_DECISION_ROUTER_CONFIG,
8
+ migrateDecisionRouterConfig,
9
+ } from './decision-router-config.mjs'
4
10
  import { PROMPT_CANCELED } from './prompt-result.mjs'
5
11
  import { strings } from './strings.mjs'
6
12
 
@@ -48,17 +54,18 @@ export async function promptReview(
48
54
  /**
49
55
  * Collect interactive setup choices before the installer begins any writes.
50
56
  *
51
- * @param {{ components?: string[], defaultComponents?: string[], noMcp?: boolean, prompts?: typeof clack, isTTY?: boolean }} [options]
52
- * @returns {Promise<{ components?: Set<string>, target?: string, confirmed?: boolean, canceled?: boolean, cancelPoint?: string }>}
57
+ * @param {{ components?: string[], defaultComponents?: string[], noMcp?: boolean, prompts?: typeof clack, isTTY?: boolean, getDecisionRouterConfig?: (target: string) => unknown }} [options]
58
+ * @returns {Promise<{ components?: Set<string>, target?: string, decisionRouterConfig?: object, canceled?: boolean, cancelPoint?: string }>}
53
59
  *
54
- * `cancelPoint` names the step the user stopped at (`components`, `target`,
55
- * `confirmation`), so the caller can print one explainable line and persist the
56
- * same stable key in the run record.
60
+ * `cancelPoint` names the setup choice where the user stopped (`components` or
61
+ * `target`), so the caller can print one explainable line and persist the same
62
+ * stable key in the run record.
57
63
  */
58
64
  export async function runInteractiveInstall({
59
65
  components = [],
60
66
  defaultComponents = [],
61
67
  noMcp = false,
68
+ getDecisionRouterConfig = () => DEFAULT_DECISION_ROUTER_CONFIG,
62
69
  prompts = clack,
63
70
  isTTY = isTerminal(),
64
71
  } = {}) {
@@ -66,9 +73,18 @@ export async function runInteractiveInstall({
66
73
  const defaults = (defaultComponents.length > 0 ? defaultComponents : components).filter(isAllowed)
67
74
  const defaultSet = new Set(defaults)
68
75
 
69
- // Preserve the prior no-TTY fallback (defaults, global target, and no apply
70
- // authorization) without asking a terminal prompt library to access stdin.
71
- if (!isTTY) return { components: defaultSet, target: 'global', confirmed: true }
76
+ // Preserve the same component and target defaults without asking a terminal
77
+ // prompt library to access stdin. Apply authorization is handled once, after
78
+ // the installer has built and displayed the complete plan. Re-read the
79
+ // selected default target's preference so --interactive without a TTY does
80
+ // not reset an existing provider choice or consent on update.
81
+ if (!isTTY) {
82
+ return {
83
+ components: defaultSet,
84
+ target: 'global',
85
+ decisionRouterConfig: migrateDecisionRouterConfig(getDecisionRouterConfig('global')),
86
+ }
87
+ }
72
88
 
73
89
  prompts.intro?.('OpenCode Installer')
74
90
 
@@ -110,13 +126,86 @@ export async function runInteractiveInstall({
110
126
  })
111
127
  if (cancelPrompt(prompts, target, 'target')) return { canceled: true, cancelPoint: 'target' }
112
128
 
113
- const confirmed = await prompts.confirm({
114
- message: `Install ${selectedComponents.size} component(s) in ${target === 'global' ? 'global config' : 'current project'}?`,
115
- initialValue: true,
129
+ // The old four-option metadata prompt (Local/OpenAI/Jev/Auto) recorded an
130
+ // installer preference that controlled nothing at runtime and confused
131
+ // everyone. The interactive question is now the honest one: configure the
132
+ // Jev decision model now (one write, explicit caps) or skip — the CLI
133
+ // (`decision-router setup-model`) remains the later path either way. The
134
+ // legacy installer-state record stays at its default (Local): metadata the
135
+ // runtime never reads, while real consent lives in the user-level config
136
+ // that setup-model writes.
137
+ const jevActivation = await prompts.select({
138
+ message:
139
+ 'Configure the Jev decision model now? (advisory tool for Zeus; one write: selection, consent, caps, period — USD caps are required)',
140
+ options: [
141
+ {
142
+ label: 'Skip (default)',
143
+ value: 'skip',
144
+ hint: 'Configure later: decision-router setup-model',
145
+ },
146
+ {
147
+ label: 'OpenCode Console Jev (stock)',
148
+ value: 'opencode-console-jev/jev-1.13',
149
+ hint: 'Billed to your Console; uses host-owned auth',
150
+ },
151
+ {
152
+ label: 'Console Jev free variant',
153
+ value: 'opencode-console-jev-free/jev-1.13-free',
154
+ hint: 'No paid budget consumed; host-owned auth',
155
+ },
156
+ {
157
+ label: 'TypeSafe Jev (direct)',
158
+ value: 'typesafe-jev/jev-1.14.0',
159
+ hint: 'Installer merges the provider entry; you sign in with your TypeSafe key (/connect)',
160
+ },
161
+ ],
162
+ initialValue: 'skip',
116
163
  })
117
- if (cancelPrompt(prompts, confirmed, 'confirmation')) {
118
- return { canceled: true, cancelPoint: 'confirmation' }
164
+ if (cancelPrompt(prompts, jevActivation, 'decisionRouter')) {
165
+ return { canceled: true, cancelPoint: 'decisionRouter' }
166
+ }
167
+ // Only known targets activate; anything else (a stale stub, a renamed
168
+ // option) degrades to skip instead of configuring a wrong route.
169
+ const KNOWN_JEV_TARGETS = new Set([
170
+ 'opencode-console-jev/jev-1.13',
171
+ 'opencode-console-jev-free/jev-1.13-free',
172
+ 'typesafe-jev/jev-1.14.0',
173
+ ])
174
+ const activationChoice =
175
+ typeof jevActivation === 'string' && KNOWN_JEV_TARGETS.has(jevActivation)
176
+ ? jevActivation
177
+ : 'skip'
178
+ let decisionModelActivation = null
179
+ if (activationChoice !== 'skip') {
180
+ // Caps prompts degrade to the recommended defaults when the prompt
181
+ // implementation has no text input (stubbed tests, restricted TTYs).
182
+ const askText = async (message, fallback) => {
183
+ if (typeof prompts.text !== 'function') return fallback
184
+ const answer = await prompts.text({ message, defaultValue: fallback, placeholder: fallback })
185
+ if (cancelPrompt(prompts, answer, 'decisionRouter')) {
186
+ return { canceled: true }
187
+ }
188
+ return String(answer || fallback)
189
+ }
190
+ const monthly = await askText('Monthly USD cap for decision calls (e.g. 5)', '5')
191
+ if (monthly && typeof monthly === 'object') {
192
+ return { canceled: true, cancelPoint: 'decisionRouter' }
193
+ }
194
+ const perDecision = await askText('Per-decision USD cap (e.g. 0.10)', '0.10')
195
+ if (perDecision && typeof perDecision === 'object') {
196
+ return { canceled: true, cancelPoint: 'decisionRouter' }
197
+ }
198
+ decisionModelActivation = {
199
+ target: activationChoice,
200
+ monthly: String(monthly || '5'),
201
+ perDecision: String(perDecision || '0.10'),
202
+ }
119
203
  }
120
204
 
121
- return { components: selectedComponents, target, confirmed }
205
+ return {
206
+ components: selectedComponents,
207
+ target,
208
+ decisionRouterConfig: createDecisionRouterConfig(DECISION_ROUTER_PROVIDERS[0], false),
209
+ decisionModelActivation,
210
+ }
122
211
  }
@@ -33,7 +33,7 @@
33
33
  * Build and REGISTER a SIGINT handler.
34
34
  *
35
35
  * @param {{
36
- * message: string,
36
+ * message: string | (() => string),
37
37
  * json?: boolean,
38
38
  * onInterrupt?: () => void,
39
39
  * endGaugeLine?: () => void,
@@ -62,8 +62,9 @@ export function createInterruptHandler({
62
62
  // The progress gauge owns the current terminal line; close it so the
63
63
  // message is not appended to a half-drawn bar and then erased.
64
64
  endGaugeLine()
65
- if (json) writeStderr(message)
66
- else logStderr(message)
65
+ const line = typeof message === 'function' ? message() : message
66
+ if (json) writeStderr(line)
67
+ else logStderr(line)
67
68
  onInterrupt()
68
69
  } finally {
69
70
  exit(130)
@@ -0,0 +1,164 @@
1
+ import { opencodeWildcardPatternsOverlap } from './opencode-wildcard.mjs'
2
+
3
+ /** Canonical OpenCode V2 MCP action-name normalization shared by all writers. */
4
+
5
+ export function normalizeMcpPermissionSegment(value) {
6
+ return value.replace(/[^a-zA-Z0-9_]/g, '_')
7
+ }
8
+
9
+ /** V1 spellings support V1 hosts; normalized spellings are required by V2. */
10
+ export function mcpPermissionAliases(value) {
11
+ return [...new Set([value, normalizeMcpPermissionSegment(value)])]
12
+ }
13
+
14
+ export function mcpServerPermissionActions(server) {
15
+ return mcpPermissionAliases(server).map((alias) => `${alias}_*`)
16
+ }
17
+
18
+ /**
19
+ * These generated action patterns are all fixed prefixes followed by `*`.
20
+ * Their languages intersect exactly when one fixed prefix contains the other.
21
+ */
22
+ export function mcpPermissionActionPatternsOverlap(left, right) {
23
+ return opencodeWildcardPatternsOverlap(left, right)
24
+ }
25
+
26
+ export function mcpServerPermissionScopesOverlap(left, right) {
27
+ return mcpServerPermissionActions(left).some((leftAction) =>
28
+ mcpServerPermissionActions(right).some((rightAction) =>
29
+ mcpPermissionActionPatternsOverlap(leftAction, rightAction),
30
+ ),
31
+ )
32
+ }
33
+
34
+ /** Refuse distinct V1 server names whose generated action globs overlap in V2. */
35
+ export function assertMcpServerPermissionScopesUnambiguous(rules) {
36
+ for (let leftIndex = 0; leftIndex < rules.length; leftIndex += 1) {
37
+ const left = rules[leftIndex]
38
+ for (let rightIndex = leftIndex + 1; rightIndex < rules.length; rightIndex += 1) {
39
+ const right = rules[rightIndex]
40
+ if (
41
+ left.server !== right.server &&
42
+ mcpServerPermissionScopesOverlap(left.server, right.server)
43
+ ) {
44
+ throw new TypeError(
45
+ 'Distinct MCP permission server scopes overlap after OpenCode V2 action normalization.',
46
+ )
47
+ }
48
+ }
49
+ }
50
+ }
51
+
52
+ /** Refuse policy scopes that also match a distinct configured MCP server. */
53
+ export function assertMcpPermissionScopesDoNotAliasConfiguredServers(
54
+ policyServers,
55
+ configuredServers,
56
+ ) {
57
+ for (const policyServer of policyServers) {
58
+ for (const configuredServer of configuredServers) {
59
+ if (
60
+ policyServer !== configuredServer &&
61
+ mcpServerPermissionScopesOverlap(policyServer, configuredServer)
62
+ ) {
63
+ throw new TypeError(
64
+ 'An MCP permission scope overlaps a distinct configured server after OpenCode V2 action normalization.',
65
+ )
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Agent MCP metadata emits default server denies and then explicit grants.
73
+ * Refuse grants that can also match a different server's denied action scope.
74
+ */
75
+ export function assertMcpPermissionServerGrantsUnambiguous(servers) {
76
+ const scopes = servers.map(({ server, tools }) => ({
77
+ server,
78
+ tools,
79
+ effect: tools === 'all' ? 'allow' : 'deny',
80
+ }))
81
+
82
+ for (let leftIndex = 0; leftIndex < scopes.length; leftIndex += 1) {
83
+ const left = scopes[leftIndex]
84
+ for (let rightIndex = leftIndex + 1; rightIndex < scopes.length; rightIndex += 1) {
85
+ const right = scopes[rightIndex]
86
+ if (
87
+ left.effect !== right.effect &&
88
+ mcpServerPermissionScopesOverlap(left.server, right.server)
89
+ ) {
90
+ throw new TypeError('Overlapping MCP permission scopes have conflicting agent effects.')
91
+ }
92
+ }
93
+ }
94
+
95
+ for (const grant of scopes) {
96
+ if (!Array.isArray(grant.tools)) continue
97
+ const grantActions = grant.tools.flatMap((tool) =>
98
+ mcpPermissionAliases(grant.server).flatMap((serverAlias) =>
99
+ mcpPermissionAliases(tool).map((toolAlias) => `${serverAlias}_${toolAlias}`),
100
+ ),
101
+ )
102
+ for (const deny of scopes) {
103
+ if (grant.server === deny.server || deny.effect !== 'deny') continue
104
+ if (
105
+ grantActions.some((action) =>
106
+ mcpServerPermissionActions(deny.server).some((scope) =>
107
+ mcpPermissionActionPatternsOverlap(action, scope),
108
+ ),
109
+ )
110
+ ) {
111
+ throw new TypeError('An MCP tool grant overlaps a different server deny scope.')
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ /** Refuse generated MCP allows that would replace an explicit agent deny/ask. */
118
+ export function assertMcpGeneratedPermissionsDoNotWeakenExplicitRules(explicit, generated) {
119
+ if (explicit === undefined) return
120
+ if (explicit === null || typeof explicit !== 'object' || Array.isArray(explicit)) {
121
+ throw new TypeError(
122
+ 'Explicit agent permissions must be an object when combined with mcp_tools.',
123
+ )
124
+ }
125
+
126
+ const grants = Object.entries(generated).filter(([, effect]) => effect === 'allow')
127
+ if (grants.length === 0) return
128
+
129
+ for (const [action, rule] of Object.entries(explicit)) {
130
+ if (!grants.some(([grantAction]) => opencodeWildcardPatternsOverlap(action, grantAction))) {
131
+ continue
132
+ }
133
+ const isResourceMap = rule !== null && typeof rule === 'object' && !Array.isArray(rule)
134
+ if (typeof rule !== 'string' && !isResourceMap) {
135
+ throw new TypeError(
136
+ 'An overlapping explicit agent permission cannot be safely combined with mcp_tools.',
137
+ )
138
+ }
139
+ const effects = typeof rule === 'string' ? [rule] : isResourceMap ? Object.values(rule) : []
140
+ if (effects.some((effect) => !['allow', 'ask', 'deny'].includes(effect))) {
141
+ throw new TypeError(
142
+ 'An overlapping explicit agent permission cannot be safely combined with mcp_tools.',
143
+ )
144
+ }
145
+ if (effects.some((effect) => effect === 'deny' || effect === 'ask')) {
146
+ throw new TypeError(
147
+ 'A generated MCP grant overlaps an explicit agent deny or ask permission.',
148
+ )
149
+ }
150
+ }
151
+ }
152
+
153
+ /** Refuse names whose V2-normalized action cannot distinguish their source. */
154
+ export function assertMcpPermissionNamesUnambiguous(names) {
155
+ const normalizedOwners = new Map()
156
+ for (const name of names) {
157
+ const normalized = normalizeMcpPermissionSegment(name)
158
+ const owner = normalizedOwners.get(normalized)
159
+ if (owner !== undefined && owner !== name) {
160
+ throw new TypeError('MCP names collide after OpenCode V2 permission normalization.')
161
+ }
162
+ normalizedOwners.set(normalized, name)
163
+ }
164
+ }
@@ -11,9 +11,8 @@
11
11
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
12
12
  import { dirname, join } from 'node:path'
13
13
  import { fileURLToPath } from 'node:url'
14
- import { configure as configureUi, tag } from './cli-ui.mjs'
15
14
  import { ACTIONS, fingerprintOutput, recordChange } from './plan.mjs'
16
- import { createInitialState, readState, writeState } from './state.mjs'
15
+ import { createInitialState, MIGRATION_SCHEMA_VERSION, readState, writeState } from './state.mjs'
17
16
 
18
17
  const __dirname = dirname(fileURLToPath(import.meta.url))
19
18
  const ROOT = join(__dirname, '..', '..')
@@ -47,76 +46,84 @@ export function detectVersion(target) {
47
46
  * @param {string} target - Installation directory
48
47
  * @param {string|null} currentVersion - Detected version (null = fresh install)
49
48
  * @param {{ dryRun?: boolean, recorder?: (change: object) => void }} [options]
50
- * @returns {{ applied: number, messages: string[] }}
49
+ * @returns {{ applied: number, messages: string[], plannedState: object|null, status?: 'invalid'|'unsupported', marker?: unknown, message?: string }}
51
50
  */
52
- export function runMigrations(
53
- target,
54
- currentVersion,
55
- { dryRun = false, recorder = null, updatedAt = new Date().toISOString() } = {},
56
- ) {
51
+ export function runMigrations(target, options = {}, legacyOptions = {}) {
52
+ // Preserve the old `(target, version, options)` call shape for downstream
53
+ // callers while making the persisted migration marker authoritative.
54
+ const explicitVersion = typeof options === 'string' ? options : null
55
+ const {
56
+ dryRun = false,
57
+ recorder = null,
58
+ updatedAt = new Date().toISOString(),
59
+ } = typeof options === 'object' && options !== null ? options : legacyOptions
60
+ const state = readState(target)
61
+ if (!state) return { applied: 0, messages: [], plannedState: null }
62
+
63
+ const schemaMarker = state.migration_schema_version
64
+ if (schemaMarker !== null && schemaMarker !== undefined) {
65
+ const parsedMarker = parseSemver(schemaMarker)
66
+ if (!parsedMarker) return blockedMigration('invalid', schemaMarker)
67
+ if (compareSemver(parsedMarker, parseSemver(MIGRATION_SCHEMA_VERSION)) > 0) {
68
+ return blockedMigration('unsupported', schemaMarker)
69
+ }
70
+ }
71
+
72
+ const currentVersion =
73
+ state.migration_schema_version ?? explicitVersion ?? state.pantheon_version ?? null
57
74
  const applied = []
58
- const semver = parseSemver(currentVersion)
75
+ let cursor = parseSemver(currentVersion)
59
76
 
60
77
  // ── Migration: v3.10.0 → v3.18.0 ──────────────────────────────────
61
78
  // Fix dangling references, add Memory Protocol
62
- if (semver && lt(semver, [3, 18, 0])) {
79
+ if (cursor && compareSemver(cursor, parseSemver('3.18.0')) < 0) {
63
80
  applied.push({
64
- from: formatSemver(semver),
81
+ from: formatSemver(cursor),
65
82
  to: '3.18.0',
66
83
  description: 'Fix dangling references, add Memory Protocol',
67
84
  })
68
- semver[0] = 3
69
- semver[1] = 18
70
- semver[2] = 0
85
+ cursor = parseSemver('3.18.0')
71
86
  }
72
87
 
73
88
  // ── Migration: v3.18.0 → v3.19.0 ──────────────────────────────────
74
89
  // Add runtime component, _pantheon_paths
75
- if (semver && lt(semver, [3, 19, 0])) {
90
+ if (cursor && compareSemver(cursor, parseSemver('3.19.0')) < 0) {
76
91
  applied.push({
77
- from: formatSemver(semver),
92
+ from: formatSemver(cursor),
78
93
  to: '3.19.0',
79
94
  description: 'Add runtime component, _pantheon_paths',
80
95
  })
81
- semver[0] = 3
82
- semver[1] = 19
83
- semver[2] = 0
96
+ cursor = parseSemver('3.19.0')
84
97
  }
85
98
 
86
99
  // ── Migration: v3.19.0 → v3.19.1 ──────────────────────────────────
87
100
  // Add persistence MCP, fix 157 dangling refs
88
- if (semver && lt(semver, [3, 19, 1])) {
101
+ if (cursor && compareSemver(cursor, parseSemver('3.19.1')) < 0) {
89
102
  applied.push({
90
- from: formatSemver(semver),
103
+ from: formatSemver(cursor),
91
104
  to: '3.19.1',
92
105
  description: 'Add persistence MCP, fix dangling refs',
93
106
  })
94
- semver[0] = 3
95
- semver[1] = 19
96
- semver[2] = 1
107
+ cursor = parseSemver('3.19.1')
97
108
  }
98
109
 
99
110
  // ── Migration: v3.19.1 → v3.19.2 ──────────────────────────────────
100
111
  // Upgrade state schema from v1 to v2
101
- if (semver && lt(semver, [3, 19, 2])) {
112
+ if (cursor && compareSemver(cursor, parseSemver(MIGRATION_SCHEMA_VERSION)) < 0) {
102
113
  applied.push({
103
- from: formatSemver(semver),
104
- to: '3.19.2',
114
+ from: formatSemver(cursor),
115
+ to: MIGRATION_SCHEMA_VERSION,
105
116
  description: 'Upgrade install state schema to v2 with component tracking',
106
117
  })
107
- semver[0] = 3
108
- semver[1] = 19
109
- semver[2] = 2
118
+ cursor = parseSemver(MIGRATION_SCHEMA_VERSION)
110
119
  }
111
120
 
112
121
  // ── Write updated state ───────────────────────────────────────────
113
- if (applied.length > 0) {
122
+ const markerChanged = state.migration_schema_version !== MIGRATION_SCHEMA_VERSION
123
+ if (applied.length > 0 || markerChanged) {
114
124
  const statePath = join(target, '.pantheon', 'install-state.json')
115
- const newVersion = formatSemver(semver)
116
- let state = readState(target)
117
- const stateExisted = state !== null
118
- if (!state) state = createInitialState(newVersion, updatedAt)
119
- state.pantheon_version = newVersion
125
+ const stateExisted = true
126
+ state.applied_migrations ??= []
120
127
  for (const m of applied) {
121
128
  state.applied_migrations.push({
122
129
  from: m.from,
@@ -133,6 +140,7 @@ export function runMigrations(
133
140
  runtime: { version: 1, status: 'installed' },
134
141
  }
135
142
  }
143
+ state.migration_schema_version = MIGRATION_SCHEMA_VERSION
136
144
  state.updated_at = updatedAt
137
145
  state.schema_version = 2
138
146
  const stateContent = `${JSON.stringify(state, null, 2)}\n`
@@ -155,12 +163,20 @@ export function runMigrations(
155
163
  }
156
164
 
157
165
  return {
158
- applied: applied.length,
166
+ applied: 0,
159
167
  messages: applied.map((m) => `${m.from} → ${m.to}: ${m.description}`),
160
168
  plannedState: null,
161
169
  }
162
170
  }
163
171
 
172
+ function blockedMigration(status, marker) {
173
+ const message =
174
+ status === 'unsupported'
175
+ ? `Migration schema ${marker} is newer than supported ${MIGRATION_SCHEMA_VERSION}; refusing to downgrade or modify the installation.`
176
+ : 'Invalid migration schema marker; refusing to modify the installation.'
177
+ return { applied: 0, messages: [], plannedState: null, status, marker, message }
178
+ }
179
+
164
180
  // ---------------------------------------------------------------------------
165
181
  // Checkpoint system for crash recovery
166
182
  // ---------------------------------------------------------------------------
@@ -279,7 +295,7 @@ export function rollbackMigration(target, version) {
279
295
  console.log(` Rolling back migration: ${targetMigration.from} -> ${targetMigration.to}`)
280
296
 
281
297
  targetMigration.status = 'rolled_back'
282
- state.pantheon_version = targetMigration.from
298
+ state.migration_schema_version = targetMigration.from
283
299
  writeState(target, state)
284
300
 
285
301
  console.log(` [OK] Rolled back to ${targetMigration.from}`)
@@ -307,46 +323,69 @@ export function listAppliedMigrations(target) {
307
323
  // Minimal semver helpers (no external deps)
308
324
  // ---------------------------------------------------------------------------
309
325
 
310
- /**
311
- * Parse "x.y.z" → [major, minor, patch] or null.
312
- * @param {string|null} v
313
- * @returns {number[]|null}
314
- */
315
- function parseSemver(v) {
316
- if (!v || typeof v !== 'string') return null
317
- const parts = v.split('.').map(Number)
318
- if (parts.length < 2 || parts.some(Number.isNaN)) return null
319
- return [parts[0], parts[1], parts[2] ?? 0]
320
- }
321
-
322
- /**
323
- * Format [major, minor, patch] → "x.y.z".
324
- * @param {number[]} v
325
- * @returns {string}
326
- */
327
- function formatSemver(v) {
328
- return `${v[0]}.${v[1]}.${v[2]}`
326
+ /** Parse strict SemVer precedence, accepting an optional `v` and build metadata. */
327
+ export function parseSemver(value) {
328
+ if (typeof value !== 'string') return null
329
+ const match = value.match(
330
+ /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,
331
+ )
332
+ if (!match) return null
333
+ const prerelease = match[4]
334
+ ? match[4].split('.').map((identifier) => {
335
+ if (!/^\d+$/.test(identifier)) return identifier
336
+ if (identifier.length > 1 && identifier.startsWith('0')) return null
337
+ return Number(identifier)
338
+ })
339
+ : []
340
+ if (prerelease.includes(null)) return null
341
+
342
+ const parsed = {
343
+ major: Number(match[1]),
344
+ minor: Number(match[2]),
345
+ patch: Number(match[3]),
346
+ prerelease,
347
+ }
348
+ Object.defineProperty(parsed, 'compare', {
349
+ enumerable: false,
350
+ value: (other) => compareSemver(parsed, other),
351
+ })
352
+ return parsed
329
353
  }
330
354
 
331
- /**
332
- * Compare two semver arrays: is a < b?
333
- * @param {number[]} a
334
- * @param {number[]} b
335
- * @returns {boolean}
336
- */
337
- function lt(a, b) {
338
- for (let i = 0; i < 3; i++) {
339
- if ((a[i] ?? 0) !== (b[i] ?? 0)) {
340
- return (a[i] ?? 0) < (b[i] ?? 0)
355
+ function compareSemver(left, right) {
356
+ for (const field of ['major', 'minor', 'patch']) {
357
+ if (left[field] !== right[field]) return left[field] < right[field] ? -1 : 1
358
+ }
359
+ const a = left.prerelease
360
+ const b = right.prerelease
361
+ if (a.length === 0 || b.length === 0) {
362
+ if (a.length === b.length) return 0
363
+ return a.length === 0 ? 1 : -1
364
+ }
365
+ const length = Math.min(a.length, b.length)
366
+ for (let index = 0; index < length; index += 1) {
367
+ if (a[index] === b[index]) continue
368
+ if (typeof a[index] === 'number' && typeof b[index] === 'number') {
369
+ return a[index] < b[index] ? -1 : 1
341
370
  }
371
+ if (typeof a[index] === 'number') return -1
372
+ if (typeof b[index] === 'number') return 1
373
+ return a[index] < b[index] ? -1 : 1
342
374
  }
343
- return false
375
+ if (a.length === b.length) return 0
376
+ return a.length < b.length ? -1 : 1
377
+ }
378
+
379
+ function formatSemver(value) {
380
+ const core = `${value.major}.${value.minor}.${value.patch}`
381
+ return value.prerelease.length === 0 ? core : `${core}-${value.prerelease.join('.')}`
344
382
  }
345
383
 
346
384
  // ---------------------------------------------------------------------------
347
385
  // CLI entry point
348
386
  // ---------------------------------------------------------------------------
349
- function main() {
387
+ async function main() {
388
+ const { configure: configureUi, tag } = await import('./cli-ui.mjs')
350
389
  const args = process.argv.slice(2)
351
390
  const targetIdx = args.indexOf('--target')
352
391
  const target = targetIdx !== -1 ? args[targetIdx + 1] : process.cwd()
@@ -394,12 +433,21 @@ function main() {
394
433
 
395
434
  console.log(` Current version: ${currentVersion}`)
396
435
 
397
- if (!force && currentVersion === PANTHON_VERSION) {
436
+ const state = readState(target)
437
+ if (
438
+ !force &&
439
+ currentVersion === PANTHON_VERSION &&
440
+ state?.migration_schema_version === MIGRATION_SCHEMA_VERSION
441
+ ) {
398
442
  console.log(' [OK] Already at latest version — no migrations needed')
399
443
  return
400
444
  }
401
445
 
402
- const migration = runMigrations(target, currentVersion, { dryRun })
446
+ const migration = runMigrations(target, { dryRun })
447
+
448
+ if (migration.status === 'unsupported' || migration.status === 'invalid') {
449
+ throw new Error(migration.message)
450
+ }
403
451
 
404
452
  if (migration.applied > 0) {
405
453
  console.log(` [OK] Applied ${migration.applied} migration(s):`)
@@ -412,5 +460,8 @@ function main() {
412
460
  }
413
461
 
414
462
  if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {
415
- main()
463
+ main().catch((error) => {
464
+ console.error(` [ERROR] ${error instanceof Error ? error.message : String(error)}`)
465
+ process.exitCode = 1
466
+ })
416
467
  }