pantheon-opencode 1.6.0-beta.9 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +144 -365
  4. package/README.md +124 -607
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +504 -141
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +22 -13
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +850 -45
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +99 -383
  29. package/scripts/install/interrupt.mjs +78 -0
  30. package/scripts/install/migrate.mjs +49 -25
  31. package/scripts/install/model-picker.mjs +218 -250
  32. package/scripts/install/opencode-state.mjs +91 -0
  33. package/scripts/install/opencode-version.mjs +83 -21
  34. package/scripts/install/opencode.mjs +1675 -187
  35. package/scripts/install/plan-artifact.mjs +517 -0
  36. package/scripts/install/plan.mjs +475 -0
  37. package/scripts/install/plugin.mjs +214 -27
  38. package/scripts/install/prompt-result.mjs +2 -0
  39. package/scripts/install/run-record.mjs +115 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +93 -8
  43. package/scripts/install/v2-capabilities.mjs +205 -0
  44. package/scripts/install/venv.mjs +90 -47
  45. package/scripts/install/verify.mjs +128 -0
  46. package/scripts/install/vision-prompt.mjs +173 -0
  47. package/scripts/install-mcp.mjs +2 -2
  48. package/scripts/manifest-inventory.mjs +49 -3
  49. package/scripts/mcp_persistence.py +1535 -1050
  50. package/scripts/memory_mcp.py +12 -843
  51. package/scripts/node-engine-policy.mjs +85 -0
  52. package/scripts/package-evidence.mjs +10 -2
  53. package/scripts/postinstall.mjs +26 -26
  54. package/scripts/probe-pantheon-cost.mjs +118 -19
  55. package/scripts/prune.mjs +9 -3
  56. package/scripts/reconcile.mjs +325 -0
  57. package/scripts/release-gates.mjs +687 -0
  58. package/scripts/restore.mjs +222 -0
  59. package/scripts/run-node-tests.mjs +24 -8
  60. package/scripts/sync-artifacts.mjs +19 -7
  61. package/scripts/sync-tui.mjs +5 -1
  62. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  63. package/scripts/uninstall.mjs +369 -34
  64. package/scripts/update.mjs +164 -0
  65. package/scripts/validate-node-engine-policy.mjs +13 -0
  66. package/scripts/version-check.mjs +34 -1
  67. package/scripts/versioning.mjs +23 -3
  68. package/scripts/vision-status.mjs +682 -0
  69. package/skills-lock.json +8 -8
  70. package/src/agents/aphrodite.md +13 -10
  71. package/src/agents/apollo.md +4 -5
  72. package/src/agents/athena.md +74 -46
  73. package/src/agents/demeter.md +10 -7
  74. package/src/agents/gaia.md +0 -1
  75. package/src/agents/hephaestus.md +4 -3
  76. package/src/agents/hermes.md +10 -9
  77. package/src/agents/iris.md +6 -1
  78. package/src/agents/mnemosyne.md +10 -4
  79. package/src/agents/nyx.md +4 -4
  80. package/src/agents/prometheus.md +12 -11
  81. package/src/agents/talos.md +6 -0
  82. package/src/agents/zeus.md +84 -56
  83. package/src/instructions/agent-return-format.instructions.md +12 -41
  84. package/src/instructions/memory-protocol.instructions.md +5 -11
  85. package/src/instructions/test-economy.instructions.md +12 -0
  86. package/src/instructions/yagni.instructions.md +6 -15
  87. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  88. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  89. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  90. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  91. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  92. package/src/mcp/_pantheon_paths.py +24 -0
  93. package/src/mcp/mcp_codemap_module.py +86 -18
  94. package/src/mcp/mcp_persistence.py +1535 -1050
  95. package/src/mcp/memory_mcp.py +444 -94
  96. package/src/mcp/pantheon_vision.py +285 -41
  97. package/src/mcp/requirements-mcp.txt +6 -1
  98. package/src/mcp/requirements-vision.txt +1 -1
  99. package/src/pantheon/context-pruner.ts +541 -0
  100. package/src/pantheon/cost-command.ts +901 -60
  101. package/src/pantheon/delegation-enforce.ts +160 -23
  102. package/src/pantheon/goal-loop.ts +11 -8
  103. package/src/pantheon/guard-path.ts +162 -0
  104. package/src/pantheon/memory-context.ts +1017 -0
  105. package/src/pantheon/model-agents.ts +19 -0
  106. package/src/pantheon/model-command.ts +218 -56
  107. package/src/pantheon/model-pricing.ts +536 -0
  108. package/src/pantheon/presets.mjs +2 -0
  109. package/src/pantheon/task-result-guard.ts +50 -14
  110. package/src/pantheon/v2-bounded-read.ts +654 -0
  111. package/src/pantheon/v2-bridge.ts +27 -0
  112. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  113. package/src/pantheon/v2-execute-after.ts +135 -24
  114. package/src/pantheon/v2-model-overrides.ts +275 -0
  115. package/src/pantheon/v2-shell-hooks.ts +260 -0
  116. package/src/pantheon/v2-tools.ts +89 -35
  117. package/src/pantheon/v2-unsupported.mjs +34 -7
  118. package/src/pantheon/v2-vision.ts +622 -0
  119. package/src/pantheon/vision-local.ts +531 -0
  120. package/src/pantheon/vision.ts +1166 -116
  121. package/src/plugin-v2.ts +1039 -171
  122. package/src/plugin.ts +37 -13
  123. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  124. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  125. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  126. package/src/plugins/tui/dist/tui.js +1 -1
  127. package/src/plugins/tui/package-lock.json +15 -15
  128. package/src/plugins/tui/package.json +7 -5
  129. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  130. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  131. package/src/routing.yml +50 -5
  132. package/src/skills/agent-coordination/SKILL.md +7 -2
  133. package/src/skills/artifact-management/SKILL.md +5 -1
  134. package/src/skills/auto-continue/SKILL.md +14 -6
  135. package/src/skills/codemap/SKILL.md +1 -1
  136. package/src/skills/memory-bank/SKILL.md +21 -13
  137. package/src/skills/session-goal/SKILL.md +12 -22
  138. package/src/skills/spec-driven-development/SKILL.md +3 -1
  139. package/src/skills/worktrees/SKILL.md +30 -11
  140. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -29,70 +29,462 @@ function deepClone(obj) {
29
29
  // V1 → V2 helpers
30
30
  // ---------------------------------------------------------------------------
31
31
 
32
- /** Action name mapping for permissions (V1 key → V2 action), including task → subagent. */
32
+ /**
33
+ * Action name mapping for permissions (V1 key → V2 action), including
34
+ * task → subagent.
35
+ *
36
+ * `write` is an alias of `edit`. Every V2 host measured for P0-5 (2.0.22,
37
+ * 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`.
42
+ *
43
+ * Only mappings confirmed against a host belong here: `bash → shell`, `task →
44
+ * subagent`, `read → read` and `write → edit` were observed on 2.0.22/2.0.30/
45
+ * 2.1.0/2.1.2. Identity entries (`skill`, `websearch`, `edit`) and keys left out
46
+ * of this table (`webfetch`, `mcp`, …) have no observed host action: they are
47
+ * kept as passthrough rather than renamed by guess.
48
+ */
33
49
  const V1_PERMISSION_TO_ACTION = {
34
50
  bash: 'shell',
35
51
  task: 'subagent',
36
52
  skill: 'skill',
53
+ // Listed before `write` so the reverse map resolves `edit` to the canonical
54
+ // V1 key instead of to the alias.
37
55
  edit: 'edit',
56
+ write: 'edit',
38
57
  websearch: 'websearch',
39
58
  // passthrough unknowns
40
59
  }
41
60
 
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
+ */
65
+ const EFFECT_RESTRICTIVENESS = { allow: 1, ask: 2, deny: 3 }
66
+
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
+ function isKnownEffect(effect) {
73
+ return typeof effect === 'string' && Object.hasOwn(EFFECT_RESTRICTIVENESS, effect)
74
+ }
75
+
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. */
126
+ function isValidPermissionEntry(entry) {
127
+ return (
128
+ isPlainObject(entry) && typeof entry.action === 'string' && typeof entry.resource === 'string'
129
+ )
130
+ }
131
+
132
+ /**
133
+ * Report entries that are not rule objects. They cannot be compared, so they
134
+ * are preserved verbatim (never dropped) and excluded from ordering.
135
+ */
136
+ function warnInvalidPermissionEntries(entries) {
137
+ const invalid = entries.filter((entry) => !isValidPermissionEntry(entry))
138
+ if (invalid.length === 0) return
139
+ console.warn(
140
+ `[config-migration] ${invalid.length} malformed permission ${invalid.length === 1 ? 'entry was' : 'entries were'} preserved without sorting: ${JSON.stringify(invalid)}`,
141
+ )
142
+ }
143
+
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
+ /**
267
+ * Resolve two effects proposed for the same action+resource.
268
+ *
269
+ * Security bias: `deny` always wins, including against an unrecognized effect,
270
+ * and an unrecognized effect never silently replaces a known one. When both
271
+ * effects are unrecognized they cannot be ranked, so the first is kept and the
272
+ * warning says exactly that — it makes no restrictiveness claim.
273
+ *
274
+ * @returns {string} the effect to keep
275
+ */
276
+ function resolveEffects(current, next, label) {
277
+ if (current === next) return current
278
+
279
+ const currentKnown = isKnownEffect(current)
280
+ const nextKnown = isKnownEffect(next)
281
+
282
+ if (!currentKnown && !nextKnown) {
283
+ console.warn(
284
+ `[config-migration] unrecognized effects for ${label}: "${current}" vs "${next}"; keeping the first "${current}"`,
285
+ )
286
+ return current
287
+ }
288
+ if (currentKnown && !nextKnown) {
289
+ console.warn(
290
+ `[config-migration] unrecognized effect "${next}" for ${label} cannot replace the known effect "${current}"; keeping "${current}"`,
291
+ )
292
+ return current
293
+ }
294
+ if (!currentKnown && nextKnown) {
295
+ console.warn(
296
+ `[config-migration] unrecognized effect "${current}" for ${label} was replaced by the known effect "${next}"; keeping "${next}"`,
297
+ )
298
+ return next
299
+ }
300
+
301
+ const winner = EFFECT_RESTRICTIVENESS[next] > EFFECT_RESTRICTIVENESS[current] ? next : current
302
+ console.warn(
303
+ `[config-migration] conflicting effects for ${label}: "${current}" vs "${next}"; keeping the more restrictive "${winner}"`,
304
+ )
305
+ return winner
306
+ }
307
+
308
+ /**
309
+ * Define an own enumerable property. Plain assignment is not enough for
310
+ * attacker-controlled keys: `obj['__proto__'] = value` mutates the prototype
311
+ * (or is dropped), producing a config with no key at all.
312
+ */
313
+ function setOwn(target, key, value) {
314
+ Object.defineProperty(target, key, {
315
+ value,
316
+ enumerable: true,
317
+ writable: true,
318
+ configurable: true,
319
+ })
320
+ }
321
+
322
+ /**
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.
347
+ */
348
+ const MCP_SERVER_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
349
+
350
+ /**
351
+ * Translate the V1 `permission.mcp` block.
352
+ *
353
+ * Measured on OpenCode 2.0.29–2.1.3 (P0-5 MCP gating): the host evaluates an
354
+ * MCP tool call as `<server>_<tool>` with `resources: ["*"]`. The V1 key
355
+ * `permission.mcp.<server>`, the action `mcp` and the `resource` field are all
356
+ * inert — passing them through emitted a config that enforced nothing.
357
+ *
358
+ * deny → { action: "<server>_*", resource: "*", effect: "deny" }
359
+ * allow → { action: "<server>_*", resource: "*", effect: "allow" }
360
+ * ask → no rule + warning. `ask` on an action rule HIDES the tool instead of
361
+ * prompting, so translating it would silently remove the tool; that is
362
+ * not what the user asked for, and it must not be downgraded to deny
363
+ * or upgraded to allow without saying so.
364
+ *
365
+ * An invalid server name gets the same treatment as `ask`: no rule and a
366
+ * warning, because an action the host never emits protects nothing.
367
+ *
368
+ * The glob gates every tool of the server and needs no `tools/list` discovery,
369
+ * which is why it is preferred over per-tool `<server>_<tool>` rules.
370
+ */
371
+ function convertMcpPermissions(value, result, index, { suppressAskWarning = false } = {}) {
372
+ 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
+ )
376
+ return
377
+ }
378
+ for (const [server, effect] of Object.entries(value)) {
379
+ if (!MCP_SERVER_NAME_PATTERN.test(server)) {
380
+ console.warn(
381
+ `[config-migration] permission.mcp."${server}" is an invalid MCP server name (expected ${MCP_SERVER_NAME_PATTERN}): no rule was emitted.`,
382
+ )
383
+ continue
384
+ }
385
+ if (effect === 'deny' || effect === 'allow') {
386
+ pushPermission(result, index, `${server}_*`, '*', effect)
387
+ continue
388
+ }
389
+ 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
+ }
395
+ continue
396
+ }
397
+ console.warn(
398
+ `[config-migration] permission.mcp."${server}" has unsupported effect ${JSON.stringify(effect)}; no rule was emitted.`,
399
+ )
400
+ }
401
+ }
402
+
42
403
  /**
43
404
  * Convert V1 permission object to V2 permissions array.
44
405
  *
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.
408
+ *
45
409
  * V1 shape:
46
410
  * { bash: { "git *": "allow" }, edit: "allow", skill: { "*": "allow" }, websearch: "deny" }
47
411
  *
48
412
  * V2 shape:
49
413
  * [ { action: "shell", resource: "git *", effect: "allow" }, ... ]
50
414
  */
