pantheon-opencode 1.6.1 → 1.6.2-beta.2

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 (115) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +29 -0
  4. package/README.md +100 -19
  5. package/README.pt-BR.md +27 -11
  6. package/bin/pantheon-init.mjs +106 -19
  7. package/package.json +3 -2
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +1 -1
  11. package/scripts/doctor.mjs +213 -45
  12. package/scripts/install/agents-md.mjs +2 -1
  13. package/scripts/install/config-migration.mjs +344 -393
  14. package/scripts/install/config-paths.mjs +15 -0
  15. package/scripts/install/mcp-permissions.mjs +164 -0
  16. package/scripts/install/opencode-version.mjs +31 -13
  17. package/scripts/install/opencode-wildcard.mjs +106 -0
  18. package/scripts/install/opencode.mjs +240 -69
  19. package/scripts/install/plan-artifact.mjs +12 -1
  20. package/scripts/install/plugin.mjs +17 -1
  21. package/scripts/install/v2-capabilities.mjs +5 -6
  22. package/scripts/package-evidence.mjs +1 -0
  23. package/scripts/sandbox-env.sh +174 -0
  24. package/scripts/setup-v2-config.mjs +1703 -0
  25. package/scripts/setup.mjs +415 -0
  26. package/scripts/sync-tui.mjs +9 -1
  27. package/scripts/test-opencode-v2-sandbox.sh +438 -151
  28. package/scripts/update-skills-lock.mjs +30 -0
  29. package/skills-lock.json +10 -10
  30. package/src/agents/aphrodite.md +5 -2
  31. package/src/agents/apollo.md +5 -0
  32. package/src/agents/athena.md +6 -1
  33. package/src/agents/demeter.md +5 -1
  34. package/src/agents/gaia.md +4 -0
  35. package/src/agents/hephaestus.md +6 -1
  36. package/src/agents/hermes.md +6 -3
  37. package/src/agents/iris.md +5 -1
  38. package/src/agents/mnemosyne.md +20 -50
  39. package/src/agents/nyx.md +5 -1
  40. package/src/agents/prometheus.md +4 -0
  41. package/src/agents/talos.md +4 -0
  42. package/src/agents/themis.md +4 -0
  43. package/src/agents/zeus.md +9 -3
  44. package/src/instructions/agent-return-format.instructions.md +1 -1
  45. package/src/instructions/memory-protocol.instructions.md +3 -3
  46. package/src/instructions/test-economy.instructions.md +6 -6
  47. package/src/mcp/pantheon_vision.py +37 -36
  48. package/src/pantheon/cost-command.ts +30 -133
  49. package/src/pantheon/model-pricing.ts +1 -536
  50. package/src/pantheon/v2-vision.ts +34 -29
  51. package/src/pantheon/vision.ts +43 -10
  52. package/src/plugin-v2.ts +30 -53
  53. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  54. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
  55. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
  56. package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
  57. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
  58. package/src/plugins/tui/dist/quota-adapters.js +1142 -0
  59. package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
  60. package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
  61. package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
  62. package/src/plugins/tui/dist/quota-cli.js +184 -0
  63. package/src/plugins/tui/dist/quota-cli.js.map +1 -0
  64. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +684 -0
  65. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
  66. package/src/plugins/tui/dist/server-v2.d.ts +14 -0
  67. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  68. package/src/plugins/tui/dist/server-v2.js +796 -0
  69. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  70. package/src/plugins/tui/dist/tui-v2.d.ts +375 -53
  71. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  72. package/src/plugins/tui/dist/tui-v2.js +5876 -530
  73. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  74. package/src/plugins/tui/dist/tui.js +1 -1
  75. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
  76. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
  77. package/src/plugins/tui/dist/usage-history-worker.js +25 -0
  78. package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
  79. package/src/plugins/tui/index-v2.ts +3 -6
  80. package/src/plugins/tui/package-lock.json +17 -2
  81. package/src/plugins/tui/package.json +6 -3
  82. package/src/plugins/tui/src/context-gauge.ts +59 -0
  83. package/src/plugins/tui/src/cost-data.ts +607 -0
  84. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
  85. package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
  86. package/src/plugins/tui/src/index-v2.tsx +231 -240
  87. package/src/plugins/tui/src/model-pricing.ts +536 -0
  88. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  89. package/src/plugins/tui/src/quota-adapters.ts +1598 -0
  90. package/src/plugins/tui/src/quota-cli.ts +237 -0
  91. package/src/plugins/tui/src/quota-rpc.ts +373 -0
  92. package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
  93. package/src/plugins/tui/src/quota-v2.tsx +1238 -0
  94. package/src/plugins/tui/src/server-v2.ts +985 -0
  95. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  96. package/src/plugins/tui/src/usage-history-contract.ts +217 -0
  97. package/src/plugins/tui/src/usage-history-validation.ts +104 -0
  98. package/src/plugins/tui/src/usage-history-view.tsx +236 -0
  99. package/src/plugins/tui/src/usage-history-worker.ts +25 -0
  100. package/src/plugins/tui/src/usage-view-model.ts +272 -0
  101. package/src/plugins/tui/tsconfig.typecheck.json +6 -1
  102. package/src/plugins/tui/tsdown.config.ts +44 -5
  103. package/src/routing.yml +72 -13
  104. package/src/skills/README.md +4 -0
  105. package/src/skills/agent-coordination/SKILL.md +0 -3
  106. package/src/skills/artifact-management/SKILL.md +0 -3
  107. package/src/skills/auto-continue/SKILL.md +0 -3
  108. package/src/skills/code-review-checklist/SKILL.md +0 -3
  109. package/src/skills/context-compression/SKILL.md +0 -3
  110. package/src/skills/memory-bank/SKILL.md +6 -28
  111. package/src/skills/session-goal/SKILL.md +0 -3
  112. package/src/skills/simplify/SKILL.md +5 -4
  113. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  114. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  115. package/src/pantheon/memory-context.ts +0 -1017
@@ -3,9 +3,8 @@
3
3
  *
4
4
  * Converts opencode.json between:
5
5
  * - V1 (object-based): `permission`, `agent`, `provider`, `mcp` with flat keys
6
- * - V2 (array-based): `permissions`, `agents`, `providers`; MCP remains the
7
- * named top-level server map because OpenCode 1.18.x validates that shape for
8
- * both the V1 and V2 installer paths.
6
+ * - V2 (array-based): `permissions`, `agents`, `providers`, and
7
+ * `mcp.servers.<name>` server configuration.
9
8
  *
10
9
  * Rules:
11
10
  * 1. Deep clone before mutating — never modifies input
@@ -16,6 +15,14 @@
16
15
  * @module config-migration
17
16
  */
18
17
 
18
+ import {
19
+ assertMcpPermissionNamesUnambiguous,
20
+ assertMcpPermissionScopesDoNotAliasConfiguredServers,
21
+ assertMcpServerPermissionScopesUnambiguous,
22
+ mcpServerPermissionActions,
23
+ } from './mcp-permissions.mjs'
24
+ import { opencodeWildcardPatternsOverlap } from './opencode-wildcard.mjs'
25
+
19
26
  // ---------------------------------------------------------------------------
20
27
  // Helpers