51
- function convertPermissionsV1toV2(permObj) {
415
+ function convertPermissionsV1toV2(permObj, options = {}) {
52
416
  const result = []
417
+ const index = new Map()
53
418
  for (const [key, value] of Object.entries(permObj)) {
54
- const action = V1_PERMISSION_TO_ACTION[key] || key
419
+ // `permission.mcp` is a server map, not an action name: it needs its own
420
+ // translation (see convertMcpPermissions).
421
+ if (key === 'mcp') {
422
+ convertMcpPermissions(value, result, index, options)
423
+ continue
424
+ }
425
+ const action = Object.hasOwn(V1_PERMISSION_TO_ACTION, key) ? V1_PERMISSION_TO_ACTION[key] : key
55
426
  if (typeof value === 'string') {
56
427
  // Simple: { edit: "allow" } → [{ action: "edit", resource: "*", effect: "allow" }]
57
- result.push({ action, resource: '*', effect: value })
428
+ pushPermission(result, index, action, '*', value)
58
429
  } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
59
430
  // Nested: { bash: { "git *": "allow" } } → [{ action: "shell", resource: "git *", effect: "allow" }]
60
431
  for (const [resource, effect] of Object.entries(value)) {
61
- result.push({ action, resource, effect })
432
+ pushPermission(result, index, action, resource, effect)
62
433
  }
63
434
  } else {
64
435
  console.warn(`[config-migration] Unexpected permission value for "${key}":`, value)
65
436
  }
66
437
  }
67
- return result
438
+ return sortPermissions(result)
68
439
  }
69
440
 
70
441
  /**
71
442
  * Convert V2 permissions array back to V1 permission object.
443
+ *
444
+ * Rules that land on the same V1 key+resource are merged with the same
445
+ * restrictiveness policy as the forward map (`deny > ask > allow`, `deny`
446
+ * always wins, an unrecognized effect never replaces a known one). "Last wins"
447
+ * would let `[{edit,*,deny},{edit,*,allow}]` downgrade a deny to allow, which
448
+ * is the opposite of what the forward direction guarantees.
72
449
  */
73
450
  function convertPermissionsV2toV1(permArray) {
74
- const result = {}
75
- // Reverse action mapping: V2 action → V1 key
76
- const ACTION_TO_V1 = Object.fromEntries(
77
- Object.entries(V1_PERMISSION_TO_ACTION).map(([k, v]) => [v, k]),
78
- )
451
+ // Reverse action mapping: V2 action → V1 key. Aliases collapse onto one action
452
+ // (`write` and `edit` both → `edit`), so the FIRST key wins — the canonical
453
+ // V1 spelling — instead of the alias that happens to be listed last.
454
+ // Null prototype + hasOwn: actions named like Object.prototype members
455
+ // (`__proto__`, `constructor`, `toString`) must pass through literally.
456
+ const ACTION_TO_V1 = Object.create(null)
457
+ for (const [v1Key, action] of Object.entries(V1_PERMISSION_TO_ACTION)) {
458
+ if (!Object.hasOwn(ACTION_TO_V1, action)) ACTION_TO_V1[action] = v1Key
459
+ }
79
460
 
461
+ // Group by V1 key first, resolving collisions per resource, so the output
462
+ // shape (scalar for a lone "*" rule, object otherwise) does not depend on
463
+ // array order.
464
+ const byKey = new Map()
80
465
  for (const { action, resource, effect } of permArray) {
81
- const v1Key = ACTION_TO_V1[action] || action
82
- if (resource === '*') {
83
- result[v1Key] = effect
84
- } else {
85
- if (!result[v1Key] || typeof result[v1Key] === 'string') {
86
- // Convert scalar to object
87
- if (typeof result[v1Key] === 'string') {
88
- const prevEffect = result[v1Key]
89
- result[v1Key] = { '*': prevEffect }
90
- } else {
91
- result[v1Key] = {}
92
- }
93
- }
94
- result[v1Key][resource] = effect
466
+ const v1Key = Object.hasOwn(ACTION_TO_V1, action) ? ACTION_TO_V1[action] : action
467
+ let rules = byKey.get(v1Key)
468
+ if (rules === undefined) {
469
+ rules = new Map()
470
+ byKey.set(v1Key, rules)
471
+ }
472
+ const label = `permission "${v1Key}" resource "${resource}"`
473
+ rules.set(
474
+ resource,
475
+ rules.has(resource) ? resolveEffects(rules.get(resource), effect, label) : effect,
476
+ )
477
+ }
478
+
479
+ const result = {}
480
+ for (const [v1Key, rules] of byKey) {
481
+ if (rules.size === 1 && rules.has('*')) {
482
+ setOwn(result, v1Key, rules.get('*'))
483
+ continue
95
484
  }
485
+ const group = {}
486
+ for (const [resource, effect] of rules) setOwn(group, resource, effect)
487
+ setOwn(result, v1Key, group)
96
488
  }
97
489
  return result
98
490
  }
@@ -604,6 +996,161 @@ export function mergeContextSandboxBlocks(v2Explicit, legacy) {
604
996
  return merged
605
997
  }
606
998
 
999
+ // ---------------------------------------------------------------------------
1000
+ // Top-level permissions: V1 `permission` + V2 `permissions` coexistence
1001
+ // ---------------------------------------------------------------------------
1002
+
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
+ */
1014
+ 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
+ })
1037
+
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}"`,
1062
+ )
1063
+ }
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
+ }
1088
+
1089
+ /**
1090
+ * Resolve top-level `permission` (V1) and `permissions` (V2) when both exist.
1091
+ *
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.
1105
+ *
1106
+ * @param {object} config - deep-cloned input config
1107
+ * @returns {{present: boolean, value: any}}
1108
+ */
1109
+ function resolveTopLevelPermissions(config) {
1110
+ const hasV1 = Object.hasOwn(config, 'permission')
1111
+ const hasV2 = Object.hasOwn(config, 'permissions')
1112
+ if (!hasV1 && !hasV2) return { present: false, value: undefined }
1113
+
1114
+ const v1 = hasV1 ? config.permission : undefined
1115
+ const v2 = hasV2 ? config.permissions : undefined
1116
+ 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.
1122
+ const hasV1Rules = Array.isArray(convertedV1) && convertedV1.length > 0
1123
+
1124
+ if (!hasV2) {
1125
+ return { present: true, value: v1IsObject ? convertedV1 : v1 }
1126
+ }
1127
+ if (!Array.isArray(v2)) {
1128
+ if (v1IsObject) {
1129
+ console.warn(
1130
+ '[config-migration] "permissions" is not an array; keeping the rules converted from the V1 "permission" block instead',
1131
+ )
1132
+ return { present: true, value: convertedV1 }
1133
+ }
1134
+ return { present: true, value: v2 }
1135
+ }
1136
+ if (!hasV1) {
1137
+ warnInvalidPermissionEntries(v2)
1138
+ return { present: true, value: v2 }
1139
+ }
1140
+ if (!v1IsObject) {
1141
+ console.warn(
1142
+ '[config-migration] both "permission" and "permissions" are present; the V1 "permission" value is not an object and was ignored, keeping the V2 "permissions" array',
1143
+ )
1144
+ return { present: true, value: v2 }
1145
+ }
1146
+ if (!hasV1Rules) return { present: true, value: v2 }
1147
+
1148
+ console.warn(
1149
+ '[config-migration] both "permission" (V1) and "permissions" (V2) are present; merging the V1 rules into the existing V2 array',
1150
+ )
1151
+ return { present: true, value: mergePermissionArrays(v2, convertedV1) }
1152
+ }
1153
+
607
1154
  // ---------------------------------------------------------------------------