21
28
  // ---------------------------------------------------------------------------
@@ -35,10 +42,8 @@ function deepClone(obj) {
35
42
  *
36
43
  * `write` is an alias of `edit`. Every V2 host measured for P0-5 (2.0.22,
37
44
  * 2.0.30, 2.1.0, 2.1.2) evaluates a `write` tool call under the action name
38
- * `edit`; a rule emitted as `write` is therefore never the rule that decides the
39
- * call, and `permission.write: deny` would not block a write. Both keys collapse
40
- * onto `edit`, and a collision is resolved by effect restrictiveness
41
- * (deny > ask > allow), never by iteration order — see `pushPermission`.
45
+ * `edit`; rules are mapped to that action while their input order and distinct
46
+ * entries are preserved because V2 permission evaluation is order-sensitive.
42
47
  *
43
48
  * Only mappings confirmed against a host belong here: `bash → shell`, `task →
44
49
  * subagent`, `read → read` and `write → edit` were observed on 2.0.22/2.0.30/
@@ -58,71 +63,14 @@ const V1_PERMISSION_TO_ACTION = {
58
63
  // passthrough unknowns
59
64
  }
60
65
 
61
- /**
62
- * Effect restrictiveness used when two V1 keys collapse onto one V2 action.
63
- * `deny` is the most restrictive, so a deny from either alias wins.
64
- */
66
+ /** Effect restrictiveness is used only when V2 rules must collapse into V1 keys. */
65
67
  const EFFECT_RESTRICTIVENESS = { allow: 1, ask: 2, deny: 3 }
66
68
 
67
- /**
68
- * True only for effects this module understands. `Object.hasOwn` is required:
69
- * an inherited key (`constructor`, `toString`, `__proto__`) is not an effect,
70
- * and treating it as one would rank it above `deny`.
71
- */
72
69
  function isKnownEffect(effect) {
73
70
  return typeof effect === 'string' && Object.hasOwn(EFFECT_RESTRICTIVENESS, effect)
74
71
  }
75
72
 
76
- /**
77
- * Emission order (not restrictiveness rank) for rules that share a specificity.
78
- * Unknown effects sit after the known non-deny effects and before `deny`, so at
79
- * equal specificity `deny` is the most restrictive rule and comes last.
80
- */
81
- const UNKNOWN_EFFECT_EMISSION_ORDER = 2.5
82
-
83
- /** Resource containing any glob metacharacter. */
84
- const GLOB_PATTERN = /[*?[\]{}]/
85
-
86
- function effectEmissionOrder(effect) {
87
- return isKnownEffect(effect) ? EFFECT_RESTRICTIVENESS[effect] : UNKNOWN_EFFECT_EMISSION_ORDER
88
- }
89
-
90
- /** 0 = `*`, 1 = glob, 2 = literal resource. */
91
- function resourceSpecificity(resource) {
92
- if (resource === '*') return 0
93
- return GLOB_PATTERN.test(resource) ? 1 : 2
94
- }
95
-
96
- /**
97
- * Canonical order for emitted permission rules.
98
- *
99
- * Specificity decides between DIFFERENT resources: the host resolves overlaps
100
- * with `last-match-wins` (measured), so rules are emitted least specific first
101
- * (`*` → glob → literal) and the most specific matching rule wins. Only when
102
- * two rules share a specificity does restrictiveness break the tie
103
- * (`allow` → `ask` → unknown → `deny`), keeping the more restrictive rule last.
104
- *
105
- * Same action+resource is not decided here: `resolveEffects` has already
106
- * merged those with `deny > ask > allow` and the unknown-effect guard.
107
- *
108
- * Code-unit tie-breaks make the output independent of the V1 object's key
109
- * iteration order.
110
- */
111
- function comparePermissions(a, b) {
112
- const actionA = String(a.action)
113
- const actionB = String(b.action)
114
- if (actionA !== actionB) return actionA < actionB ? -1 : 1
115
- const resourceA = String(a.resource)
116
- const resourceB = String(b.resource)
117
- const bySpecificity = resourceSpecificity(resourceA) - resourceSpecificity(resourceB)
118
- if (bySpecificity !== 0) return bySpecificity
119
- const byEffect = effectEmissionOrder(a.effect) - effectEmissionOrder(b.effect)
120
- if (byEffect !== 0) return byEffect
121
- if (resourceA === resourceB) return 0
122
- return resourceA < resourceB ? -1 : 1
123
- }
124
-
125
- /** A rule the converter can order: an object with string action+resource. */
73
+ /** A structurally valid permission rule, used for redacted malformed-entry counts. */
126
74
  function isValidPermissionEntry(entry) {
127
75
  return (
128
76
  isPlainObject(entry) && typeof entry.action === 'string' && typeof entry.resource === 'string'
@@ -130,139 +78,16 @@ function isValidPermissionEntry(entry) {
130
78
  }
131
79
 
132
80
  /**
133
- * Report entries that are not rule objects. They cannot be compared, so they
134
- * are preserved verbatim (never dropped) and excluded from ordering.
81
+ * Report malformed entries without echoing user-supplied config values.
135
82
  */
136
83
  function warnInvalidPermissionEntries(entries) {
137
84
  const invalid = entries.filter((entry) => !isValidPermissionEntry(entry))
138
85
  if (invalid.length === 0) return
139
86
  console.warn(
140
- `[config-migration] ${invalid.length} malformed permission ${invalid.length === 1 ? 'entry was' : 'entries were'} preserved without sorting: ${JSON.stringify(invalid)}`,
87
+ `[config-migration] ${invalid.length} malformed permission ${invalid.length === 1 ? 'entry was' : 'entries were'} preserved in order.`,
141
88
  )
142
89
  }
143
90
 
144
- function sortPermissions(entries) {
145
- const valid = entries.filter(isValidPermissionEntry)
146
- const invalid = entries.filter((entry) => !isValidPermissionEntry(entry))
147
- warnInvalidPermissionEntries(entries)
148
- // Malformed entries keep their relative order at the end; they must not crash
149
- // the comparator, and dropping them would hide a broken config.
150
- return [...valid.sort(comparePermissions), ...invalid]
151
- }
152
-
153
- /**
154
- * Conservative glob matcher for a literal resource. `**` crosses `/`, `*` and
155
- * `?` do not; character classes are treated literally, which can only miss a
156
- * warning — never invent one.
157
- */
158
- function globMatchesLiteral(pattern, literal) {
159
- if (pattern === '*') return true
160
- let source = '^'
161
- for (let i = 0; i < pattern.length; i++) {
162
- const char = pattern[i]
163
- if (char === '*') {
164
- if (pattern[i + 1] === '*') {
165
- source += '.*'
166
- i++
167
- } else {
168
- source += '[^/]*'
169
- }
170
- } else if (char === '?') {
171
- source += '[^/]'
172
- } else {
173
- source += char.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
174
- }
175
- }
176
- return new RegExp(`${source}$`).test(literal)
177
- }
178
-
179
- /** Last matching rule for one action+resource, the way the host decides. */
180
- function effectiveEffectAt(entries, action, resource) {
181
- let effect
182
- for (const entry of entries) {
183
- if (!isValidPermissionEntry(entry)) continue
184
- if (entry.action !== action) continue
185
- if (globMatchesLiteral(entry.resource, resource)) effect = entry.effect
186
- }
187
- return effect
188
- }
189
-
190
- /**
191
- * Warn when canonical ordering weakens an existing V2 decision.
192
- *
193
- * The V2 array is user state; sorting it is only done to make a V1+V2 merge
194
- * deterministic. If reordering alone turns a `deny` into anything weaker for a
195
- * resource named in that array, the user must hear about it — the config they
196
- * installed gated that path before the merge. The warning is informational
197
- * (the canonical order is still required for determinism), and only fires for
198
- * deny → non-deny; tightening (allow → deny) is not noise.
199
- */
200
- function warnOrderingChangesEffectiveEffect(before, after) {
201
- // Probe each distinct resource string. A glob matches its own literal text
202
- // (`src/**` matches the probe `src/**`), so this covers every rule's scope
203
- // without inventing concrete paths.
204
- const probes = new Set()
205
- for (const entry of before) {
206
- if (isValidPermissionEntry(entry)) probes.add(`${entry.action}\u0000${entry.resource}`)
207
- }
208
- for (const key of probes) {
209
- const [action, resource] = key.split('\u0000')
210
- const beforeEffect = effectiveEffectAt(before, action, resource)
211
- const afterEffect = effectiveEffectAt(after, action, resource)
212
- if (beforeEffect === 'deny' && afterEffect !== 'deny') {
213
- console.warn(
214
- `[config-migration] reordering the existing V2 permissions changes ${action} "${resource}" from "deny" to "${afterEffect}" under last-match-wins; the canonical order is kept, but the deny no longer applies to that resource`,
215
- )
216
- }
217
- }
218
- }
219
-
220
- /**
221
- * Warn when a deny loses force under the canonical specificity order.
222
- *
223
- * A scoped allow inside a broader deny is also how the V1 format expresses an
224
- * intentional exception — `src/agents/mnemosyne.md` is the shipping example:
225
- * `"*": deny` plus `allow` in the memory bank. Warning on every such pair would
226
- * fire for the product's own templates and train users to ignore the warning,
227
- * so same-source scoping is treated as intentional and stays silent.
228
- *
229
- * The warning is reserved for overrides that cross a source boundary: a deny
230
- * already persisted in the V2 `permissions` array that an incoming V1 block
231
- * neutralises in a narrower scope, or the reverse. There the two rules were not
232
- * written together and the user may not realise the deny no longer applies.
233
- *
234
- * Two arbitrary globs share a specificity class, so the effect tie-break puts
235
- * `deny` last and they cannot relax a deny; no glob-subsumption guess is needed.
236
- */
237
- function warnSuppressedPermissions(entries, sourceByEntry) {
238
- for (let i = 0; i < entries.length; i++) {
239
- const earlier = entries[i]
240
- if (!isValidPermissionEntry(earlier) || earlier.effect !== 'deny') continue
241
- const earlierResource = String(earlier.resource)
242
- const earlierSpecificity = resourceSpecificity(earlierResource)
243
- for (let j = i + 1; j < entries.length; j++) {
244
- const later = entries[j]
245
- if (!isValidPermissionEntry(later)) continue
246
- if (later.action !== earlier.action || later.effect === 'deny') continue
247
- const laterResource = String(later.resource)
248
- if (resourceSpecificity(laterResource) <= earlierSpecificity) continue
249
-
250
- const earlierSource = sourceByEntry?.get(earlier)
251
- const laterSource = sourceByEntry?.get(later)
252
- if (sourceByEntry && earlierSource === laterSource) continue
253
-
254
- // `*` overlaps everything; a glob only overlaps a literal it matches.
255
- if (earlierResource !== '*' && !globMatchesLiteral(earlierResource, laterResource)) continue
256
-
257
- const earlierOrigin = earlierSource ? `, ${earlierSource}` : ''
258
- const laterOrigin = laterSource ? `, ${laterSource}` : ''
259
- console.warn(
260
- `[config-migration] permission rule ${earlier.action} "${earlierResource}" (${earlier.effect}${earlierOrigin}) is overridden for resources matching "${laterResource}" by the later ${later.action} "${laterResource}" (${later.effect}${laterOrigin}) under last-match-wins; the deny does not apply in that scope`,
261
- )
262
- }
263
- }
264
- }
265
-
266
91
  /**
267
92
  * Resolve two effects proposed for the same action+resource.
268
93
  *
@@ -273,7 +98,7 @@ function warnSuppressedPermissions(entries, sourceByEntry) {
273
98
  *
274
99
  * @returns {string} the effect to keep
275
100
  */
276
- function resolveEffects(current, next, label) {
101
+ function resolveEffects(current, next) {
277
102
  if (current === next) return current
278
103
 
279
104
  const currentKnown = isKnownEffect(current)
@@ -281,26 +106,22 @@ function resolveEffects(current, next, label) {
281
106
 
282
107
  if (!currentKnown && !nextKnown) {
283
108
  console.warn(
284
- `[config-migration] unrecognized effects for ${label}: "${current}" vs "${next}"; keeping the first "${current}"`,
109
+ '[config-migration] Unrecognized effects could not be ranked; keeping the first value.',
285
110
  )
286
111
  return current
287
112
  }
288
113
  if (currentKnown && !nextKnown) {
289
- console.warn(
290
- `[config-migration] unrecognized effect "${next}" for ${label} cannot replace the known effect "${current}"; keeping "${current}"`,
291
- )
114
+ console.warn('[config-migration] An unrecognized effect could not replace a known effect.')
292
115
  return current
293
116
  }
294
117
  if (!currentKnown && nextKnown) {
295
- console.warn(
296
- `[config-migration] unrecognized effect "${current}" for ${label} was replaced by the known effect "${next}"; keeping "${next}"`,
297
- )
118
+ console.warn('[config-migration] A known effect replaced an unrecognized effect.')
298
119
  return next
299
120
  }
300
121
 
301
122
  const winner = EFFECT_RESTRICTIVENESS[next] > EFFECT_RESTRICTIVENESS[current] ? next : current
302
123
  console.warn(
303
- `[config-migration] conflicting effects for ${label}: "${current}" vs "${next}"; keeping the more restrictive "${winner}"`,
124
+ '[config-migration] Conflicting effects were found; keeping the more restrictive value.',
304
125
  )
305
126
  return winner
306
127
  }
@@ -320,30 +141,9 @@ function setOwn(target, key, value) {
320
141
  }
321
142
 
322
143
  /**
323
- * Emit one permission entry, merging with an existing entry for the same
324
- * action+resource instead of appending a contradiction.
325
- *
326
- * `index` maps `action\0resource` → position in `result` and is owned by the
327
- * caller for the duration of one conversion.
328
- */
329
- function pushPermission(result, index, action, resource, effect) {
330
- const key = `${action}\u0000${resource}`
331
- const existing = index.get(key)
332
- if (existing === undefined) {
333
- index.set(key, result.length)
334
- result.push({ action, resource, effect })
335
- return
336
- }
337
- const current = result[existing]
338
- if (current.effect === effect) return
339
- current.effect = resolveEffects(current.effect, effect, `${action} "${resource}"`)
340
- }
341
-
342
- /**
343
- * Valid MCP server name. Mirrors `deriveNativeMcpPermissions`
344
- * (install/opencode.mjs) so the `<server>_*` action emitted here is a name the
345
- * host can actually produce; `*`, spaces or any other character would create an
346
- * action no host evaluates — a gate that only looks enforced.
144
+ * Valid MCP server name. Mirrors the installer validation. The original spelling
145
+ * preserves V1 compatibility; the shared permission helper also emits the V2
146
+ * punctuation-normalized alias. Names outside this set cannot be mapped safely.
347
147
  */
348
148
  const MCP_SERVER_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
349
149
 
@@ -355,8 +155,8 @@ const MCP_SERVER_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
355
155
  * `permission.mcp.<server>`, the action `mcp` and the `resource` field are all
356
156
  * inert — passing them through emitted a config that enforced nothing.
357
157
  *
358
- * deny → { action: "<server>_*", resource: "*", effect: "deny" }
359
- * allow → { action: "<server>_*", resource: "*", effect: "allow" }
158
+ * deny/allow → one rule for each V1/original and V2/normalized server alias,
159
+ * with action "<server-alias>_*" and resource "*".
360
160
  * ask → no rule + warning. `ask` on an action rule HIDES the tool instead of
361
161
  * prompting, so translating it would silently remove the tool; that is
362
162
  * not what the user asked for, and it must not be downgraded to deny
@@ -368,34 +168,46 @@ const MCP_SERVER_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
368
168
  * The glob gates every tool of the server and needs no `tools/list` discovery,
369
169
  * which is why it is preferred over per-tool `<server>_<tool>` rules.
370
170
  */
371
- function convertMcpPermissions(value, result, index, { suppressAskWarning = false } = {}) {
171
+ function convertMcpPermissions(value, result, provenance, configuredMcpServers) {
372
172
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
373
- console.warn(
374
- `[config-migration] permission.mcp must be an object of server → effect; got ${JSON.stringify(value)}. No MCP rule was emitted.`,
375
- )
173
+ console.warn('[config-migration] permission.mcp is malformed; no MCP rules were emitted.')
376
174
  return
377
175
  }
176
+ const validServers = Object.keys(value).filter((server) => MCP_SERVER_NAME_PATTERN.test(server))
177
+ assertMcpPermissionNamesUnambiguous(validServers)
178
+ assertMcpPermissionScopesDoNotAliasConfiguredServers(validServers, configuredMcpServers)
179
+ assertMcpServerPermissionScopesUnambiguous(
180
+ Object.entries(value)
181
+ .filter(
182
+ ([server, effect]) =>
183
+ MCP_SERVER_NAME_PATTERN.test(server) && (effect === 'allow' || effect === 'deny'),
184
+ )
185
+ .map(([server, effect]) => ({ server, effect })),
186
+ )
378
187
  for (const [server, effect] of Object.entries(value)) {
379
188
  if (!MCP_SERVER_NAME_PATTERN.test(server)) {
380
189
  console.warn(
381
- `[config-migration] permission.mcp."${server}" is an invalid MCP server name (expected ${MCP_SERVER_NAME_PATTERN}): no rule was emitted.`,
190
+ '[config-migration] An MCP permission has an invalid server name; no rule was emitted.',
382
191
  )
383
192
  continue
384
193
  }
385
194
  if (effect === 'deny' || effect === 'allow') {
386
- pushPermission(result, index, `${server}_*`, '*', effect)
195
+ for (const action of mcpServerPermissionActions(server)) {
196
+ const rule = { action, resource: '*', effect }
197
+ result.push(rule)
198
+ provenance.push({ rule, sourceAction: 'mcp', sourceKind: 'mcp', sourceName: server })
199
+ }
387
200
  continue
388
201
  }
389
202
  if (effect === 'ask') {
390
- if (!suppressAskWarning) {
391
- console.warn(
392
- `[config-migration] permission.mcp."${server}" is "ask", which is not expressible for MCP on OpenCode 2.x: no rule is emitted and the server's tools remain available. Use "deny" (action "${server}_*") to gate them, or disable the server in the host MCP config.`,
393
- )
394
- }
203
+ console.warn(
204
+ '[config-migration] An MCP ask policy cannot be enforced in OpenCode V2; no rule was emitted. ' +
205
+ 'Use `npm run setup` to choose an explicit outcome.',
206
+ )
395
207
  continue
396
208
  }
397
209
  console.warn(
398
- `[config-migration] permission.mcp."${server}" has unsupported effect ${JSON.stringify(effect)}; no rule was emitted.`,
210
+ '[config-migration] An MCP permission has an unsupported effect; no rule was emitted.',
399
211
  )
400
212
  }
401
213
  }
@@ -403,8 +215,8 @@ function convertMcpPermissions(value, result, index, { suppressAskWarning = fals
403
215
  /**
404
216
  * Convert V1 permission object to V2 permissions array.
405
217
  *
406
- * Rules are emitted in the canonical order from `comparePermissions`, not in
407
- * the V1 object's key order, because the host is last-match-wins.
218
+ * Rules are emitted in source insertion order. V2 evaluates permission rules in
219
+ * array order, so sorting or collapsing distinct rules can change the policy.
408
220
  *
409
221
  * V1 shape:
410
222
  * { bash: { "git *": "allow" }, edit: "allow", skill: { "*": "allow" }, websearch: "deny" }
@@ -412,30 +224,97 @@ function convertMcpPermissions(value, result, index, { suppressAskWarning = fals
412
224
  * V2 shape:
413
225
  * [ { action: "shell", resource: "git *", effect: "allow" }, ... ]
414
226
  */
415
- function convertPermissionsV1toV2(permObj, options = {}) {
227
+ function convertPermissionsV1toV2(permObj, configuredMcpServers = []) {
416
228
  const result = []
417
- const index = new Map()
229
+ const provenance = []
418
230
  for (const [key, value] of Object.entries(permObj)) {
419
231
  // `permission.mcp` is a server map, not an action name: it needs its own
420
232
  // translation (see convertMcpPermissions).
421
233
  if (key === 'mcp') {
422
- convertMcpPermissions(value, result, index, options)
234
+ convertMcpPermissions(value, result, provenance, configuredMcpServers)
423
235
  continue
424
236
  }
425
237
  const action = Object.hasOwn(V1_PERMISSION_TO_ACTION, key) ? V1_PERMISSION_TO_ACTION[key] : key
426
238
  if (typeof value === 'string') {
427
239
  // Simple: { edit: "allow" } → [{ action: "edit", resource: "*", effect: "allow" }]
428
- pushPermission(result, index, action, '*', value)
240
+ const rule = { action, resource: '*', effect: value }
241
+ result.push(rule)
242
+ provenance.push({ rule, sourceAction: key, sourceKind: 'action', sourceName: key })
429
243
  } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
430
244
  // Nested: { bash: { "git *": "allow" } } → [{ action: "shell", resource: "git *", effect: "allow" }]
431
245
  for (const [resource, effect] of Object.entries(value)) {
432
- pushPermission(result, index, action, resource, effect)
246
+ const rule = { action, resource, effect }
247
+ result.push(rule)
248
+ provenance.push({ rule, sourceAction: key, sourceKind: 'action', sourceName: key })
433
249
  }
434
250
  } else {
435
- console.warn(`[config-migration] Unexpected permission value for "${key}":`, value)
251
+ console.warn('[config-migration] An unexpected permission value was preserved by omission.')
252
+ }
253
+ }
254
+ assertV1ActionNormalizationDoesNotCollapseSources(provenance)
255
+ return result
256
+ }
257
+
258
+ /**
259
+ * Preserve same-source V1 rule order, but reject only overlaps introduced by
260
+ * converting distinct V1 action/server identities to intersecting V2 actions.
261
+ * V1 and V2 both use last-match-wins, so a same-source deny followed by a more
262
+ * specific allow is intentional and must not be reordered or rejected.
263
+ */
264
+ function assertV1ActionNormalizationDoesNotCollapseSources(provenance) {
265
+ const actionPolicies = new Map()
266
+ for (const source of provenance) {
267
+ if (source.sourceKind !== 'action') continue
268
+ const policy = actionPolicies.get(source.sourceAction) ?? []
269
+ policy.push({ resource: source.rule.resource, effect: source.rule.effect })
270
+ actionPolicies.set(source.sourceAction, policy)
271
+ }
272
+ const identicalActionPolicies = (left, right) => {
273
+ const leftPolicy = actionPolicies.get(left.sourceAction)
274
+ const rightPolicy = actionPolicies.get(right.sourceAction)
275
+ return (
276
+ leftPolicy !== undefined &&
277
+ rightPolicy !== undefined &&
278
+ JSON.stringify(leftPolicy) === JSON.stringify(rightPolicy)
279
+ )
280
+ }
281
+
282
+ for (let leftIndex = 0; leftIndex < provenance.length; leftIndex += 1) {
283
+ const left = provenance[leftIndex]
284
+ for (let rightIndex = leftIndex + 1; rightIndex < provenance.length; rightIndex += 1) {
285
+ const right = provenance[rightIndex]
286
+ const distinctMcpServers =
287
+ left.sourceKind === 'mcp' &&
288
+ right.sourceKind === 'mcp' &&
289
+ left.sourceName !== right.sourceName
290
+ const distinctActions =
291
+ left.sourceKind === 'action' &&
292
+ right.sourceKind === 'action' &&
293
+ left.sourceAction !== right.sourceAction
294
+ const actionAliasCollision =
295
+ distinctActions &&
296
+ !identicalActionPolicies(left, right) &&
297
+ !opencodeWildcardPatternsOverlap(left.sourceAction, right.sourceAction) &&
298
+ left.rule.effect !== right.rule.effect &&
299
+ opencodeWildcardPatternsOverlap(left.rule.action, right.rule.action)
300
+ const mcpAliasCollision =
301
+ distinctMcpServers && opencodeWildcardPatternsOverlap(left.rule.action, right.rule.action)
302
+ const crossKindAliasCollision =
303
+ left.sourceKind !== right.sourceKind &&
304
+ !opencodeWildcardPatternsOverlap(left.sourceAction, right.sourceAction) &&
305
+ left.rule.effect !== right.rule.effect &&
306
+ opencodeWildcardPatternsOverlap(left.rule.action, right.rule.action)
307
+
308
+ if (
309
+ (actionAliasCollision || mcpAliasCollision || crossKindAliasCollision) &&
310
+ opencodeWildcardPatternsOverlap(left.rule.resource, right.rule.resource)
311
+ ) {
312
+ throw new TypeError(
313
+ 'Distinct V1 permission sources overlap after OpenCode V2 action normalization; migration stopped.',
314
+ )
315
+ }
436
316
  }
437
317
  }
438
- return sortPermissions(result)
439
318
  }
440
319
 
441
320
  /**
@@ -469,11 +348,7 @@ function convertPermissionsV2toV1(permArray) {
469
348
  rules = new Map()
470
349
  byKey.set(v1Key, rules)
471
350
  }
472
- const label = `permission "${v1Key}" resource "${resource}"`
473
- rules.set(
474
- resource,
475
- rules.has(resource) ? resolveEffects(rules.get(resource), effect, label) : effect,
476
- )
351
+ rules.set(resource, rules.has(resource) ? resolveEffects(rules.get(resource), effect) : effect)
477
352
  }
478
353
 
479
354
  const result = {}
@@ -619,42 +494,120 @@ function convertProviderV2toV1(_name, config) {
619
494
  return result
620
495
  }
621
496
 
497
+ /**
498
+ * Validate the MCP source shape before any installer seeding can normalize it.
499
+ * Returns the shape decision consumed by the converter so both paths apply
500
+ * exactly the same nested-map and legacy-toggle rules.
501
+ *
502
+ * @param {unknown} mcpConfig
503
+ * @returns {{ hasV2ServersMap: boolean, legacyServersToggle: boolean }}
504
+ */
505
+ export function validateMcpV1toV2Source(mcpConfig) {
506
+ if (Array.isArray(mcpConfig)) {
507
+ throw new Error(
508
+ 'Malformed MCP configuration: top-level mcp must be an object map, not an array.',
509
+ )
510
+ }
511
+ if (!isPlainObject(mcpConfig)) {
512
+ throw new Error('Malformed MCP configuration: top-level mcp must be an object map.')
513
+ }
514
+
515
+ const wrappedServers = mcpConfig.servers
516
+ if (Array.isArray(wrappedServers)) {
517
+ throw new Error('Malformed MCP configuration: mcp.servers must be an object map, not an array.')
518
+ }
519
+ const legacyServersToggle =
520
+ isPlainObject(wrappedServers) &&
521
+ Object.keys(wrappedServers).length === 1 &&
522
+ typeof wrappedServers.enabled === 'boolean'
523
+ const looksLikeServerConfig = (value) =>
524
+ isPlainObject(value) &&
525
+ (typeof value.type === 'string' ||
526
+ typeof value.url === 'string' ||
527
+ typeof value.cwd === 'string' ||
528
+ Array.isArray(value.command))
529
+ const nestedServerMap =
530
+ isPlainObject(wrappedServers) &&
531
+ (Object.keys(wrappedServers).length === 0 ||
532
+ Object.values(wrappedServers).every(looksLikeServerConfig))
533
+ const flatServerNamedServers = looksLikeServerConfig(wrappedServers)
534
+
535
+ if (!legacyServersToggle && nestedServerMap && flatServerNamedServers) {
536
+ throw new Error('Ambiguous mcp.servers value could be a flat server or a nested server map.')
537
+ }
538
+
539
+ const malformedNestedMap =
540
+ isPlainObject(wrappedServers) &&
541
+ !legacyServersToggle &&
542
+ !nestedServerMap &&
543
+ !flatServerNamedServers
544
+
545
+ if (malformedNestedMap) {
546
+ throw new Error('Malformed or ambiguous nested MCP server map cannot be migrated safely.')
547
+ }
548
+
549
+ const hasV2ServersMap =
550
+ isPlainObject(wrappedServers) &&
551
+ !legacyServersToggle &&
552
+ nestedServerMap &&
553
+ !flatServerNamedServers
554
+
555
+ for (const [name, value] of Object.entries(mcpConfig)) {
556
+ if (
557
+ name === 'servers' &&
558
+ (legacyServersToggle || hasV2ServersMap || looksLikeServerConfig(value))
559
+ ) {
560
+ continue
561
+ }
562
+ if (!isPlainObject(value)) {
563
+ throw new Error(
564
+ 'Malformed MCP server entry: every flat server configuration must be an object.',
565
+ )
566
+ }
567
+ }
568
+
569
+ return { hasV2ServersMap, legacyServersToggle }
570
+ }
571
+
622
572
  /**
623
573
  * Convert V1 MCP config to V2.
624
574
  *
625
575
  * The server names are arbitrary — a user calls theirs whatever they like, and
626
576
  * which MCP servers exist is entirely their configuration, never ours.
627
577
  *
628
- * V1: { myserver: { type: "remote", url: "...", enabled: true, timeout: 30000 } }
629
- * V2 installer output: { myserver: { type: "remote", url: "...", enabled: true } }
578
+ * V1: { myserver: { type: "remote", url: "...", enabled: true } }
579
+ * V2: { servers: { myserver: { type: "remote", url: "...", disabled: false } } }
630
580
  *
631
- * OpenCode 1.18.18 does not have an `mcp.servers` wrapper. It interprets
632
- * `servers` as the name of an MCP server and then rejects it with
633
- * `Missing key mcp.servers.enabled`. Keep MCP in the documented shape and
634
- * normalize old generated V2 entries back to it.
581
+ * V2's MCP schema stores named servers under `mcp.servers`; V1's flat map is
582
+ * wrapped during migration. A pre-existing V2 wrapper is retained in place,
583
+ * and distinct flat siblings are included rather than silently discarded. A
584
+ * duplicate name across the two shapes is ambiguous and fails closed.
635
585
  */
636
586
  function convertMcpV1toV2(mcpConfig) {
637
- if (!mcpConfig || typeof mcpConfig !== 'object') return mcpConfig
638
-
587
+ const { hasV2ServersMap, legacyServersToggle } = validateMcpV1toV2Source(mcpConfig)
639
588
  const servers = {}
640
- const source =
641
- mcpConfig.servers && typeof mcpConfig.servers === 'object' && !Array.isArray(mcpConfig.servers)
642
- ? { ...mcpConfig, ...mcpConfig.servers }
643
- : mcpConfig
644
-
645
- for (const [name, serverConfig] of Object.entries(source)) {
646
- if (name === 'servers') continue
647
- // Installer versions that seeded the legacy wrapper also wrote a boolean
648
- // feature toggle (`servers: { enabled: true }`). After unwrapping, that
649
- // toggle surfaces as a non-object entry and is not a server; drop it.
650
- if (serverConfig === null || typeof serverConfig !== 'object') continue
651
- const srv = { ...serverConfig }
652
-
653
- // Normalize legacy V2's disabled flag to OpenCode 1.18.x's enabled flag.
654
- if ('disabled' in srv) {
655
- srv.enabled = !srv.disabled
656
- delete srv.disabled
589
+ // Expand a nested map exactly where its `servers` property occurred. This
590
+ // retains the source order relative to flat siblings while still detecting
591
+ // duplicate names across both shapes below.
592
+ const source = Object.entries(mcpConfig).flatMap(([name, config]) =>
593
+ hasV2ServersMap && name === 'servers' ? Object.entries(config) : [[name, config]],
594
+ )
595
+
596
+ for (const [name, serverConfig] of source) {
597
+ if (!hasV2ServersMap && name === 'servers' && legacyServersToggle) {
598
+ // Older installers used mcp.servers.enabled as a feature toggle beside
599
+ // flat server entries. It is not a named server configuration.
600
+ continue
657
601
  }
602
+ if (!isPlainObject(serverConfig)) {
603
+ throw new Error(
604
+ 'Malformed MCP server entry: every flat server configuration must be an object.',
605
+ )
606
+ }
607
+ if (Object.hasOwn(servers, name)) {
608
+ throw new Error('Conflicting flat and nested MCP server entries cannot be merged safely.')
609
+ }
610
+ const srv = normalizeMcpServerFlags(serverConfig, 'v2')
658
611
 
659
612
  // Normalize legacy V2's split timeout to the V1/V2-compatible number.
660
613
  if (srv.timeout !== undefined && srv.timeout !== null) {
@@ -666,10 +619,45 @@ function convertMcpV1toV2(mcpConfig) {
666
619
  // A shorthand inherited-server override is valid only when named directly.
667
620
  // Runtime MCP entries always have a complete config, so leave other values
668
621
  // untouched and avoid dropping user-owned servers.
669
- servers[name] = srv
622
+ setOwn(servers, name, srv)
670
623
  }
671
624
 
672
- return servers
625
+ return { servers }
626
+ }
627
+
628
+ /**
629
+ * Normalize the V1 `enabled` and V2 `disabled` spellings without guessing
630
+ * when both are present. OpenCode V2 connects configured servers by default;
631
+ * `disabled: true` is the native opt-out.
632
+ *
633
+ * @param {object} serverConfig
634
+ * @param {'v1' | 'v2'} targetVersion
635
+ * @returns {object}
636
+ */
637
+ function normalizeMcpServerFlags(serverConfig, targetVersion) {
638
+ const srv = { ...serverConfig }
639
+ const hasEnabled = Object.hasOwn(srv, 'enabled')
640
+ const hasDisabled = Object.hasOwn(srv, 'disabled')
641
+ if (hasEnabled && typeof srv.enabled !== 'boolean') {
642
+ throw new TypeError('MCP server enabled must be a boolean.')
643
+ }
644
+ if (hasDisabled && typeof srv.disabled !== 'boolean') {
645
+ throw new TypeError('MCP server disabled must be a boolean.')
646
+ }
647
+ if (hasEnabled && hasDisabled && srv.enabled === srv.disabled) {
648
+ throw new TypeError('Conflicting MCP enabled and disabled flags.')
649
+ }
650
+
651
+ if (targetVersion === 'v2') {
652
+ if (hasEnabled) {
653
+ srv.disabled = !srv.enabled
654
+ delete srv.enabled
655
+ }
656
+ } else if (hasDisabled) {
657
+ srv.enabled = !srv.disabled
658
+ delete srv.disabled
659
+ }
660
+ return srv
673
661
  }
674
662
 
675
663
  /**
@@ -677,8 +665,13 @@ function convertMcpV1toV2(mcpConfig) {
677
665
  */
678
666
  function convertMcpV2toV1(mcpConfig) {
679
667
  if (!mcpConfig || typeof mcpConfig !== 'object') return mcpConfig
680
-
681
- return convertMcpV1toV2(mcpConfig)
668
+ const v2Servers = convertMcpV1toV2(mcpConfig)?.servers
669
+ if (!isPlainObject(v2Servers)) return mcpConfig
670
+ const servers = {}
671
+ for (const [name, config] of Object.entries(v2Servers)) {
672
+ setOwn(servers, name, normalizeMcpServerFlags(config, 'v1'))
673
+ }
674
+ return servers
682
675
  }
683
676
 
684
677
  // ---------------------------------------------------------------------------
@@ -705,6 +698,15 @@ export const MCP_ENTRYPOINT_RENAMES = Object.freeze({
705
698
  'pantheon_vision_server.py': 'pantheon_vision.py',
706
699
  })
707
700
 
701
+ /** Exact server-to-entrypoint identities written by the installer. */
702
+ export const PANTHEON_MCP_ENTRYPOINTS = Object.freeze({
703
+ 'pantheon-resources': 'mcp_resources.py',
704
+ 'pantheon-code-mode': 'code_mode.py',
705
+ 'pantheon-memory': 'memory_mcp.py',
706
+ 'pantheon-persistence': 'mcp_persistence.py',
707
+ 'pantheon-vision': 'pantheon_vision.py',
708
+ })
709
+
708
710
  /**
709
711
  * Rewrite a single path/argument string when its basename is a renamed MCP
710
712
  * entrypoint. The directory prefix is preserved verbatim, so both relative
@@ -724,13 +726,10 @@ function renameMcpEntrypointPath(value) {
724
726
  }
725
727
 
726
728
  /**
727
- * Heal stale MCP entrypoint paths in a flat named-server map, in place.
728
- *
729
- * Scans every server — not only the `pantheon-*` keys — because a user who
730
- * hand-edited their config may have renamed the key while keeping the
731
- * Pantheon path. Both `command` (installer writes `[python, script]`) and
732
- * `args` (the standalone installer writes `[script]`) are covered, since
733
- * which array carries the script differs between installers.
729
+ * Heal only exact Pantheon MCP server/entrypoint pairs in a flat map, in place.
730
+ * A matching script basename alone is not ownership evidence. Both `command`
731
+ * and `args` forms are supported, while other servers and custom entrypoints
732
+ * remain untouched.
734
733
  *
735
734
  * @param {object} mcp - the `mcp` map from a config (mutated in place)
736
735
  * @returns {number} count of rewritten strings (0 = already current)
@@ -739,13 +738,23 @@ export function migrateMcpEntrypointPaths(mcp) {
739
738
  if (!mcp || typeof mcp !== 'object' || Array.isArray(mcp)) return 0
740
739
 
741
740
  let changed = 0
742
- for (const server of Object.values(mcp)) {
741
+ for (const [name, server] of Object.entries(mcp)) {
743
742
  if (!server || typeof server !== 'object') continue
743
+ const currentEntrypoint = PANTHEON_MCP_ENTRYPOINTS[name]
744
+ if (!currentEntrypoint) continue
745
+ const staleEntrypoint = Object.keys(MCP_ENTRYPOINT_RENAMES).find(
746
+ (oldName) => MCP_ENTRYPOINT_RENAMES[oldName] === currentEntrypoint,
747
+ )
748
+ if (!staleEntrypoint) continue
744
749
  for (const field of ['command', 'args']) {
745
750
  const list = server[field]
746
751
  if (!Array.isArray(list)) continue
747
752
  for (let i = 0; i < list.length; i++) {
748
- const next = renameMcpEntrypointPath(list[i])
753
+ const value = list[i]
754
+ if (typeof value !== 'string') continue
755
+ const slash = Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\'))
756
+ if (value.slice(slash + 1) !== staleEntrypoint) continue
757
+ const next = renameMcpEntrypointPath(value)
749
758
  if (next !== list[i]) {
750
759
  list[i] = next
751
760
  changed++
@@ -1000,113 +1009,42 @@ export function mergeContextSandboxBlocks(v2Explicit, legacy) {
1000
1009
  // Top-level permissions: V1 `permission` + V2 `permissions` coexistence
1001
1010
  // ---------------------------------------------------------------------------
1002
1011
 
1003
- /**
1004
- * Merge converted V1 rules into an existing V2 permissions array.
1005
- *
1006
- * The V2 array is the base and is never discarded. Incoming rules are appended
1007
- * when their action+resource is new, and merged with `resolveEffects` when they
1008
- * collide, so a deny already on disk cannot be downgraded by a later rule.
1009
- *
1010
- * Entries carry their source while merging so `warnSuppressedPermissions` can
1011
- * distinguish an intentional same-block scope (silent) from a cross-source
1012
- * override that neutralises a persisted deny (warned).
1013
- */
1012
+ /** Append converted V1 entries after existing V2 entries without reordering or deduplication. */
1014
1013
  function mergePermissionArrays(base, incoming) {
1015
- // Ordering is necessary for determinism once V1 rules join the array. Check
1016
- // whether that reorder alone weakens an existing V2 decision before applying
1017
- // it, so the change is never silent (B6).
1018
- const validBase = base.filter(isValidPermissionEntry)
1019
- warnOrderingChangesEffectiveEffect(validBase, sortPermissions(validBase))
1020
-
1021
- const sources = new Map()
1022
- const result = base.map((entry) => {
1023
- const copy = isPlainObject(entry) ? { ...entry } : entry
1024
- sources.set(copy, 'V2 permissions')
1025
- return copy
1026
- })
1027
- const index = new Map()
1028
- result.forEach((entry, position) => {
1029
- if (
1030
- isPlainObject(entry) &&
1031
- typeof entry.action === 'string' &&
1032
- typeof entry.resource === 'string'
1033
- ) {
1034
- index.set(`${entry.action}\u0000${entry.resource}`, position)
1035
- }
1036
- })
1014
+ warnInvalidPermissionEntries(base)
1015
+ return [...base, ...incoming]
1016
+ }
1037
1017
 
1038
- for (const entry of incoming) {
1039
- if (
1040
- !isPlainObject(entry) ||
1041
- typeof entry.action !== 'string' ||
1042
- typeof entry.resource !== 'string'
1043
- ) {
1044
- // Preserve a shape we cannot merge rather than dropping the rule.
1045
- result.push(entry)
1046
- sources.set(entry, 'V1 permission')
1047
- continue
1048
- }
1049
- const key = `${entry.action}\u0000${entry.resource}`
1050
- const existing = index.get(key)
1051
- if (existing === undefined) {
1052
- const copy = { ...entry }
1053
- index.set(key, result.length)
1054
- result.push(copy)
1055
- sources.set(copy, 'V1 permission')
1056
- continue
1057
- }
1058
- result[existing].effect = resolveEffects(
1059
- result[existing].effect,
1060
- entry.effect,
1061
- `${entry.action} "${entry.resource}"`,
1018
+ function assertNoConflictingV1AndV2PermissionRules(v2, convertedV1) {
1019
+ const conflicts = convertedV1.some(
1020
+ (legacy) =>
1021
+ isValidPermissionEntry(legacy) &&
1022
+ v2.some(
1023
+ (native) =>
1024
+ isValidPermissionEntry(native) &&
1025
+ legacy.effect !== native.effect &&
1026
+ opencodeWildcardPatternsOverlap(native.action, legacy.action) &&
1027
+ opencodeWildcardPatternsOverlap(native.resource, legacy.resource),
1028
+ ),
1029
+ )
1030
+ if (conflicts) {
1031
+ throw new Error(
1032
+ 'Conflicting V1 and native V2 permission rules require an explicit policy choice; migration stopped.',
1062
1033
  )
1063
1034
  }
1064
-
1065
- const sorted = sortPermissions(result)
1066
- warnSuppressedPermissions(sorted, sources)
1067
- return sorted
1068
- }
1069
-
1070
- /**
1071
- * Servers `applyMcpServerEntries` seeds on every install. Their presence in
1072
- * `mcp` means the install path already ran and reported every `ask` entry via
1073
- * `S.mcpAskNotEnforceable`, so the migration must not repeat it: one warning
1074
- * per server. A standalone migration has no such markers and still warns here.
1075
- */
1076
- const INSTALLER_MCP_SERVERS = Object.freeze([
1077
- 'pantheon-resources',
1078
- 'pantheon-code-mode',
1079
- 'pantheon-memory',
1080
- 'pantheon-persistence',
1081
- 'pantheon-vision',
1082
- ])
1083
-
1084
- function isInstallerPrepared(config) {
1085
- if (!isPlainObject(config) || !isPlainObject(config.mcp)) return false
1086
- return INSTALLER_MCP_SERVERS.every((server) => Object.hasOwn(config.mcp, server))
1087
1035
  }
1088
1036
 
1089
1037
  /**
1090
1038
  * Resolve top-level `permission` (V1) and `permissions` (V2) when both exist.
1091
1039
  *
1092
- * Precedence is fixed and does NOT depend on the order the keys appear in the
1093
- * object:
1094
- * 1. the existing V2 `permissions` array is the base (it is the target
1095
- * format and may already carry rules a previous install wrote);
1096
- * 2. the converted V1 `permission` rules are merged into it;
1097
- * 3. same action+resource conflicts resolve by restrictiveness
1098
- * (`deny > ask > allow`), and an unrecognized effect never replaces a
1099
- * known one — see `resolveEffects`.
1100
- *
1101
- * A V2 array with no V1 block is returned VERBATIM: reordering user state can
1102
- * turn a `deny` into an `allow` under last-match-wins (B6), so the pure V2 path
1103
- * never sorts. Ordering is only introduced by the merge, where determinism
1104
- * requires it, and a weakening reorder is reported.
1040
+ * When both shapes exist, the existing V2 array remains first and converted V1
1041
+ * rules are appended in source order. No rule is sorted, deduplicated, or
1042
+ * resolved by an invented restrictiveness policy.
1105
1043
  *
1106
1044
  * @param {object} config - deep-cloned input config
1107
1045
  * @returns {{present: boolean, value: any}}
1108
1046
  */
1109
- function resolveTopLevelPermissions(config) {
1047
+ function resolveTopLevelPermissions(config, configuredMcpServers = []) {
1110
1048
  const hasV1 = Object.hasOwn(config, 'permission')
1111
1049
  const hasV2 = Object.hasOwn(config, 'permissions')
1112
1050
  if (!hasV1 && !hasV2) return { present: false, value: undefined }
@@ -1114,11 +1052,8 @@ function resolveTopLevelPermissions(config) {
1114
1052
  const v1 = hasV1 ? config.permission : undefined
1115
1053
  const v2 = hasV2 ? config.permissions : undefined
1116
1054
  const v1IsObject = isPlainObject(v1)
1117
- const convertOptions = { suppressAskWarning: isInstallerPrepared(config) }
1118
- const convertedV1 = v1IsObject ? convertPermissionsV1toV2(v1, convertOptions) : undefined
1119
- // A V1 block that converts to zero rules (`permission: {}`, or only entries
1120
- // that are not rules) is not a block to merge. Treating it as one used to
1121
- // reorder a pure V2 array, which can downgrade a deny under last-match-wins.
1055
+ const convertedV1 = v1IsObject ? convertPermissionsV1toV2(v1, configuredMcpServers) : undefined
1056
+ // An empty V1 block adds nothing to an existing V2 array.
1122
1057
  const hasV1Rules = Array.isArray(convertedV1) && convertedV1.length > 0
1123
1058
 
1124
1059
  if (!hasV2) {
@@ -1145,6 +1080,8 @@ function resolveTopLevelPermissions(config) {
1145
1080
  }
1146
1081
  if (!hasV1Rules) return { present: true, value: v2 }
1147
1082
 
1083
+ assertNoConflictingV1AndV2PermissionRules(v2, convertedV1)
1084
+
1148
1085
  console.warn(
1149
1086
  '[config-migration] both "permission" (V1) and "permissions" (V2) are present; merging the V1 rules into the existing V2 array',
1150
1087
  )
@@ -1165,10 +1102,24 @@ function resolveTopLevelPermissions(config) {
1165
1102
  * @param {object} config - V1 config object (not mutated)
1166
1103
  * @returns {object} V2 config object
1167
1104
  */
1168
- export function migrateV1toV2(config) {
1105
+ function configuredMcpServerNames(mcpConfig) {
1106
+ if (!isPlainObject(mcpConfig)) return []
1107
+ const { hasV2ServersMap, legacyServersToggle } = validateMcpV1toV2Source(mcpConfig)
1108
+ return Object.entries(mcpConfig).flatMap(([name, value]) => {
1109
+ if (hasV2ServersMap && name === 'servers') return Object.keys(value)
1110
+ if (legacyServersToggle && name === 'servers') return []
1111
+ return [name]
1112
+ })
1113
+ }
1114
+
1115
+ export function migrateV1toV2(config, { mcpServerNames = [] } = {}) {
1169
1116
  const c = deepClone(config)
1117
+ // JSON cloning omits own properties whose value is undefined. Keep a present
1118
+ // MCP field visible to validation so it cannot be mistaken for absence.
1119
+ if (Object.hasOwn(config, 'mcp') && config.mcp === undefined) c.mcp = undefined
1170
1120
  const result = {}
1171
- const topLevelPermissions = resolveTopLevelPermissions(c)
1121
+ const allMcpServerNames = [...new Set([...configuredMcpServerNames(c.mcp), ...mcpServerNames])]
1122
+ const topLevelPermissions = resolveTopLevelPermissions(c, allMcpServerNames)
1172
1123
  let permissionsEmitted = false
1173
1124
 
1174
1125
  for (const [key, value] of Object.entries(c)) {
@@ -1184,7 +1135,7 @@ export function migrateV1toV2(config) {
1184
1135
  for (const [agentName, agentConfig] of Object.entries(value)) {
1185
1136
  const ac = { ...agentConfig }
1186
1137
  if (ac.permission && typeof ac.permission === 'object') {
1187
- ac.permissions = convertPermissionsV1toV2(ac.permission)
1138
+ ac.permissions = convertPermissionsV1toV2(ac.permission, allMcpServerNames)
1188
1139
  delete ac.permission
1189
1140
  }
1190
1141
  agents[agentName] = ac
@@ -1210,7 +1161,7 @@ export function migrateV1toV2(config) {
1210
1161
  providers[renamed] = convertProviderV1toV2(provName, provConfig)
1211
1162
  }
1212
1163
  result.providers = providers
1213
- } else if (key === 'mcp' && typeof value === 'object' && value !== null) {
1164
+ } else if (key === 'mcp') {
1214
1165
  result.mcp = convertMcpV1toV2(value)
1215
1166
  } else if (v2Key !== key) {
1216
1167
  result[v2Key] = value