608
1155
  // Public API
609
1156
  // ---------------------------------------------------------------------------
@@ -611,18 +1158,27 @@ export function mergeContextSandboxBlocks(v2Explicit, legacy) {
611
1158
  /**
612
1159
  * Migrate a V1 opencode.json config to V2 format.
613
1160
  *
1161
+ * When top-level `permission` (V1) and `permissions` (V2) coexist, the V2 array
1162
+ * is the base and the V1 rules are merged into it — see
1163
+ * `resolveTopLevelPermissions`.
1164
+ *
614
1165
  * @param {object} config - V1 config object (not mutated)
615
1166
  * @returns {object} V2 config object
616
1167
  */
617
1168
  export function migrateV1toV2(config) {
618
1169
  const c = deepClone(config)
619
1170
  const result = {}
1171
+ const topLevelPermissions = resolveTopLevelPermissions(c)
1172
+ let permissionsEmitted = false
620
1173
 
621
1174
  for (const [key, value] of Object.entries(c)) {
622
1175
  const v2Key = V1_TO_V2_RENAMES[key] || key
623
1176
 
624
- if (key === 'permission' && typeof value === 'object' && value !== null) {
625
- result.permissions = convertPermissionsV1toV2(value)
1177
+ if (key === 'permission' || key === 'permissions') {
1178
+ if (topLevelPermissions.present && !permissionsEmitted) {
1179
+ result.permissions = topLevelPermissions.value
1180
+ permissionsEmitted = true
1181
+ }
626
1182
  } else if (key === 'agent' && typeof value === 'object' && value !== null) {
627
1183
  const agents = {}
628
1184
  for (const [agentName, agentConfig] of Object.entries(value)) {