pantheon-opencode 1.6.0-beta.9 → 1.6.0

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 (131) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -376
  4. package/README.md +83 -610
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +19 -11
  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 +828 -40
  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 +78 -383
  29. package/scripts/install/migrate.mjs +49 -25
  30. package/scripts/install/model-picker.mjs +218 -250
  31. package/scripts/install/opencode-version.mjs +83 -21
  32. package/scripts/install/opencode.mjs +1413 -154
  33. package/scripts/install/plan-artifact.mjs +517 -0
  34. package/scripts/install/plan.mjs +475 -0
  35. package/scripts/install/plugin.mjs +214 -27
  36. package/scripts/install/prompt-result.mjs +2 -0
  37. package/scripts/install/shared.mjs +256 -99
  38. package/scripts/install/state.mjs +63 -8
  39. package/scripts/install/strings.mjs +60 -4
  40. package/scripts/install/venv.mjs +90 -47
  41. package/scripts/install/verify.mjs +128 -0
  42. package/scripts/install/vision-prompt.mjs +173 -0
  43. package/scripts/install-mcp.mjs +2 -2
  44. package/scripts/manifest-inventory.mjs +49 -3
  45. package/scripts/mcp_persistence.py +1535 -1050
  46. package/scripts/memory_mcp.py +12 -843
  47. package/scripts/node-engine-policy.mjs +85 -0
  48. package/scripts/package-evidence.mjs +10 -2
  49. package/scripts/postinstall.mjs +26 -26
  50. package/scripts/probe-pantheon-cost.mjs +118 -19
  51. package/scripts/prune.mjs +9 -3
  52. package/scripts/reconcile.mjs +325 -0
  53. package/scripts/release-gates.mjs +682 -0
  54. package/scripts/restore.mjs +222 -0
  55. package/scripts/run-node-tests.mjs +24 -8
  56. package/scripts/sync-artifacts.mjs +19 -7
  57. package/scripts/sync-tui.mjs +5 -1
  58. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  59. package/scripts/uninstall.mjs +369 -34
  60. package/scripts/update.mjs +164 -0
  61. package/scripts/validate-node-engine-policy.mjs +13 -0
  62. package/scripts/version-check.mjs +34 -1
  63. package/scripts/versioning.mjs +23 -3
  64. package/scripts/vision-status.mjs +682 -0
  65. package/skills-lock.json +8 -8
  66. package/src/agents/aphrodite.md +13 -10
  67. package/src/agents/apollo.md +4 -5
  68. package/src/agents/athena.md +74 -46
  69. package/src/agents/demeter.md +10 -7
  70. package/src/agents/gaia.md +0 -1
  71. package/src/agents/hephaestus.md +4 -3
  72. package/src/agents/hermes.md +10 -9
  73. package/src/agents/iris.md +6 -1
  74. package/src/agents/mnemosyne.md +10 -4
  75. package/src/agents/nyx.md +4 -4
  76. package/src/agents/prometheus.md +12 -11
  77. package/src/agents/talos.md +6 -0
  78. package/src/agents/zeus.md +84 -56
  79. package/src/instructions/agent-return-format.instructions.md +12 -41
  80. package/src/instructions/memory-protocol.instructions.md +5 -11
  81. package/src/instructions/test-economy.instructions.md +12 -0
  82. package/src/instructions/yagni.instructions.md +6 -15
  83. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  84. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  85. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  86. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  87. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  88. package/src/mcp/_pantheon_paths.py +24 -0
  89. package/src/mcp/mcp_codemap_module.py +86 -18
  90. package/src/mcp/mcp_persistence.py +1535 -1050
  91. package/src/mcp/memory_mcp.py +444 -94
  92. package/src/mcp/pantheon_vision.py +285 -41
  93. package/src/mcp/requirements-mcp.txt +5 -0
  94. package/src/pantheon/context-pruner.ts +541 -0
  95. package/src/pantheon/cost-command.ts +814 -60
  96. package/src/pantheon/goal-loop.ts +11 -8
  97. package/src/pantheon/memory-context.ts +1017 -0
  98. package/src/pantheon/model-agents.ts +19 -0
  99. package/src/pantheon/model-command.ts +218 -56
  100. package/src/pantheon/model-pricing.ts +536 -0
  101. package/src/pantheon/presets.mjs +2 -0
  102. package/src/pantheon/task-result-guard.ts +50 -14
  103. package/src/pantheon/v2-bounded-read.ts +640 -0
  104. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  105. package/src/pantheon/v2-execute-after.ts +135 -24
  106. package/src/pantheon/v2-model-overrides.ts +275 -0
  107. package/src/pantheon/v2-tools.ts +89 -35
  108. package/src/pantheon/v2-unsupported.mjs +2 -3
  109. package/src/pantheon/v2-vision.ts +622 -0
  110. package/src/pantheon/vision-local.ts +531 -0
  111. package/src/pantheon/vision.ts +1160 -115
  112. package/src/plugin-v2.ts +654 -162
  113. package/src/plugin.ts +15 -11
  114. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  115. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  117. package/src/plugins/tui/dist/tui.js +1 -1
  118. package/src/plugins/tui/package-lock.json +6 -6
  119. package/src/plugins/tui/package.json +5 -4
  120. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  121. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  122. package/src/routing.yml +50 -5
  123. package/src/skills/agent-coordination/SKILL.md +7 -2
  124. package/src/skills/artifact-management/SKILL.md +5 -1
  125. package/src/skills/auto-continue/SKILL.md +14 -6
  126. package/src/skills/codemap/SKILL.md +1 -1
  127. package/src/skills/memory-bank/SKILL.md +21 -13
  128. package/src/skills/session-goal/SKILL.md +12 -22
  129. package/src/skills/spec-driven-development/SKILL.md +3 -1
  130. package/src/skills/worktrees/SKILL.md +30 -11
  131. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -17,22 +17,28 @@
17
17
  */
18
18
 
19
19
  import { createHash } from 'node:crypto'
20
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
20
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
21
21
  import { homedir } from 'node:os'
22
- import { dirname, isAbsolute, join, resolve } from 'node:path'
22
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
23
23
  import { listV2UnsupportedFeatures } from '../../src/pantheon/v2-unsupported.mjs'
24
- import { copyAgentPrompts } from '../build-agents-md.mjs'
24
+ import { copyAgentPrompts, writeAgentsMdManaged } from '../build-agents-md.mjs'
25
+ import { backupWarning, createBackupSet, previewBackupSet } from './backup.mjs'
25
26
  import {
26
27
  bullet,
27
28
  colors,
28
29
  configure,
30
+ gauge as createGauge,
31
+ endGaugeLine,
29
32
  error,
30
33
  info,
34
+ notice,
31
35
  printSummary,
36
+ printWorktreeGuidance,
32
37
  section,
33
38
  spinner,
34
39
  step,
35
40
  success,
41
+ tag,
36
42
  warning,
37
43
  } from './cli-ui.mjs'
38
44
  import {
@@ -40,10 +46,27 @@ import {
40
46
  migrateMcpEntrypointPaths,
41
47
  migrateV1toV2,
42
48
  } from './config-migration.mjs'
49
+ import { componentForInstalledPath, updateFileInventory } from './file-inventory.mjs'
43
50
  import { healthCheck } from './health-check.mjs'
44
51
  import { detectVersion, runMigrations } from './migrate.mjs'
45
- import { resolveOpenCodeVersion } from './opencode-version.mjs'
52
+ import { DRY_RUN_PROBE_TIMEOUT_MS, resolveOpenCodeVersion } from './opencode-version.mjs'
53
+ import {
54
+ ACTIONS,
55
+ createRecorder,
56
+ displayPath,
57
+ fingerprintOutput,
58
+ formatChangePlan,
59
+ isRecording,
60
+ planStatsMismatch,
61
+ recordChange,
62
+ recordRemovalTree,
63
+ removeReviewedTree,
64
+ snapshot,
65
+ summarizeChanges,
66
+ } from './plan.mjs'
67
+ import { findPlanDrift } from './plan-artifact.mjs'
46
68
  import { copyPluginFiles, installPlugin, registerPlugin, unregisterPlugin } from './plugin.mjs'
69
+ import { PROMPT_CANCELED } from './prompt-result.mjs'
47
70
  import {
48
71
  checkRuntimePrerequisites,
49
72
  collectSkillNames,
@@ -60,6 +83,7 @@ import { createInitialState, hasState, readState, setComponentState, writeState
60
83
  import { strings } from './strings.mjs'
61
84
 
62
85
  import { setupVenv, venvPythonPath } from './venv.mjs'
86
+ import { assertNoSymlinkAncestors, assertPathWithin, assertSafeRemoval } from './verify.mjs'
63
87
 
64
88
  const COMPONENT_NAMES = [
65
89
  'agents',
@@ -71,6 +95,211 @@ const COMPONENT_NAMES = [
71
95
  'runtime',
72
96
  ]
73
97
 
98
+ /**
99
+ * The ordered phases one install invocation really runs, derived from the
100
+ * FINAL component selection (the interactive wizard may have changed it) and
101
+ * from dry-run semantics. `gauge.total` must be this length — never a fixed
102
+ * guess — so the counter can never drift from the work.
103
+ *
104
+ * * prerequisites run only on an apply with the runtime component;
105
+ * * the backup is planned (dry run) or created (apply);
106
+ * * venv setup runs in BOTH modes (a dry run reports what it would create);
107
+ * * the health check and the install-state write are apply-only.
108
+ *
109
+ * @param {{ components: Iterable<string>, dryRun: boolean }} options
110
+ * @returns {string[]} phase labels, in execution order
111
+ */
112
+ export function planInstallPhases({ components, dryRun }) {
113
+ const S = strings()
114
+ const selected = new Set(components)
115
+ const phases = []
116
+ if (selected.has('runtime') && !dryRun) phases.push(S.checkingPrerequisites)
117
+ phases.push(dryRun ? S.planningBackup : S.creatingBackup)
118
+ if (selected.has('agents')) phases.push(S.installingAgents)
119
+ if (selected.has('skills')) phases.push(S.installingSkills)
120
+ if (selected.has('instructions')) phases.push(S.installingInstructions)
121
+ if (selected.has('prompts')) phases.push(S.installingPrompts)
122
+ if (selected.has('commands')) phases.push(S.installingCommands)
123
+ if (selected.has('plugins')) phases.push(S.installingPlugins)
124
+ if (selected.has('runtime')) {
125
+ phases.push(S.installingRuntime)
126
+ phases.push(S.settingUpRuntime)
127
+ if (!dryRun) phases.push(S.runningHealthChecks)
128
+ }
129
+ phases.push(S.writingConfiguration)
130
+ if (selected.has('runtime')) phases.push(S.runningMigrations)
131
+ if (!dryRun) phases.push(S.recordingState)
132
+ return phases
133
+ }
134
+
135
+ /**
136
+ * MCP server scripts the runtime component installs. Hoisted so the backup-set
137
+ * enumeration and the runtime writer share one source of truth.
138
+ */
139
+ const MCP_SCRIPTS = [
140
+ 'mcp_resources.py',
141
+ 'code_mode.py',
142
+ 'memory_mcp.py',
143
+ 'scrub-secrets.py',
144
+ '_pantheon_paths.py',
145
+ 'mcp_codemap_module.py',
146
+ 'mcp_persistence.py',
147
+ 'pantheon_vision.py',
148
+ 'eval_store.py',
149
+ 'themis_heuristic_scan.py',
150
+ ]
151
+
152
+ /** Recursively list regular files under `root`, relative to `root`. */
153
+ function walkFiles(root, base = root, out = []) {
154
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
155
+ const full = join(root, entry.name)
156
+ if (entry.isDirectory()) walkFiles(full, base, out)
157
+ else if (entry.isFile()) out.push(relative(base, full))
158
+ }
159
+ return out
160
+ }
161
+
162
+ /**
163
+ * Enumerate what the backup set must preserve, derived from the selected
164
+ * components. It returns:
165
+ * - `entries`: paths (relative to `target`) the run can CREATE/UPDATE/REMOVE.
166
+ * For every managed destination tree we take the UNION of the files that
167
+ * already exist there (so a `--clean`, a stale removal, or an
168
+ * instructions-only refresh is captured) and the source-derived destination
169
+ * paths (so a file that will be created is recorded as absent). The union is
170
+ * a superset of the plan's changes — unchanged files are backed up too.
171
+ * - `notRevertible`: paths the run may delete or write but whose byte-for-byte
172
+ * copy is not feasible or is out of the config dir (bulk `.venv` / plugin
173
+ * `node_modules`, the global `tui.json` copies and the global vision config).
174
+ * These are recorded explicitly in the manifest rather than silently ignored.
175
+ * It never reads file contents.
176
+ *
177
+ * @param {string} target
178
+ * @param {Set<string>} componentSet
179
+ * @param {string} version
180
+ * @param {boolean} isGlobal
181
+ * @returns {{ entries: string[], notRevertible: string[] }}
182
+ */
183
+ function collectInstallBackupEntries(target, componentSet, version, isGlobal) {
184
+ const entries = []
185
+ const notRevertible = []
186
+ const rel = (abs) => relative(target, abs)
187
+ const addFile = (abs) => entries.push(rel(abs))
188
+ // Existing files under an in-target tree (covers removals / clean / refresh).
189
+ // `skipDirNames` prunes bulk subdirectories (e.g. plugin `node_modules`) so the
190
+ // walk stays cheap while everything else — including legacy files a clean pass
191
+ // deletes — is captured.
192
+ const addExisting = (dir, skipDirNames = null) => {
193
+ if (!existsSync(dir)) return
194
+ const walk = (base) => {
195
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
196
+ if (skipDirNames && entry.isDirectory() && skipDirNames.has(entry.name)) continue
197
+ const full = join(base, entry.name)
198
+ if (entry.isDirectory()) walk(full)
199
+ else if (entry.isFile()) addFile(full)
200
+ }
201
+ }
202
+ walk(dir)
203
+ }
204
+ // Destination paths derived from a source tree (covers files to be created).
205
+ const addSource = (srcDir, dstDir, filter = null) => {
206
+ if (!existsSync(srcDir)) return
207
+ for (const r of walkFiles(srcDir)) {
208
+ if (filter && !filter(r)) continue
209
+ addFile(join(dstDir, r))
210
+ }
211
+ }
212
+
213
+ const baseDir = isGlobal ? target : join(target, '.opencode')
214
+ const agentPrefix = isGlobal || version === 'v2' ? 'agents' : '.opencode/agents'
215
+ const agentDir = join(target, agentPrefix)
216
+
217
+ // Always touched.
218
+ addFile(join(target, 'opencode.json'))
219
+ addFile(join(target, '.pantheon', 'install-state.json'))
220
+ addFile(join(baseDir, 'opencode-vision.json'))
221
+ // The active-preset writer (writeActivePreset(target, …)) lives at
222
+ // <target>/.pantheon, NOT under <baseDir>, for both project and global scope.
223
+ addFile(join(target, '.pantheon', 'active-preset.json'))
224
+ addFile(join(target, '.pantheon', 'active-preset.json.bak'))
225
+
226
+ // The agent prompt dir is refreshed (existing-only) by an instructions-only
227
+ // run too, so enumerate it whenever EITHER component can write it.
228
+ if (componentSet.has('agents') || componentSet.has('instructions')) {
229
+ addExisting(agentDir)
230
+ }
231
+ if (componentSet.has('agents')) {
232
+ addFile(join(target, 'routing.yml'))
233
+ addSource(
234
+ join(ROOT, 'src', 'agents'),
235
+ agentDir,
236
+ (r) => r.endsWith('.md') && r.toLowerCase() !== 'readme.md',
237
+ )
238
+ }
239
+ if (componentSet.has('skills')) {
240
+ addExisting(join(baseDir, 'skills'))
241
+ addSource(join(ROOT, 'src', 'skills'), join(baseDir, 'skills'))
242
+ }
243
+ if (componentSet.has('instructions')) addFile(join(target, 'AGENTS.md'))
244
+ if (componentSet.has('prompts')) {
245
+ addExisting(join(target, 'prompts'))
246
+ addSource(join(ROOT, 'prompts'), join(target, 'prompts'))
247
+ }
248
+ if (componentSet.has('commands')) {
249
+ const commandDir = isGlobal || version === 'v2' ? 'commands' : '.opencode/commands'
250
+ addExisting(join(target, commandDir))
251
+ addSource(join(ROOT, 'commands'), join(target, commandDir), (r) => r.endsWith('.md'))
252
+ }
253
+ if (componentSet.has('plugins')) {
254
+ const dstPluginDir = isGlobal
255
+ ? join(target, 'plugins', 'pantheon-tui')
256
+ : join(target, '.opencode', 'plugins', 'pantheon-tui')
257
+ // Existing files under the installed plugin dir (legacy `index.tsx` /
258
+ // `dist/tui.tsx` and any extras a `--clean` run deletes) are captured, like
259
+ // every sibling tree — EXCEPT the bulk `node_modules`, which is regenerated
260
+ // by `npm ci` and listed as not revertible.
261
+ addExisting(dstPluginDir, new Set(['node_modules']))
262
+ addSource(join(ROOT, 'src', 'plugins', 'tui', 'dist'), join(dstPluginDir, 'dist'))
263
+ addFile(join(dstPluginDir, 'package.json'))
264
+ addFile(join(dstPluginDir, 'package-lock.json'))
265
+ addFile(join(dstPluginDir, 'tui.ts'))
266
+ addFile(join(dstPluginDir, 'index.ts'))
267
+ notRevertible.push(rel(join(dstPluginDir, 'node_modules')))
268
+ if (version === 'v1') {
269
+ const projectTui = join(baseDir, 'tui.json')
270
+ addFile(projectTui)
271
+ // Cross-location cleanup touches copies OUTSIDE the config dir.
272
+ for (const loc of tuiConfigLocations(target)) {
273
+ if (resolve(loc) !== resolve(projectTui)) notRevertible.push(loc)
274
+ }
275
+ }
276
+ // V2's single terminal-client config, which this install also edits (it
277
+ // cancels the builtin Context sidebar block). Captured so `restore` reverts
278
+ // it byte-for-byte like every other file we touch.
279
+ if (version === 'v2' && isGlobal) addFile(join(baseDir, V2_CLI_CONFIG_FILENAME))
280
+ }
281
+ if (componentSet.has('runtime')) {
282
+ const runtimeTarget = isGlobal ? target : join(target, '.opencode')
283
+ addExisting(join(runtimeTarget, 'scripts'))
284
+ for (const script of MCP_SCRIPTS) addFile(join(runtimeTarget, 'scripts', script))
285
+ addFile(join(runtimeTarget, 'requirements-vision.txt'))
286
+ addSource(join(ROOT, '.pantheon', 'code-mode'), join(runtimeTarget, '.pantheon', 'code-mode'))
287
+ addExisting(join(runtimeTarget, '.pantheon', 'code-mode'))
288
+ addFile(join(runtimeTarget, '.pantheon', 'tiers.json'))
289
+ // `--force` recreates the venv from scratch: bulk, not copied.
290
+ notRevertible.push(rel(join(target, '.venv')))
291
+ }
292
+
293
+ // The vision config is written GLOBALLY (outside the config dir).
294
+ const xdg = process.env.XDG_CONFIG_HOME || join(homedir(), '.config')
295
+ const globalVision = join(xdg, 'opencode', 'opencode-vision.json')
296
+ if (resolve(globalVision) !== resolve(join(baseDir, 'opencode-vision.json'))) {
297
+ notRevertible.push(globalVision)
298
+ }
299
+
300
+ return { entries, notRevertible }
301
+ }
302
+
74
303
  /**
75
304
  * The product defaults an install seeds into the user's `opencode.json`.
76
305
  *
@@ -136,14 +365,27 @@ export const MANAGED_FIELDS = Object.freeze([
136
365
  'disable_model_invocation',
137
366
  ])
138
367
 
139
- const PANTHEON_MCP_SERVERS = Object.freeze([
140
- 'pantheon-resources',
141
- 'pantheon-memory',
142
- 'pantheon-code-mode',
143
- 'pantheon-persistence',
144
- 'pantheon-vision',
368
+ /**
369
+ * The five managed MCP servers, in the ORDER the installer writes them.
370
+ *
371
+ * This table is the single source for both the write (`applyMcpServerEntries`)
372
+ * and the dry-run preview: the preview names the servers this pass seeds, so
373
+ * reordering a server here changes both in lockstep. `script` is the runtime
374
+ * entrypoint, relative to the runtime directory.
375
+ *
376
+ * @type {readonly {name: string, script: string}[]}
377
+ */
378
+ const PANTHEON_MCP_SERVER_ENTRIES = Object.freeze([
379
+ Object.freeze({ name: 'pantheon-resources', script: 'scripts/mcp_resources.py' }),
380
+ Object.freeze({ name: 'pantheon-code-mode', script: 'scripts/code_mode.py' }),
381
+ Object.freeze({ name: 'pantheon-memory', script: 'scripts/memory_mcp.py' }),
382
+ Object.freeze({ name: 'pantheon-persistence', script: 'scripts/mcp_persistence.py' }),
383
+ Object.freeze({ name: 'pantheon-vision', script: 'scripts/pantheon_vision.py' }),
145
384
  ])
146
385
 
386
+ /** The managed server names, in write order. */
387
+ const PANTHEON_MCP_SERVERS = Object.freeze(PANTHEON_MCP_SERVER_ENTRIES.map((entry) => entry.name))
388
+
147
389
  function normalizeMcpPermissionSegment(value) {
148
390
  return value.replace(/[^a-zA-Z0-9_]/g, '_')
149
391
  }
@@ -210,30 +452,40 @@ function deepClone(value) {
210
452
 
211
453
  /**
212
454
  * (Re)generate the code-mode manifest with SHA-256 digests for every bundled
213
- * script. This is the explicit installation opt-in: the MCP server only
214
- * executes scripts listed here whose on-disk hash matches. Missing or empty
215
- * directories approve nothing (0) — execution is never implicit.
455
+ * script, and write it to the destination. This is the explicit installation
456
+ * opt-in: the MCP server only executes scripts listed here whose on-disk hash
457
+ * matches. Missing or empty source approves nothing — execution is never
458
+ * implicit.
459
+ *
460
+ * This function is the SINGLE owner of `manifest.json`: `syncDir` deliberately
461
+ * excludes it (see the runtime block), so exactly one writer and one stats
462
+ * count exist for that path. The payload is derived from the SOURCE scripts
463
+ * (what will be installed), then compared against the CURRENT installed
464
+ * manifest, so the preview action matches what apply writes — including on a
465
+ * script upgrade, where the installed manifest is stale.
466
+ *
467
+ * @returns {{ approved: number, status: 'created'|'skipped'|'conflict'|null }}
216
468
  */
217
- function writeCodeModeManifest(dir, dryRun) {
218
- if (!existsSync(dir)) return 0
469
+ function writeCodeModeManifest(srcDir, dstDir, dryRun, recorder = null) {
470
+ if (!existsSync(srcDir)) return { approved: 0, status: null }
219
471
  let names
220
472
  try {
221
- names = readdirSync(dir)
473
+ names = readdirSync(srcDir)
222
474
  .filter((name) => /\.(sh|py)$/i.test(name) && !name.startsWith('.'))
223
475
  .sort()
224
476
  } catch {
225
- return 0
477
+ return { approved: 0, status: null }
226
478
  }
227
- if (names.length === 0) return 0
479
+ if (names.length === 0) return { approved: 0, status: null }
228
480
  const scripts = {}
229
481
  for (const name of names) {
230
482
  scripts[name] = createHash('sha256')
231
- .update(readFileSync(join(dir, name)))
483
+ .update(readFileSync(join(srcDir, name)))
232
484
  .digest('hex')
233
485
  }
234
486
  const payload = `${JSON.stringify({ version: 1, scripts }, null, 2)}\n`
235
- writeIfChanged(join(dir, 'manifest.json'), payload, dryRun)
236
- return names.length
487
+ const status = writeIfChanged(join(dstDir, 'manifest.json'), payload, dryRun, { recorder })
488
+ return { approved: names.length, status }
237
489
  }
238
490
 
239
491
  function readJsonConfig(filePath) {
@@ -574,6 +826,249 @@ export function tuiConfigLocations(target) {
574
826
  return [...new Set([homeTui, xdgTui, projectTui])]
575
827
  }
576
828
 
829
+ /**
830
+ * V2 terminal-client config filename. V2 replaced the layered V1 `tui.json(c)`
831
+ * files with ONE GLOBAL client config (`~/.config/opencode/cli.json`); there is
832
+ * no project-local equivalent, so this file only ever lives in a config dir
833
+ * that is a global host config dir.
834
+ */
835
+ export const V2_CLI_CONFIG_FILENAME = 'cli.json'
836
+
837
+ /**
838
+ * Builtin V2 sidebar plugin that renders the Context block.
839
+ *
840
+ * Pantheon's TUI plugin renders its OWN Context block, so leaving the builtin
841
+ * enabled draws the block twice (nativo + nosso). The host cancels a plugin
842
+ * through an EXACT `-<id>` entry in the client config's `plugins` array; a
843
+ * wildcard (`-opencode.sidebar.*`) would also disable the mcp and footer blocks,
844
+ * so it is never used here.
845
+ */
846
+ export const CONTEXT_SIDEBAR_NEGATION = '-opencode.sidebar.context'
847
+
848
+ /**
849
+ * Bundle the V2 host loads from the copied TUI plugin dir (relative to it).
850
+ *
851
+ * The capability check below must read the bytes the host will ACTUALLY load,
852
+ * i.e. the copy under the config dir — never the in-package build artifact,
853
+ * which a package upgrade replaces independently of what was deployed.
854
+ */
855
+ export const TUI_V2_BUNDLE_RELATIVE_PATH = 'dist/tui-v2.js'
856
+
857
+ /**
858
+ * Stable marker proving the deployed TUI bundle renders Pantheon's own Context
859
+ * block.
860
+ *
861
+ * It is a named export of the bundle (`export { ..., contextBlockRows, ... }`).
862
+ * ESM export names are the module's public interface and CANNOT be mangled by
863
+ * tsdown/rolldown (or any minifier): mangling renames only non-exported
864
+ * bindings, because consumers resolve exports by name. The bundle also cannot
865
+ * tree-shake it away — the sidebar imports it, and
866
+ * `tests/tui-v2-sidebar.test.mjs` imports it from `dist/tui-v2.js`, so a build
867
+ * that drops the export fails the suite.
868
+ *
869
+ * A rebuild that changes the block's user-facing copy or internals keeps the
870
+ * export; only a rewrite that REMOVES the block drops it — which is exactly
871
+ * when the builtin Context block must stay enabled.
872
+ */
873
+ export const CONTEXT_BLOCK_BUNDLE_MARKER = 'contextBlockRows'
874
+
875
+ /**
876
+ * Path of the V2 TUI bundle inside an installed config dir.
877
+ *
878
+ * @param {string} configDir - OpenCode config directory
879
+ * @returns {string} absolute path of the copied `dist/tui-v2.js`
880
+ */
881
+ export function resolveInstalledTuiBundlePath(configDir) {
882
+ return join(resolveTuiCopyTarget(configDir), TUI_V2_BUNDLE_RELATIVE_PATH)
883
+ }
884
+
885
+ /**
886
+ * Pure capability test: does this bundle text provide Pantheon's Context block?
887
+ *
888
+ * Deliberately a plain byte scan: the answer must not depend on importing the
889
+ * bundle (the host API it needs is absent while installing).
890
+ *
891
+ * @param {unknown} bundleText - contents of the deployed `dist/tui-v2.js`
892
+ * @returns {{ ok: boolean, reason: string }} `reason` is empty when `ok`
893
+ */
894
+ export function bundleProvidesContextBlock(bundleText) {
895
+ if (typeof bundleText !== 'string') {
896
+ return { ok: false, reason: 'the TUI bundle could not be read as text' }
897
+ }
898
+ if (!new RegExp(`\\b${CONTEXT_BLOCK_BUNDLE_MARKER}\\b`).test(bundleText)) {
899
+ return {
900
+ ok: false,
901
+ reason:
902
+ `the deployed TUI bundle has no "${CONTEXT_BLOCK_BUNDLE_MARKER}" export, so it ` +
903
+ 'predates the Pantheon Context block',
904
+ }
905
+ }
906
+ return { ok: true, reason: '' }
907
+ }
908
+
909
+ /**
910
+ * Inspect the TUI bundle that the host will load for the given config dir.
911
+ *
912
+ * A dry run copies nothing, so it evaluates the in-package build artifact
913
+ * instead (what WOULD be deployed) and only falls back to an existing deployed
914
+ * copy — a preview must not report a capability failure that the real run
915
+ * would not have.
916
+ *
917
+ * @param {string} configDir - OpenCode config directory
918
+ * @param {object} [options]
919
+ * @param {boolean} [options.dryRun=false]
920
+ * @returns {{ ok: boolean, reason: string, bundlePath: string }}
921
+ */
922
+ export function inspectContextBlockCapability(configDir, { dryRun = false } = {}) {
923
+ const installedPath = resolveInstalledTuiBundlePath(configDir)
924
+ const sourcePath = join(ROOT, 'src', 'plugins', 'tui', TUI_V2_BUNDLE_RELATIVE_PATH)
925
+ const bundlePath = dryRun && !existsSync(installedPath) ? sourcePath : installedPath
926
+ let bundleText
927
+ try {
928
+ bundleText = readFileSync(bundlePath, 'utf8')
929
+ } catch (cause) {
930
+ return {
931
+ ok: false,
932
+ bundlePath,
933
+ reason: `${bundlePath} is missing or unreadable (${cause.code ?? cause.message})`,
934
+ }
935
+ }
936
+ return { ...bundleProvidesContextBlock(bundleText), bundlePath }
937
+ }
938
+
939
+ /**
940
+ * Remove {@link CONTEXT_SIDEBAR_NEGATION} from a V2 `plugins` array, preserving
941
+ * every other entry and its order. Only the EXACT directive is removed: the
942
+ * host honors nothing else, and a wildcard would also cancel the mcp and
943
+ * footer blocks.
944
+ *
945
+ * Idempotent: an array without the directive is returned untouched.
946
+ *
947
+ * @param {unknown} plugins - current `plugins` value (may be absent or invalid)
948
+ * @returns {{ plugins: unknown[], changed: boolean }}
949
+ */
950
+ export function withContextSidebarEnabled(plugins) {
951
+ const current = Array.isArray(plugins) ? plugins : []
952
+ const next = current.filter((entry) => entry !== CONTEXT_SIDEBAR_NEGATION)
953
+ return { plugins: next, changed: next.length !== current.length }
954
+ }
955
+
956
+ /**
957
+ * Append {@link CONTEXT_SIDEBAR_NEGATION} to a V2 `plugins` array while
958
+ * preserving every existing entry (plain strings and `{ package, options }`
959
+ * objects) and their order.
960
+ *
961
+ * Idempotent: when the exact directive is already present the array is returned
962
+ * untouched, so a second `init` never duplicates it.
963
+ *
964
+ * @param {unknown} plugins - current `plugins` value (may be absent or invalid)
965
+ * @returns {{ plugins: unknown[], changed: boolean }}
966
+ */
967
+ export function withContextSidebarDisabled(plugins) {
968
+ const current = Array.isArray(plugins) ? plugins : []
969
+ if (current.includes(CONTEXT_SIDEBAR_NEGATION)) return { plugins: current, changed: false }
970
+ return { plugins: [...current, CONTEXT_SIDEBAR_NEGATION], changed: true }
971
+ }
972
+
973
+ /**
974
+ * Reconcile the builtin Context sidebar block in the V2 terminal-client config
975
+ * with the deployed TUI bundle.
976
+ *
977
+ * Cancelling the builtin block is only safe when the deployed bundle really
978
+ * draws Pantheon's replacement (see {@link bundleProvidesContextBlock});
979
+ * negating against a stale bundle removed the Context block from the sidebar
980
+ * entirely. So the negation tracks the capability on EVERY run:
981
+ *
982
+ * capability present → add the exact negation (or leave it in place);
983
+ * capability absent → remove a previously written negation, keeping the
984
+ * native readout working, and warn with the reason and
985
+ * the rebuild/redeploy step.
986
+ *
987
+ * Only the `plugins` array is merged; the rest of the user's `cli.json` (theme,
988
+ * session, keybinds, anything else) is preserved verbatim, key order included,
989
+ * and the write is skipped byte-for-byte when the array is already correct.
990
+ * A file that cannot be parsed — or whose `plugins` is not an array — is NEVER
991
+ * overwritten: the caller reports a warning and the install continues, because
992
+ * clobbering a hand-edited client config is worse than a duplicated block.
993
+ *
994
+ * @param {string} configDir - config dir holding cli.json (global config dir)
995
+ * @param {object} [options]
996
+ * @param {boolean} [options.dryRun=false]
997
+ * @param {(change: object) => void} [options.recorder=null] - preview recorder
998
+ * @param {(message: string) => void} [options.warn] - warning sink
999
+ * @param {{ ok: boolean, reason: string } | null} [options.capability=null]
1000
+ * pre-computed verdict (tests/preview); inspected from disk when omitted
1001
+ * @returns {'created'|'removed'|'skipped'|'unverified'|'invalid'|'conflict'}
1002
+ */
1003
+ export function applyContextSidebarNegation(
1004
+ configDir,
1005
+ { dryRun = false, recorder = null, warn = warning, capability = null } = {},
1006
+ ) {
1007
+ const cliConfigPath = join(configDir, V2_CLI_CONFIG_FILENAME)
1008
+ let config = {}
1009
+ let raw = null
1010
+ if (existsSync(cliConfigPath)) {
1011
+ raw = readFileSync(cliConfigPath, 'utf8')
1012
+ try {
1013
+ config = JSON.parse(raw)
1014
+ } catch {
1015
+ warn(
1016
+ `Left ${cliConfigPath} untouched: it is not valid JSON, so the builtin Context ` +
1017
+ 'sidebar block stays enabled (it may render twice alongside the Pantheon block).',
1018
+ )
1019
+ return 'invalid'
1020
+ }
1021
+ }
1022
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) {
1023
+ warn(`Left ${cliConfigPath} untouched: expected a JSON object at the top level.`)
1024
+ return 'invalid'
1025
+ }
1026
+ if (config.plugins !== undefined && !Array.isArray(config.plugins)) {
1027
+ // Never replace a value we do not understand: the user may have written it
1028
+ // by hand in a shape a future host accepts.
1029
+ warn(`Left ${cliConfigPath} untouched: its "plugins" value is not an array.`)
1030
+ return 'invalid'
1031
+ }
1032
+
1033
+ // The host only honours the exact directive, so `next` never invents one.
1034
+ const verdict = capability ?? inspectContextBlockCapability(configDir, { dryRun })
1035
+ const next = verdict.ok
1036
+ ? withContextSidebarDisabled(config.plugins)
1037
+ : withContextSidebarEnabled(config.plugins)
1038
+ const removing = !verdict.ok && next.changed
1039
+
1040
+ if (!verdict.ok) {
1041
+ // A silent negation here is the bug this check exists for: the native
1042
+ // readout disappears and nothing replaces it.
1043
+ warn(
1044
+ `Builtin Context sidebar block left ENABLED: ${verdict.reason}. ` +
1045
+ (removing
1046
+ ? `Removed ${CONTEXT_SIDEBAR_NEGATION} from ${cliConfigPath} so the native block ` +
1047
+ 'keeps rendering. '
1048
+ : '') +
1049
+ 'Rebuild the TUI bundle (npm run build --prefix src/plugins/tui) and redeploy ' +
1050
+ 'pantheon-tui, then re-run init to de-duplicate the Context block.',
1051
+ )
1052
+ }
1053
+ if (!next.changed) return verdict.ok ? 'skipped' : 'unverified'
1054
+ config.plugins = next.plugins
1055
+
1056
+ const content = `${JSON.stringify(config, null, 2)}\n`
1057
+ const status = writeConfigWithBackup(cliConfigPath, content, dryRun, {
1058
+ expectedContent: raw,
1059
+ recorder,
1060
+ })
1061
+ if (status === 'conflict') {
1062
+ warn(
1063
+ `Left ${cliConfigPath} untouched: it changed on disk during the install. ` +
1064
+ 'Re-run init to disable the builtin Context sidebar block.',
1065
+ )
1066
+ return 'conflict'
1067
+ }
1068
+ if (status !== 'created') return 'skipped'
1069
+ return removing ? 'removed' : 'created'
1070
+ }
1071
+
577
1072
  /**
578
1073
  * Sync the Pantheon TUI plugin payload and V1 registration. V2 discovers the
579
1074
  * copied local-plugin entrypoints and does not use a project tui.json.
@@ -594,11 +1089,19 @@ export function tuiConfigLocations(target) {
594
1089
  * @param {object} [opts]
595
1090
  * @param {boolean} [opts.isGlobal=false] - flat global layout vs .opencode/
596
1091
  * @param {boolean} [opts.dryRun=false]
1092
+ * @param {(change: object) => void} [opts.recorder] - optional change recorder for preview
597
1093
  * @returns {'created'|'skipped'} status for the target registration
598
1094
  */
599
1095
  export function syncTuiRegistration(
600
1096
  target,
601
- { isGlobal = false, dryRun = false, version = 'v1' } = {},
1097
+ {
1098
+ isGlobal = false,
1099
+ dryRun = false,
1100
+ version = 'v1',
1101
+ recorder = null,
1102
+ reviewedRemovals = null,
1103
+ reviewedSnapshots = null,
1104
+ } = {},
602
1105
  ) {
603
1106
  const configDir = isGlobal ? target : join(target, '.opencode')
604
1107
  const targetTuiConfigPath = join(configDir, 'tui.json')
@@ -607,8 +1110,26 @@ export function syncTuiRegistration(
607
1110
  // plugins/pantheon-tui. This keeps the installed entry hermetic.
608
1111
  const tuiSrcDir = join(ROOT, 'src', 'plugins', 'tui')
609
1112
  const tuiCopyDir = resolveTuiCopyTarget(configDir)
610
- if (existsSync(tuiSrcDir)) {
611
- copyPluginFiles(tuiSrcDir, tuiCopyDir, { dryRun, version })
1113
+ // Fail closed: silently skipping the copy left `plugins` "installed" with no
1114
+ // payload — the host then loads a tui.json entry that points at nothing.
1115
+ if (!existsSync(tuiSrcDir)) {
1116
+ throw new Error(
1117
+ `Pantheon TUI plugin source not found: ${tuiSrcDir}. The package payload is ` +
1118
+ 'incomplete — reinstall pantheon-opencode (the published tarball must ship ' +
1119
+ 'src/plugins/tui), then re-run init.',
1120
+ )
1121
+ }
1122
+ const copyResult = copyPluginFiles(tuiSrcDir, tuiCopyDir, {
1123
+ dryRun,
1124
+ version,
1125
+ recorder,
1126
+ reviewedRemovals,
1127
+ reviewedSnapshots,
1128
+ })
1129
+ if (copyResult.errors > 0) {
1130
+ throw new Error(
1131
+ `${copyResult.problems[0] ?? `TUI plugin payload could not be copied to ${tuiCopyDir}.`}`,
1132
+ )
612
1133
  }
613
1134
 
614
1135
  // 2. Clean stale Pantheon TUI refs from every location OpenCode reads.
@@ -621,6 +1142,7 @@ export function syncTuiRegistration(
621
1142
  unregisterPlugin(tuiConfigPath, 'plugins/pantheon-tui', {
622
1143
  dryRun,
623
1144
  knownPantheonPaths: [ownedCopy, tuiCopyDir],
1145
+ recorder,
624
1146
  })
625
1147
  }
626
1148
 
@@ -630,7 +1152,7 @@ export function syncTuiRegistration(
630
1152
  if (version === 'v2') return 'skipped'
631
1153
 
632
1154
  // 3. Register the copied directory in the selected target only.
633
- return registerPlugin(targetTuiConfigPath, tuiCopyDir, { dryRun })
1155
+ return registerPlugin(targetTuiConfigPath, tuiCopyDir, { dryRun, recorder })
634
1156
  }
635
1157
 
636
1158
  /**
@@ -639,32 +1161,79 @@ export function syncTuiRegistration(
639
1161
  * MCP entries from the config (entries pointing at a missing venv would
640
1162
  * make every MCP fail to launch). `deps` is injectable for tests.
641
1163
  */
642
- export function setupRuntimePhase(target, { dryRun, clean, isGlobal }, stats, deps = {}) {
1164
+ export function setupRuntimePhase(
1165
+ target,
1166
+ {
1167
+ dryRun,
1168
+ clean,
1169
+ isGlobal,
1170
+ recorder = null,
1171
+ reviewedRemovals = null,
1172
+ reviewedSnapshots = null,
1173
+ onVenvDone = null,
1174
+ onHealthDone = null,
1175
+ },
1176
+ stats,
1177
+ deps = {},
1178
+ ) {
643
1179
  const S = strings()
644
1180
  const setup = deps.setupVenv ?? setupVenv
645
1181
  const check = deps.healthCheck ?? healthCheck
1182
+ let stopProgress
646
1183
  try {
647
- const venvSpinner = spinner(S.settingUpRuntime)
648
- setup(target, { dryRun, force: clean })
649
- venvSpinner(true)
1184
+ stopProgress = spinner(S.settingUpRuntime)
1185
+ try {
1186
+ setup(target, {
1187
+ dryRun,
1188
+ force: clean,
1189
+ recorder,
1190
+ reviewedRemovals,
1191
+ reviewedSnapshots,
1192
+ })
1193
+ } finally {
1194
+ // Count the phase even when setup throws: it DID run (and failed). The
1195
+ // failure is reported below as a warning, not as a missing phase.
1196
+ onVenvDone?.()
1197
+ }
1198
+ stopProgress(true)
1199
+ stopProgress = null
1200
+
1201
+ // A dry run creates no venv and installs no dependencies, so there is
1202
+ // nothing to verify yet. Running the health check here reported the
1203
+ // PRE-install target as broken and flipped runtimeHealthy=false, which
1204
+ // silently dropped every MCP entry from the previewed plan while the real
1205
+ // apply wrote them. Say what will happen instead of probing.
1206
+ if (dryRun) {
1207
+ info(S.runtimeVerifiedAfterApply)
1208
+ return true
1209
+ }
1210
+
650
1211
  const runtimeTarget = isGlobal ? target : join(target, '.opencode')
651
- const health = check(runtimeTarget, { dryRun, pythonTarget: target })
1212
+ let health
1213
+ try {
1214
+ health = check(runtimeTarget, { dryRun, pythonTarget: target })
1215
+ } finally {
1216
+ onHealthDone?.()
1217
+ }
652
1218
 
653
- section(`\uD83D\uDD0D ${S.healthSection}`)
654
- const healthStep = step(S.runningHealthChecks)
1219
+ section(S.healthSection)
1220
+ stopProgress = step(S.runningHealthChecks)
655
1221
  for (const p of health.passed) success(`${p.check}: ${p.detail}`)
656
1222
  for (const w of health.warnings) warning(`${w.check}: ${w.detail}`)
657
1223
  for (const f of health.failed) error(`${f.check}: ${f.detail}`)
658
1224
 
659
1225
  if (health.failed.length > 0) {
660
- healthStep(false)
1226
+ stopProgress(false)
1227
+ stopProgress = null
661
1228
  warning(`${health.failed.length} check(s) failed — review above`)
662
1229
  stats.warnings += health.failed.length
663
1230
  return false
664
1231
  }
665
- healthStep(true)
1232
+ stopProgress(true)
1233
+ stopProgress = null
666
1234
  return true
667
1235
  } catch (err) {
1236
+ stopProgress?.(false)
668
1237
  error(S.runtimeFailed(err.message))
669
1238
  warning(S.runtimeSkippedMcp)
670
1239
  stats.warnings += 1
@@ -683,10 +1252,13 @@ export function setupRuntimePhase(target, { dryRun, clean, isGlobal }, stats, de
683
1252
  * config in place — the migration that makes the rename non-breaking.
684
1253
  *
685
1254
  * @param {object} config - full config object (mutated in place)
686
- * @param {{ runtimeTarget: string, venvPython: string }} ctx
687
- * @returns {{ healed: number }} number of stale path strings rewritten
1255
+ * @param {{ runtimeTarget: string, venvPython: string, version?: 'v1' | 'v2' }} ctx
1256
+ * @returns {{ healed: number, warnings: string[], servers: string[] }} number of
1257
+ * stale path strings rewritten, one warning per MCP permission the host
1258
+ * cannot enforce, and the server names this call actually seeded (write
1259
+ * order) — the dry-run preview reports exactly these
688
1260
  */
689
- export function applyMcpServerEntries(config, { runtimeTarget, venvPython }) {
1261
+ export function applyMcpServerEntries(config, { runtimeTarget, venvPython, version = 'v2' }) {
690
1262
  config.mcp = config.mcp || {}
691
1263
  // MCP stays a flat named-server map for BOTH V1 and V2: OpenCode 1.18.x has
692
1264
  // no `mcp.servers` wrapper and rejects one with "Missing key
@@ -694,49 +1266,29 @@ export function applyMcpServerEntries(config, { runtimeTarget, venvPython }) {
694
1266
  // wrapper-shaped entries back to the flat map.
695
1267
  const healed = migrateMcpEntrypointPaths(config.mcp)
696
1268
 
697
- // Only add if not already configured by user
698
- if (!config.mcp['pantheon-resources']) {
699
- config.mcp['pantheon-resources'] = {
700
- type: 'local',
701
- cwd: runtimeTarget,
702
- command: [venvPython, 'scripts/mcp_resources.py'],
703
- enabled: true,
704
- }
705
- }
706
- if (!config.mcp['pantheon-code-mode']) {
707
- config.mcp['pantheon-code-mode'] = {
708
- type: 'local',
709
- cwd: runtimeTarget,
710
- command: [venvPython, 'scripts/code_mode.py'],
711
- enabled: true,
712
- }
713
- }
714
- if (!config.mcp['pantheon-memory']) {
715
- config.mcp['pantheon-memory'] = {
716
- type: 'local',
717
- cwd: runtimeTarget,
718
- command: [venvPython, 'scripts/memory_mcp.py'],
719
- enabled: true,
720
- }
721
- }
722
- if (!config.mcp['pantheon-persistence']) {
723
- config.mcp['pantheon-persistence'] = {
1269
+ // Only add if not already configured by user.
1270
+ const servers = []
1271
+ for (const entry of PANTHEON_MCP_SERVER_ENTRIES) {
1272
+ if (config.mcp[entry.name]) continue
1273
+ config.mcp[entry.name] = {
724
1274
  type: 'local',
725
1275
  cwd: runtimeTarget,
726
- command: [venvPython, 'scripts/mcp_persistence.py'],
727
- enabled: true,
728
- }
729
- }
730
- if (!config.mcp['pantheon-vision']) {
731
- config.mcp['pantheon-vision'] = {
732
- type: 'local',
733
- cwd: runtimeTarget,
734
- command: [venvPython, 'scripts/pantheon_vision.py'],
1276
+ command: [venvPython, entry.script],
735
1277
  enabled: true,
736
1278
  }
1279
+ servers.push(entry.name)
737
1280
  }
738
1281
 
739
- // Default MCP permissions
1282
+ // Default MCP permissions.
1283
+ //
1284
+ // WARNING: on OpenCode 2.x, `permission.mcp.<server>` is NOT enforced. The
1285
+ // host evaluates an MCP call as the action `<server>_<tool>` with resources
1286
+ // ["*"]; `permission.mcp.<server>` and `action:"mcp"` are inert (measured on
1287
+ // 2.0.29–2.1.3). These defaults are kept for V1 compatibility, but `ask` does
1288
+ // not prompt and `allow` grants nothing it did not already have — every `ask`
1289
+ // server below is reported to the user as unenforced. The enforceable form is
1290
+ // `{ action: "<server>_*", resource: "*", effect: "deny" }`; `ask` there
1291
+ // HIDES the tool instead of asking, so it is never emitted as a default.
740
1292
  config.permission = config.permission || {}
741
1293
  config.permission.mcp = config.permission.mcp || {}
742
1294
  if (!config.permission.mcp['pantheon-resources']) {
@@ -755,25 +1307,168 @@ export function applyMcpServerEntries(config, { runtimeTarget, venvPython }) {
755
1307
  config.permission.mcp['pantheon-vision'] = 'ask'
756
1308
  }
757
1309
 
758
- return { healed }
1310
+ // Report every `ask` entry, whether just seeded or left by a previous
1311
+ // install: the config claims a gate the host does not apply. V1's MCP
1312
+ // permission semantics were not measured, so the warning is V2-only.
1313
+ const S = strings()
1314
+ const warnings =
1315
+ version === 'v2'
1316
+ ? Object.entries(config.permission.mcp)
1317
+ .filter(([, effect]) => effect === 'ask')
1318
+ .map(([server]) => S.mcpAskNotEnforceable(server))
1319
+ : []
1320
+
1321
+ return { healed, warnings, servers }
1322
+ }
1323
+
1324
+ /**
1325
+ * Phase 4 drift detection: the planned targets whose on-disk state changed
1326
+ * between the plan pass (snapshots) and the apply pass. A path counts as drifted
1327
+ * when its existence, content hash, size, or mode differs — which includes a
1328
+ * planned-NEW path that now exists. Returns the absolute paths (empty = no
1329
+ * drift); callers print only these paths, never contents or hashes.
1330
+ */
1331
+ function detectSnapshotDrift(snapshots) {
1332
+ if (!Array.isArray(snapshots)) return []
1333
+ const changed = []
1334
+ for (const before of snapshots) {
1335
+ const now = snapshot(before.path)
1336
+ if (
1337
+ now.exists !== before.exists ||
1338
+ now.sha256 !== before.sha256 ||
1339
+ now.size !== before.size ||
1340
+ now.mode !== before.mode
1341
+ ) {
1342
+ changed.push(before.path)
1343
+ }
1344
+ }
1345
+ return changed
759
1346
  }
760
1347
 
1348
+ /**
1349
+ * Phase 5 failure semantics. `installPass` is the whole installer; this thin
1350
+ * wrapper reports a mid-apply failure HONESTLY: it aborts the remaining writes
1351
+ * (the throw), relies on each writer to clean up only its own temporary file,
1352
+ * reports the PATHS already applied (never contents), prints the recovery
1353
+ * path, and re-throws so the CLI exits non-zero. There is NO automatic rollback — the
1354
+ * exact backup set + `pantheon-opencode restore` is the recovery.
1355
+ *
1356
+ * Progress is tracked in `_lastRun` (set only by a non-dry pass, so the nested
1357
+ * dry plan pass never clobbers it). The RESOLVED target is read back from
1358
+ * `_lastRun.target` so the report and the sweep work when the caller passed
1359
+ * `undefined` (the default global install resolves to `~/.config/opencode`).
1360
+ */
1361
+ let _lastRun = null
1362
+ // The gauge of the install currently running (never the nested plan pass), so
1363
+ // an exception can close it with `✖ reason` instead of leaving a half line.
1364
+ let _activeGauge = null
1365
+
761
1366
  export async function installOpenCode(
762
1367
  target,
763
1368
  dryRun = false,
764
1369
  clean = false,
765
1370
  components = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime'],
766
1371
  opts = {},
1372
+ ) {
1373
+ // Reset per-call so a stale run can never leak into a fresh failure report.
1374
+ if (!dryRun) _lastRun = null
1375
+ // The installer is a PROGRESS surface: the gauge replaces per-step logs
1376
+ // unless --verbose asks for them back. Doctor and the other CLIs never set
1377
+ // verbose, so their output is untouched; restore it on the way out.
1378
+ const previousUi = configure({ verbose: opts.verbose === true })
1379
+ try {
1380
+ return await installPass(target, dryRun, clean, components, opts)
1381
+ } catch (err) {
1382
+ _activeGauge?.fail(err instanceof Error ? err.message : String(err))
1383
+ const run = dryRun ? null : _lastRun
1384
+ if (run) {
1385
+ const S = strings()
1386
+ const paths = summarizeChanges(run.entries ?? [])
1387
+ .files.filter((f) => f.action !== ACTIONS.UNCHANGED && f.action !== ACTIONS.CONFLICT)
1388
+ .map((f) => displayPath(run.target, f.path))
1389
+ error(S.applyFailed(err instanceof Error ? err.message : String(err)))
1390
+ if (paths.length > 0) {
1391
+ warning(S.alreadyApplied)
1392
+ for (const p of paths) warning(` ${p}`)
1393
+ }
1394
+ warning(run.backupDir ? S.restoreRecoveryHint(run.backupDir) : S.restoreNoBackup)
1395
+ }
1396
+ throw err
1397
+ } finally {
1398
+ // An early return (canceled/declined preview) leaves the gauge mid-line on
1399
+ // a TTY; clear it without claiming completion. `done()`/`fail()` already
1400
+ // set `finished`, so this is a no-op on every normal path.
1401
+ if (_activeGauge && !_activeGauge.finished) _activeGauge.cancel()
1402
+ _activeGauge = null
1403
+ configure(previousUi)
1404
+ }
1405
+ }
1406
+
1407
+ async function installPass(
1408
+ target,
1409
+ dryRun = false,
1410
+ clean = false,
1411
+ components = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime'],
1412
+ opts = {},
767
1413
  ) {
768
1414
  // Default target if not provided (global ~/.config/opencode)
769
1415
  if (!target) {
770
1416
  target = join(homedir(), '.config', 'opencode')
771
1417
  }
772
1418
 
773
- const componentSet = new Set(components)
1419
+ const componentSet = new Set(
1420
+ opts.noMcp ? components.filter((component) => component !== 'runtime') : components,
1421
+ )
774
1422
  const stats = summary.opencode
1423
+ // Per-call baseline. `stats` is the module-level cumulative summary, so the
1424
+ // consistency guard must compare against THIS call's delta, not the total.
1425
+ const statsBefore = { created: stats.created, skipped: stats.skipped }
1426
+ // Number of planned changes, filled by a dry plan pass (used by the gate).
1427
+ let plannedChanges = 0
1428
+ let planFiles = []
1429
+ let planTotals = null
1430
+ let removalPaths = []
1431
+ // MCP servers this pass seeds into opencode.json, in write order. Filled by
1432
+ // applyMcpServerEntries so the preview names exactly what the apply writes.
1433
+ let mcpServers = []
1434
+ const planTimestamp = opts.planTimestamp ?? new Date().toISOString()
1435
+ let projectedState = null
1436
+ // Phase 4: planned-target snapshots from the plan pass, used for drift checks.
1437
+ let plannedSnapshots = null
1438
+ let reviewedRemovals = null
1439
+ let reviewedSnapshots = null
775
1440
  const S = strings()
776
1441
 
1442
+ // Configure the UI channel BEFORE any output: the version resolver below
1443
+ // warns when a dry run skips the host probe, and a quiet preview (doctor's
1444
+ // internal preflight, --json) must not print it. Quiet used to be applied
1445
+ // much later, so that one warning escaped every silent preview.
1446
+ configure({ dryRun, quiet: opts.quiet === true })
1447
+
1448
+ // Beta 11 (Setup phase 1): a dry pass records every writer's intended change
1449
+ // so we can print the REAL per-file plan without writing anything. A recorder
1450
+ // ALWAYS runs now: a dry pass builds the preview/plan from it, and an apply
1451
+ // pass uses it to report which PATHS were already written if a writer throws
1452
+ // (Phase 5 failure semantics). The default is the module-level no-op recorder,
1453
+ // so an uninstrumented caller stays byte-identical.
1454
+ const ownRecorder = opts.recorder ? null : createRecorder()
1455
+ const preview = dryRun && ownRecorder ? ownRecorder : null
1456
+ let recorder = opts.recorder ?? ownRecorder.recorder
1457
+ // Test-only failure seam: throw after N recorded writes so the failure path is
1458
+ // deterministic. Never reachable from production callers (opts.deps is not a
1459
+ // CLI flag) and never applied to the internal dry plan pass.
1460
+ if (!dryRun && typeof opts.deps?.failAfter === 'number') {
1461
+ const base = recorder
1462
+ const limit = opts.deps.failAfter
1463
+ let applied = 0
1464
+ recorder = (change) => {
1465
+ base(change)
1466
+ if (++applied >= limit) throw new Error('injected failure (test-only failAfter seam)')
1467
+ }
1468
+ }
1469
+ // Track this apply so the wrapper can report the paths written on a failure.
1470
+ if (!dryRun) _lastRun = { target, entries: ownRecorder?.entries ?? [], backupDir: null }
1471
+
777
1472
  // V1/V2 dual-version awareness (Phase 3): the installer builds a unified
778
1473
  // config, then applies V2-native migration (migrateV1toV2) when
779
1474
  // --opencode-version=v2. V2 normalizes V1 fields in memory (no rewrite) and
@@ -784,9 +1479,32 @@ export async function installOpenCode(
784
1479
  // the V1 branch writes .ts file paths that a 2.x host drops from the config.
785
1480
  // `opts` is forwarded as the resolver's options bag so a caller (and CI) can
786
1481
  // pin env/probe instead of spawning a real host binary.
787
- const version = resolveOpenCodeVersion(opts.version ?? 'auto', opts)
1482
+ //
1483
+ // A DRY RUN probes the host too. It used to pass `skipProbe` and assume V1,
1484
+ // so `init --dry-run` on a 2.x host previewed the V1 plan (target `tui.json`,
1485
+ // removed `index.ts`) while the apply wrote `index.ts` and no `tui.json` —
1486
+ // a preview that contradicted the apply. The probe runs in a throwaway state
1487
+ // directory, and the dry run bounds it with the shorter
1488
+ // DRY_RUN_PROBE_TIMEOUT_MS so a hanging host cannot stall a preview. When the
1489
+ // probe still fails, V1 is assumed and `versionAssumed` marks the plan as
1490
+ // such (text + --json).
1491
+ let versionFallback = null
1492
+ const version = resolveOpenCodeVersion(opts.version ?? 'auto', {
1493
+ ...opts,
1494
+ probeTimeoutMs: dryRun ? DRY_RUN_PROBE_TIMEOUT_MS : undefined,
1495
+ onFallback: (reason) => {
1496
+ versionFallback = reason
1497
+ },
1498
+ })
1499
+ if (version === 'v2' && opts.preset) {
1500
+ throw new Error(
1501
+ '--preset is not supported for OpenCode V2 because V2 ignores the legacy active-preset marker. ' +
1502
+ 'Configure models using V2-native OpenCode configuration instead.',
1503
+ )
1504
+ }
1505
+ const versionAssumed = dryRun && versionFallback !== null
788
1506
  if (version === 'v2') {
789
- info(
1507
+ notice(
790
1508
  'OpenCode V2 target — shared config; state isolated via OPENCODE_DB ' +
791
1509
  '(~/.local/share/opencode/opencode-v2.db), service port 49375',
792
1510
  )
@@ -801,7 +1519,7 @@ export async function installOpenCode(
801
1519
  // built from (src/pantheon/v2-unsupported.mjs), so this notice cannot drift
802
1520
  // from what the plugin reports. Advisory: a V2 install is a supported
803
1521
  // configuration, not a failure.
804
- info(
1522
+ notice(
805
1523
  `V2 plugin generation — reduced surface. Unsupported features: ${listV2UnsupportedFeatures().join(', ')}`,
806
1524
  )
807
1525
  }
@@ -815,18 +1533,35 @@ export async function installOpenCode(
815
1533
 
816
1534
  if (interactive && !dryRun) {
817
1535
  const { runInteractiveInstall } = await import('./interactive.mjs')
1536
+ const hasRequestedComponents = Array.isArray(opts.requestedComponents)
1537
+ const promptComponents = hasRequestedComponents ? opts.requestedComponents : components
1538
+ const promptDefaults = hasRequestedComponents
1539
+ ? []
1540
+ : opts.noMcp
1541
+ ? COMPONENT_NAMES.filter((component) => component !== 'runtime')
1542
+ : COMPONENT_NAMES
818
1543
  const result = await runInteractiveInstall({
819
- components,
820
- defaultComponents: COMPONENT_NAMES,
1544
+ components: promptComponents,
1545
+ defaultComponents: promptDefaults,
1546
+ noMcp: opts.noMcp === true,
1547
+ prompts: opts.deps?.prompts,
1548
+ isTTY: opts.deps?.isTTY,
821
1549
  })
822
1550
 
823
- if (!result.confirmed && !autoYes) {
824
- info('Installation canceled.')
825
- return stats
1551
+ if (result.canceled) {
1552
+ notice('Installation canceled.')
1553
+ return { ...stats, applied: false, reason: 'canceled' }
1554
+ }
1555
+
1556
+ if (!result.confirmed) {
1557
+ notice('Installation canceled.')
1558
+ return { ...stats, applied: false, reason: 'canceled' }
826
1559
  }
827
1560
 
828
1561
  // Map target selection to actual path
829
- const newComponents = [...result.components]
1562
+ const newComponents = [...result.components].filter(
1563
+ (component) => !opts.noMcp || component !== 'runtime',
1564
+ )
830
1565
  componentSet.clear()
831
1566
  for (const c of newComponents) componentSet.add(c)
832
1567
 
@@ -869,11 +1604,201 @@ export async function installOpenCode(
869
1604
  // active config directory is the project root and its agent loader scans
870
1605
  // <config-dir>/{agent,agents}/**, so V2 project agents must be at ./agents.
871
1606
  // Global installs are flat for both versions.
872
- const isGlobal = isGlobalConfigDir(target)
1607
+ const isGlobal = opts.global ?? isGlobalConfigDir(target)
873
1608
  const _subDir = isGlobal ? '' : '.opencode'
874
1609
  const agentPrefix = isGlobal || version === 'v2' ? 'agents' : '.opencode/agents'
875
1610
 
876
- configure({ dryRun })
1611
+ // -----------------------------------------------------------------------
1612
+ // Plan pass + apply gate + drift check (Beta 11 Setup phases 3-4).
1613
+ // * the plan pass (a dry run — writes nothing) prints the plan and
1614
+ // snapshots every planned target;
1615
+ // * applying requires explicit authorization (Phase 3): a declined or
1616
+ // unauthorized run writes NOTHING;
1617
+ // * drift (Phase 4) aborts BEFORE any write if a planned target changed
1618
+ // between the plan pass and now.
1619
+ // A result with `applied: false` means the caller must not print success.
1620
+ // -----------------------------------------------------------------------
1621
+ const applyRequested = !dryRun
1622
+ if (applyRequested) {
1623
+ const savedStats = { ...stats }
1624
+ let planned
1625
+ try {
1626
+ // Use the LIVE selection: the wizard above may have changed componentSet.
1627
+ // An AUTHORIZED apply (`--yes`) is not a preview: compute the plan +
1628
+ // snapshots but stay silent. The gate path (no `--yes`) still prints the
1629
+ // plan for the review / decline preview.
1630
+ planned = await installOpenCode(target, true, clean, [...componentSet], {
1631
+ ...opts,
1632
+ // Hand the RESOLVED generation to the plan pass. Re-resolving would
1633
+ // probe the host a second time and could land on a different answer
1634
+ // (a transient probe failure), making the plan disagree with the
1635
+ // apply it is about to authorize.
1636
+ version,
1637
+ planTimestamp,
1638
+ planOnly: true,
1639
+ quiet: autoYes,
1640
+ quietPlan: autoYes,
1641
+ })
1642
+ } finally {
1643
+ Object.assign(stats, savedStats)
1644
+ // The plan pass left the UI in dry-run mode; restore this run's mode.
1645
+ configure({ dryRun, quiet: opts.quiet === true })
1646
+ }
1647
+ plannedSnapshots = planned?.snapshots ?? null
1648
+
1649
+ if (opts.expectedPlan) {
1650
+ const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
1651
+ const drift = findPlanDrift(opts.expectedPlan, {
1652
+ target,
1653
+ packageRoot: ROOT,
1654
+ packageVersion,
1655
+ files: planned?.files ?? [],
1656
+ snapshots: planned?.snapshots ?? [],
1657
+ })
1658
+ if (drift.length > 0) {
1659
+ warning('Reviewed install plan drifted; no files were written.')
1660
+ for (const item of drift) warning(` ${item}`)
1661
+ return { ...stats, applied: false, reason: 'drift', drift }
1662
+ }
1663
+ }
1664
+
1665
+ if (!autoYes) {
1666
+ const injected = opts.deps?.promptReview
1667
+ const canPrompt = typeof injected === 'function' || interactive
1668
+ if (canPrompt) {
1669
+ const { promptReview } = await import('./interactive.mjs')
1670
+ const ask = typeof injected === 'function' ? injected : promptReview
1671
+ const accepted = await ask(`Apply these ${planned?.planned ?? 0} changes?`, {
1672
+ default: false,
1673
+ prompts: opts.deps?.prompts,
1674
+ isTTY: opts.deps?.isTTY,
1675
+ })
1676
+ if (accepted === PROMPT_CANCELED) {
1677
+ notice(S.nothingApplied)
1678
+ return { ...stats, applied: false, reason: 'canceled' }
1679
+ }
1680
+ if (!accepted) {
1681
+ notice(S.nothingApplied)
1682
+ return { ...stats, applied: false, reason: 'declined' }
1683
+ }
1684
+ } else {
1685
+ notice(S.planOnlyNoYes)
1686
+ return { ...stats, applied: false, reason: 'not-authorized' }
1687
+ }
1688
+ }
1689
+
1690
+ // Test seam: mutate a target between the plan/authorization and the drift
1691
+ // check. Absent in production callers.
1692
+ if (typeof opts.deps?.betweenPlanAndApply === 'function') opts.deps.betweenPlanAndApply()
1693
+
1694
+ const drifted = detectSnapshotDrift(plannedSnapshots)
1695
+ if (drifted.length > 0) {
1696
+ warning(S.driftHeader)
1697
+ for (const p of drifted) warning(` ${displayPath(target, p)}`)
1698
+ warning(S.driftAbort)
1699
+ return {
1700
+ ...stats,
1701
+ applied: false,
1702
+ reason: 'drift',
1703
+ drift: drifted.map((p) => displayPath(target, p)),
1704
+ }
1705
+ }
1706
+ reviewedRemovals = new Set((planned?.removals ?? []).map((filePath) => resolve(filePath)))
1707
+ reviewedSnapshots = new Map(
1708
+ (plannedSnapshots ?? []).map((before) => [resolve(before.path), before]),
1709
+ )
1710
+ }
1711
+
1712
+ // -----------------------------------------------------------------------
1713
+ // Progress gauge: the user sees progress, not a log. The phase list is
1714
+ // derived from the FINAL component selection, so total == work performed.
1715
+ // `--verbose` keeps the old step-by-step output and draws no gauge; the
1716
+ // internal plan pass (`planOnly`) never owns the terminal.
1717
+ // -----------------------------------------------------------------------
1718
+ const phases = planInstallPhases({ components: componentSet, dryRun })
1719
+ let phaseCursor = 0
1720
+ const progress =
1721
+ opts.planOnly || opts.verbose === true ? null : createGauge({ total: phases.length })
1722
+ if (progress) _activeGauge = progress
1723
+ const advancePhase = (label) => {
1724
+ const phase = label ?? phases[phaseCursor]
1725
+ // Defensive: a phase that the code path skipped must not reprint the last
1726
+ // label at the clamped counter.
1727
+ if (phase === undefined) return
1728
+ phaseCursor += 1
1729
+ progress?.advance(1, phase)
1730
+ }
1731
+ // Prerequisites already ran above (apply + runtime only); account for it.
1732
+ if (phases[0] === S.checkingPrerequisites) advancePhase()
1733
+
1734
+ // -----------------------------------------------------------------------
1735
+ // 0. Exact backup (Beta 11 Setup phase 2): preserve the CURRENT state of
1736
+ // every regular file this run can modify/remove INSIDE the config dir,
1737
+ // byte-for-byte, BEFORE the first modifying write. Bulk directories and
1738
+ // out-of-target global files are recorded in the manifest as
1739
+ // `notRevertible`. A dry run records the planned backup-manifest path only.
1740
+ // -----------------------------------------------------------------------
1741
+ if (componentSet.has('agents')) {
1742
+ const agentTarget = join(target, agentPrefix)
1743
+ assertPathWithin(target, agentTarget)
1744
+ assertNoSymlinkAncestors(agentTarget)
1745
+ }
1746
+ if (componentSet.has('skills')) {
1747
+ const skillsTarget = isGlobal ? join(target, 'skills') : join(target, '.opencode', 'skills')
1748
+ assertPathWithin(target, skillsTarget)
1749
+ assertNoSymlinkAncestors(skillsTarget)
1750
+ }
1751
+ const backupPlan = collectInstallBackupEntries(target, componentSet, version, isGlobal)
1752
+ const pkgVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
1753
+ if (dryRun) {
1754
+ const preview = previewBackupSet({
1755
+ configDir: target,
1756
+ entries: backupPlan.entries,
1757
+ notRevertible: backupPlan.notRevertible,
1758
+ packageVersion: pkgVersion,
1759
+ clock: () => new Date(planTimestamp),
1760
+ })
1761
+ if (isRecording(recorder)) {
1762
+ for (const file of preview.files) {
1763
+ recordChange(
1764
+ {
1765
+ path: file.path,
1766
+ action: ACTIONS.CREATE,
1767
+ bytes: file.bytes,
1768
+ outputFingerprint: file.outputFingerprint,
1769
+ scored: false,
1770
+ },
1771
+ recorder,
1772
+ )
1773
+ }
1774
+ recordChange(
1775
+ {
1776
+ path: preview.manifestPath,
1777
+ action: ACTIONS.CREATE,
1778
+ bytes: preview.manifestBytes,
1779
+ outputFingerprint: preview.manifestFingerprint,
1780
+ scored: false,
1781
+ },
1782
+ recorder,
1783
+ )
1784
+ }
1785
+ } else {
1786
+ const backupStep = step(S.creatingBackup)
1787
+ const { dir: backupDir } = createBackupSet({
1788
+ configDir: target,
1789
+ entries: backupPlan.entries,
1790
+ notRevertible: backupPlan.notRevertible,
1791
+ packageVersion: pkgVersion,
1792
+ clock: () => new Date(planTimestamp),
1793
+ })
1794
+ backupStep(true)
1795
+ if (_lastRun && _lastRun.target === target) _lastRun.backupDir = backupDir
1796
+ // Secret-safe: the path only. The exact wording is fixed (once per apply).
1797
+ // Close the gauge line first: this notice must never be appended to it.
1798
+ endGaugeLine()
1799
+ console.warn(backupWarning(backupDir))
1800
+ }
1801
+ advancePhase()
877
1802
 
878
1803
  if (isGlobal) {
879
1804
  info(S.globalLayout)
@@ -883,7 +1808,7 @@ export async function installOpenCode(
883
1808
  // 1. Install agents (--components agents)
884
1809
  // -----------------------------------------------------------------------
885
1810
  if (componentSet.has('agents')) {
886
- section('\uD83D\uDCE6 Agents')
1811
+ section('Agents')
887
1812
  const srcDir = join(ROOT, 'src', 'agents')
888
1813
  if (!sourceDirValid(srcDir)) {
889
1814
  warning(`Agent source directory not found: ${srcDir}`)
@@ -891,14 +1816,26 @@ export async function installOpenCode(
891
1816
  } else {
892
1817
  const agentStep = step(S.installingAgents)
893
1818
  const dstDir = join(target, agentPrefix)
894
- if (!dryRun) mkdirSync(dstDir, { recursive: true })
895
- if (clean && existsSync(dstDir) && !dryRun) {
1819
+ assertPathWithin(target, dstDir)
1820
+ assertNoSymlinkAncestors(dstDir)
1821
+ if (!dryRun) {
1822
+ mkdirSync(dstDir, { recursive: true })
1823
+ assertNoSymlinkAncestors(dstDir)
1824
+ }
1825
+ if (clean && existsSync(dstDir)) {
1826
+ assertNoSymlinkAncestors(dstDir)
896
1827
  const existing = readdirSync(dstDir)
897
1828
  for (const f of existing) {
898
- rmSync(join(dstDir, f), { recursive: true, force: true })
1829
+ const agentPath = join(dstDir, f)
1830
+ assertSafeRemoval(dstDir, agentPath)
1831
+ if (dryRun) {
1832
+ recordRemovalTree(agentPath, recorder)
1833
+ } else {
1834
+ removeReviewedTree(agentPath, reviewedRemovals, reviewedSnapshots)
1835
+ }
899
1836
  }
900
1837
  }
901
- const { created, skipped } = copyAgentPrompts(srcDir, dstDir, dryRun)
1838
+ const { created, skipped } = copyAgentPrompts(srcDir, dstDir, dryRun, false, recorder)
902
1839
  stats.created += created
903
1840
  stats.skipped += skipped
904
1841
  agentStep(true)
@@ -912,25 +1849,37 @@ export async function installOpenCode(
912
1849
  const srcRouting = join(ROOT, 'src', 'routing.yml')
913
1850
  const dstRouting = join(target, 'routing.yml')
914
1851
  if (existsSync(srcRouting)) {
915
- const routingStatus = writeIfChanged(dstRouting, readFileSync(srcRouting, 'utf8'), dryRun)
1852
+ const routingStatus = writeIfChanged(dstRouting, readFileSync(srcRouting, 'utf8'), dryRun, {
1853
+ recorder,
1854
+ })
916
1855
  if (routingStatus === 'created') stats.created++
917
1856
  else stats.skipped++
918
1857
  }
919
1858
  }
1859
+ if (componentSet.has('agents')) advancePhase()
920
1860
 
921
1861
  // -----------------------------------------------------------------------
922
1862
  // 2. Install skills (--components skills)
923
1863
  // -----------------------------------------------------------------------
924
1864
  if (componentSet.has('skills')) {
925
- section('\uD83D\uDCDA Skills')
1865
+ section('Skills')
926
1866
  const skillNames = collectSkillNames()
927
1867
  if (skillNames.length > 0) {
928
1868
  const skillStep = step(`Installing ${skillNames.length} skills`)
929
1869
  const dstSkillsDir = isGlobal ? join(target, 'skills') : join(target, '.opencode', 'skills')
930
- if (clean && existsSync(dstSkillsDir) && !dryRun) {
1870
+ assertPathWithin(target, dstSkillsDir)
1871
+ assertNoSymlinkAncestors(dstSkillsDir)
1872
+ if (clean && existsSync(dstSkillsDir)) {
1873
+ assertNoSymlinkAncestors(dstSkillsDir)
931
1874
  const existing = readdirSync(dstSkillsDir)
932
1875
  for (const s of existing) {
933
- rmSync(join(dstSkillsDir, s), { recursive: true, force: true })
1876
+ const skillPath = join(dstSkillsDir, s)
1877
+ assertSafeRemoval(dstSkillsDir, skillPath)
1878
+ if (dryRun) {
1879
+ recordRemovalTree(skillPath, recorder)
1880
+ } else {
1881
+ removeReviewedTree(skillPath, reviewedRemovals, reviewedSnapshots)
1882
+ }
934
1883
  }
935
1884
  }
936
1885
  const installSubDir = isGlobal ? '' : '.opencode'
@@ -939,32 +1888,46 @@ export async function installOpenCode(
939
1888
  target,
940
1889
  dryRun,
941
1890
  installSubDir,
1891
+ recorder,
1892
+ reviewedRemovals,
1893
+ reviewedSnapshots,
1894
+ clean,
942
1895
  )
943
1896
  stats.created += sCreated
944
1897
  stats.skipped += sSkipped
945
1898
  skillStep(true)
946
1899
  }
947
1900
  }
1901
+ if (componentSet.has('skills')) advancePhase()
948
1902
 
949
1903
  // -----------------------------------------------------------------------
950
1904
  // 2.5 Install shared instructions: AGENTS.md (--components instructions)
951
1905
  // -----------------------------------------------------------------------
952
- // AGENTS.md is the single instruction file both V1 and V2 load; the
953
- // generated file embeds shared instructions; agent-scoped instructions are
954
- // already rendered into supported agent prompt markdown during copy. The
955
- // individual source fragments are NOT copied (nothing references
956
- // <config>/instructions/ after the section-D merge fix — copying them would
957
- // just leave stale duplicates on disk).
1906
+ // Both AGENTS.md artifacts are managed regions (scripts/build-agents-md.mjs).
1907
+ // A GLOBAL config dir receives the repo-agnostic global artifact (agent
1908
+ // table + shared rules); a PROJECT layout keeps the repository artifact.
1909
+ // writeAgentsMdManaged is conservative: content outside the managed region
1910
+ // is never deleted, and a legacy fully-generated file upgrades in place.
958
1911
  if (componentSet.has('instructions')) {
959
- section('\uD83D\uDCCB Instructions')
960
- // AGENTS.md
961
- const srcAgentsMd = join(ROOT, 'AGENTS.md')
1912
+ section('Instructions')
1913
+ const srcAgentsMd = isGlobal ? join(ROOT, 'AGENTS.global.md') : join(ROOT, 'AGENTS.md')
962
1914
  const dstAgentsMd = join(target, 'AGENTS.md')
963
1915
  if (existsSync(srcAgentsMd)) {
964
1916
  const content = readFileSync(srcAgentsMd, 'utf8')
965
- const status = writeIfChanged(dstAgentsMd, content, dryRun)
966
- if (status === 'created') stats.created++
967
- else stats.skipped++
1917
+ const status = writeAgentsMdManaged(dstAgentsMd, content, dryRun, recorder)
1918
+ if (status === 'skipped') stats.skipped++
1919
+ else {
1920
+ stats.created++
1921
+ if (status === 'merged') {
1922
+ warning(
1923
+ `AGENTS.md had non-generated content — it was preserved around the ` +
1924
+ `Pantheon managed region in ${dstAgentsMd}. Review and merge manually.`,
1925
+ )
1926
+ }
1927
+ }
1928
+ } else {
1929
+ warning(`AGENTS.md artifact not found in the package: ${srcAgentsMd}`)
1930
+ stats.errors++
968
1931
  }
969
1932
  // An instruction-only upgrade must also refresh selective guidance on
970
1933
  // already-installed Pantheon agents, but must not create agents the user
@@ -973,32 +1936,43 @@ export async function installOpenCode(
973
1936
  const installedAgents = join(target, agentPrefix)
974
1937
  const sourceAgents = join(ROOT, 'src', 'agents')
975
1938
  if (existsSync(installedAgents) && existsSync(sourceAgents)) {
976
- const refreshed = copyAgentPrompts(sourceAgents, installedAgents, dryRun, true)
1939
+ const refreshed = copyAgentPrompts(sourceAgents, installedAgents, dryRun, true, recorder)
977
1940
  stats.created += refreshed.created
978
1941
  stats.skipped += refreshed.skipped
979
1942
  }
980
1943
  }
981
1944
  }
1945
+ if (componentSet.has('instructions')) advancePhase()
982
1946
 
983
1947
  // -----------------------------------------------------------------------
984
1948
  // 2.6 Install prompts (--components prompts)
985
1949
  // -----------------------------------------------------------------------
986
1950
  if (componentSet.has('prompts')) {
987
- section('\uD83D\uDCAC Prompts')
1951
+ section('Prompts')
988
1952
  const srcPrompts = join(ROOT, 'prompts')
989
1953
  const dstPrompts = join(target, 'prompts')
990
1954
  if (existsSync(srcPrompts)) {
991
- const promptsResult = syncDir(srcPrompts, dstPrompts, dryRun, clean)
1955
+ const promptsResult = syncDir(
1956
+ srcPrompts,
1957
+ dstPrompts,
1958
+ dryRun,
1959
+ clean,
1960
+ null,
1961
+ recorder,
1962
+ reviewedRemovals,
1963
+ reviewedSnapshots,
1964
+ )
992
1965
  stats.created += promptsResult.created
993
1966
  stats.skipped += promptsResult.skipped
994
1967
  }
995
1968
  }
1969
+ if (componentSet.has('prompts')) advancePhase()
996
1970
 
997
1971
  // -----------------------------------------------------------------------
998
1972
  // 2.7 Install commands (--components commands)
999
1973
  // -----------------------------------------------------------------------
1000
1974
  if (componentSet.has('commands')) {
1001
- section('\u26A1 Commands')
1975
+ section('Commands')
1002
1976
  const srcCmds = join(ROOT, 'commands')
1003
1977
  // V2 project sandboxes use OPENCODE_CONFIG_DIR=<project root>, so OpenCode
1004
1978
  // discovers custom commands from <target>/commands. V1 project installs
@@ -1006,11 +1980,21 @@ export async function installOpenCode(
1006
1980
  const commandDir = isGlobal || version === 'v2' ? 'commands' : '.opencode/commands'
1007
1981
  const dstCmds = join(target, commandDir)
1008
1982
  if (existsSync(srcCmds)) {
1009
- const cmdResult = syncDir(srcCmds, dstCmds, dryRun, clean, (f) => f.endsWith('.md'))
1983
+ const cmdResult = syncDir(
1984
+ srcCmds,
1985
+ dstCmds,
1986
+ dryRun,
1987
+ clean,
1988
+ (f) => f.endsWith('.md'),
1989
+ recorder,
1990
+ reviewedRemovals,
1991
+ reviewedSnapshots,
1992
+ )
1010
1993
  stats.created += cmdResult.created
1011
1994
  stats.skipped += cmdResult.skipped
1012
1995
  }
1013
1996
  }
1997
+ if (componentSet.has('commands')) advancePhase()
1014
1998
 
1015
1999
  // -----------------------------------------------------------------------
1016
2000
  // -----------------------------------------------------------------------
@@ -1024,15 +2008,23 @@ export async function installOpenCode(
1024
2008
  // 2.8 Install TUI plugins (--components plugins)
1025
2009
  // -----------------------------------------------------------------------
1026
2010
  if (componentSet.has('plugins')) {
1027
- section('\uD83D\uDD0C Plugins')
2011
+ section('Plugins')
1028
2012
  const srcPluginDir = join(ROOT, 'src', 'plugins', 'tui')
1029
2013
  const dstPluginDir = isGlobal
1030
2014
  ? join(target, 'plugins', 'pantheon-tui')
1031
2015
  : join(target, '.opencode', 'plugins', 'pantheon-tui')
1032
- const pluginStats = installPlugin(srcPluginDir, dstPluginDir, { dryRun, clean, version })
2016
+ const pluginStats = installPlugin(srcPluginDir, dstPluginDir, {
2017
+ dryRun,
2018
+ clean,
2019
+ version,
2020
+ recorder,
2021
+ reviewedRemovals,
2022
+ reviewedSnapshots,
2023
+ })
1033
2024
  stats.created += pluginStats.created
1034
2025
  stats.skipped += pluginStats.skipped
1035
2026
  stats.errors += pluginStats.errors
2027
+ for (const problem of pluginStats.problems ?? []) error(problem)
1036
2028
  }
1037
2029
 
1038
2030
  // -----------------------------------------------------------------------
@@ -1041,7 +2033,14 @@ export async function installOpenCode(
1041
2033
  if (componentSet.has('plugins')) {
1042
2034
  let tuiStatus
1043
2035
  try {
1044
- tuiStatus = syncTuiRegistration(target, { isGlobal, dryRun, version })
2036
+ tuiStatus = syncTuiRegistration(target, {
2037
+ isGlobal,
2038
+ dryRun,
2039
+ version,
2040
+ recorder,
2041
+ reviewedRemovals,
2042
+ reviewedSnapshots,
2043
+ })
1045
2044
  } catch (cause) {
1046
2045
  error(`TUI plugin setup failed: ${cause.message}`)
1047
2046
  stats.errors++
@@ -1050,28 +2049,39 @@ export async function installOpenCode(
1050
2049
  if (tuiStatus === 'created') stats.created++
1051
2050
  else stats.skipped++
1052
2051
  }
2052
+ // -----------------------------------------------------------------------
2053
+ // 2.9b V2 terminal-client config: cancel the builtin Context sidebar block
2054
+ // -----------------------------------------------------------------------
2055
+ // The directive belongs in the V2 client config, which exists ONLY globally
2056
+ // (V2 has no project-local client config), so a project install must not
2057
+ // create one. Keeping it in the installer is what makes the de-duplication
2058
+ // durable: a hand edit in ~/.config/opencode/cli.json would be lost as soon as
2059
+ // the user re-runs init, and the Context block would render twice again.
2060
+ if (componentSet.has('plugins') && version === 'v2' && isGlobal) {
2061
+ try {
2062
+ const cliStatus = applyContextSidebarNegation(target, { dryRun, recorder })
2063
+ if (cliStatus === 'created') stats.created++
2064
+ else if (cliStatus === 'removed' || cliStatus === 'unverified') stats.warnings++
2065
+ else stats.skipped++
2066
+ } catch (cause) {
2067
+ // A client config we cannot update is not a failed install: the plugin
2068
+ // payload and the host config are already in place.
2069
+ warning(`Could not disable the builtin Context sidebar block: ${cause.message}`)
2070
+ stats.warnings++
2071
+ }
2072
+ }
2073
+ if (componentSet.has('plugins')) advancePhase()
1053
2074
 
1054
2075
  // -----------------------------------------------------------------------
1055
2076
  // 2.10 Install runtime infrastructure (--components runtime)
1056
2077
  // MCP server scripts, code-mode scripts, tiers.json
1057
2078
  // -----------------------------------------------------------------------
1058
2079
  if (componentSet.has('runtime')) {
1059
- section('\u2699\uFE0F Runtime')
2080
+ section('Runtime')
1060
2081
  const runtimeTarget = isGlobal ? target : join(target, '.opencode')
1061
2082
 
1062
2083
  // ── MCP server scripts ──
1063
- const mcpScripts = [
1064
- 'mcp_resources.py',
1065
- 'code_mode.py',
1066
- 'memory_mcp.py',
1067
- 'scrub-secrets.py',
1068
- '_pantheon_paths.py',
1069
- 'mcp_codemap_module.py',
1070
- 'mcp_persistence.py',
1071
- 'pantheon_vision.py',
1072
- 'eval_store.py',
1073
- 'themis_heuristic_scan.py',
1074
- ]
2084
+ const mcpScripts = MCP_SCRIPTS
1075
2085
  const srcScriptsDir = join(ROOT, 'scripts')
1076
2086
  // Canonical MCP server sources live in src/mcp/. Map them explicitly so the
1077
2087
  // sync always copies from the canonical source, never from the stale root
@@ -1099,7 +2109,7 @@ export async function installOpenCode(
1099
2109
  }
1100
2110
  const content = readFileSync(src, 'utf8')
1101
2111
  const dst = join(dstScriptsDir, script)
1102
- const status = writeIfChanged(dst, content, dryRun)
2112
+ const status = writeIfChanged(dst, content, dryRun, { recorder })
1103
2113
  if (status === 'created') {
1104
2114
  stats.created++
1105
2115
  // Make executable
@@ -1117,7 +2127,9 @@ export async function installOpenCode(
1117
2127
  const visionRequirements = join(ROOT, 'src', 'mcp', 'requirements-vision.txt')
1118
2128
  if (existsSync(visionRequirements)) {
1119
2129
  const destination = join(runtimeTarget, 'requirements-vision.txt')
1120
- const status = writeIfChanged(destination, readFileSync(visionRequirements, 'utf8'), dryRun)
2130
+ const status = writeIfChanged(destination, readFileSync(visionRequirements, 'utf8'), dryRun, {
2131
+ recorder,
2132
+ })
1121
2133
  if (status === 'created') stats.created++
1122
2134
  else stats.skipped++
1123
2135
  } else {
@@ -1129,7 +2141,19 @@ export async function installOpenCode(
1129
2141
  const srcCodeModeDir = join(ROOT, '.pantheon', 'code-mode')
1130
2142
  const dstCodeModeDir = join(runtimeTarget, '.pantheon', 'code-mode')
1131
2143
  if (existsSync(srcCodeModeDir)) {
1132
- const cmResult = syncDir(srcCodeModeDir, dstCodeModeDir, dryRun, clean)
2144
+ // manifest.json is owned by writeCodeModeManifest (below), not by the dir
2145
+ // sync. Excluding it here keeps exactly ONE writer/count for that path,
2146
+ // so the preview action and the install summary can never diverge.
2147
+ const cmResult = syncDir(
2148
+ srcCodeModeDir,
2149
+ dstCodeModeDir,
2150
+ dryRun,
2151
+ clean,
2152
+ (f) => f !== 'manifest.json',
2153
+ recorder,
2154
+ reviewedRemovals,
2155
+ reviewedSnapshots,
2156
+ )
1133
2157
  stats.created += cmResult.created
1134
2158
  stats.skipped += cmResult.skipped
1135
2159
  } else {
@@ -1140,13 +2164,18 @@ export async function installOpenCode(
1140
2164
  warning(`Code-mode source not found: ${srcCodeModeDir} — creating empty ${dstCodeModeDir}`)
1141
2165
  if (!dryRun) mkdirSync(dstCodeModeDir, { recursive: true })
1142
2166
  stats.created++
2167
+ // The empty runtime dir is a real create counted by `stats.created`, so
2168
+ // record it too (or the preview under-reports on this fallback path).
2169
+ recordChange({ path: dstCodeModeDir, action: ACTIONS.CREATE, bytes: 0 }, recorder)
1143
2170
  }
1144
2171
 
1145
2172
  // B3-08: explicit installation mode — seed the manifest with SHA-256
1146
2173
  // digests so the server never executes a script implicitly.
1147
- const approvedScripts = writeCodeModeManifest(dstCodeModeDir, dryRun)
1148
- if (approvedScripts > 0) {
1149
- info(`Code-mode manifest: ${approvedScripts} script(s) approved`)
2174
+ const manifest = writeCodeModeManifest(srcCodeModeDir, dstCodeModeDir, dryRun, recorder)
2175
+ if (manifest.status === 'created') stats.created++
2176
+ else if (manifest.status === 'skipped') stats.skipped++
2177
+ if (manifest.approved > 0) {
2178
+ info(`Code-mode manifest: ${manifest.approved} script(s) approved`)
1150
2179
  }
1151
2180
 
1152
2181
  // ── tiers.json ──
@@ -1154,11 +2183,12 @@ export async function installOpenCode(
1154
2183
  const dstTiers = join(runtimeTarget, '.pantheon', 'tiers.json')
1155
2184
  if (existsSync(srcTiers)) {
1156
2185
  const content = readFileSync(srcTiers, 'utf8')
1157
- const status = writeIfChanged(dstTiers, content, dryRun)
2186
+ const status = writeIfChanged(dstTiers, content, dryRun, { recorder })
1158
2187
  if (status === 'created') stats.created++
1159
2188
  else stats.skipped++
1160
2189
  }
1161
2190
  }
2191
+ if (componentSet.has('runtime')) advancePhase()
1162
2192
 
1163
2193
  // -----------------------------------------------------------------------
1164
2194
  // 2.11 Setup virtual environment + health check (--components runtime)
@@ -1168,7 +2198,24 @@ export async function installOpenCode(
1168
2198
  // -----------------------------------------------------------------------
1169
2199
  let runtimeHealthy = !componentSet.has('runtime')
1170
2200
  if (componentSet.has('runtime')) {
1171
- runtimeHealthy = setupRuntimePhase(target, { dryRun, clean, isGlobal }, stats)
2201
+ runtimeHealthy = setupRuntimePhase(
2202
+ target,
2203
+ {
2204
+ dryRun,
2205
+ clean,
2206
+ isGlobal,
2207
+ recorder,
2208
+ reviewedRemovals,
2209
+ reviewedSnapshots,
2210
+ // Two distinct gauge phases share this one call: the venv setup and
2211
+ // the health check. Hooks keep the gauge honest without leaking the
2212
+ // UI object into the runtime module.
2213
+ onVenvDone: () => advancePhase(S.settingUpRuntime),
2214
+ onHealthDone: () => advancePhase(S.runningHealthChecks),
2215
+ },
2216
+ stats,
2217
+ opts.deps,
2218
+ )
1172
2219
  }
1173
2220
 
1174
2221
  // -----------------------------------------------------------------------
@@ -1569,10 +2616,19 @@ export async function installOpenCode(
1569
2616
  // Point the config at the venv even on a first install; setupVenv runs
1570
2617
  // later in this function and creates this path before OpenCode starts.
1571
2618
  const runtimeTarget = isGlobal ? target : join(target, '.opencode')
1572
- applyMcpServerEntries(config, {
2619
+ const mcp = applyMcpServerEntries(config, {
1573
2620
  runtimeTarget,
1574
2621
  venvPython: venvPythonPath(target),
2622
+ version,
1575
2623
  })
2624
+ mcpServers = mcp.servers
2625
+ // `permission.mcp.<server>: ask` is inert on OpenCode 2.x. Never leave the
2626
+ // user believing the default gated anything: report each unenforced entry
2627
+ // and point at the enforceable form.
2628
+ for (const message of mcp.warnings ?? []) {
2629
+ warning(message)
2630
+ stats.warnings += 1
2631
+ }
1576
2632
  }
1577
2633
 
1578
2634
  // ── V2 native migration ──
@@ -1580,6 +2636,10 @@ export async function installOpenCode(
1580
2636
  // before writing. V1 path is untouched (zero regression).
1581
2637
  let configToWrite = config
1582
2638
  if (version === 'v2') {
2639
+ // The V2 converters can emit raw console warnings (ambiguous legacy
2640
+ // values). Close the gauge line first so they are not printed on top of it
2641
+ // and then erased by the next `\r` clear.
2642
+ endGaugeLine()
1583
2643
  info(S.v2Migrating)
1584
2644
  configToWrite = migrateV1toV2(config)
1585
2645
 
@@ -1611,25 +2671,30 @@ export async function installOpenCode(
1611
2671
  }
1612
2672
 
1613
2673
  const configContent = `${JSON.stringify(configToWrite, null, 2)}\n`
2674
+ const configStep = step(S.writingConfig)
1614
2675
  const status = writeConfigWithBackup(targetConfigPath, configContent, dryRun, {
1615
2676
  expectedContent: configRaw,
1616
2677
  // Test seam: lets a test simulate a concurrent writer landing between the
1617
2678
  // initial config read and the pre-swap recheck. Absent in production.
1618
2679
  beforeRecheck: opts.deps?.beforeRecheck,
2680
+ recorder,
1619
2681
  })
1620
2682
  if (status === 'conflict') {
2683
+ configStep(false)
1621
2684
  // The user's config changed under the installer between the read and the
1622
2685
  // swap. Treating this as an ordinary skipped write would report a
1623
2686
  // successful install over a file we never actually updated — fail loudly
1624
- // and leave the target and its `.bak` byte-identical instead.
2687
+ // and leave the target byte-identical instead.
1625
2688
  throw new Error(
1626
2689
  `Installation aborted: ${targetConfigPath} changed on disk during install ` +
1627
2690
  '(it no longer matches the content that was read); refusing to overwrite it. ' +
1628
2691
  'Re-run the installer once the file is stable.',
1629
2692
  )
1630
2693
  }
2694
+ configStep(true)
1631
2695
  if (status === 'created') stats.created++
1632
2696
  else stats.skipped++
2697
+ advancePhase()
1633
2698
 
1634
2699
  // -----------------------------------------------------------------------
1635
2700
  // 3.5 Run migrations (--components runtime)
@@ -1637,7 +2702,14 @@ export async function installOpenCode(
1637
2702
  if (componentSet.has('runtime')) {
1638
2703
  const currentVersion = detectVersion(target)
1639
2704
  if (currentVersion) {
1640
- const migration = runMigrations(target, currentVersion, { dryRun })
2705
+ const migrationStep = step(S.runningMigrations)
2706
+ const migration = runMigrations(target, currentVersion, {
2707
+ dryRun,
2708
+ recorder,
2709
+ updatedAt: planTimestamp,
2710
+ })
2711
+ migrationStep(true)
2712
+ if (migration.plannedState) projectedState = migration.plannedState
1641
2713
  if (migration.applied > 0) {
1642
2714
  success(`Applied ${migration.applied} migration(s)`)
1643
2715
  for (const msg of migration.messages) {
@@ -1645,6 +2717,125 @@ export async function installOpenCode(
1645
2717
  }
1646
2718
  }
1647
2719
  }
2720
+ // Counted even when there is nothing to migrate: the phase ran its check.
2721
+ advancePhase()
2722
+ }
2723
+
2724
+ if (opts.preset && dryRun) {
2725
+ const { writeActivePreset } = await import('./model-picker.mjs')
2726
+ writeActivePreset(target, opts.preset, {
2727
+ dryRun: true,
2728
+ source: 'cli',
2729
+ updatedAt: planTimestamp,
2730
+ recorder,
2731
+ logger: { log() {} },
2732
+ })
2733
+ }
2734
+
2735
+ // -----------------------------------------------------------------------
2736
+ // 3.75 Preview summary (Beta 11 Setup phase 1): print the REAL per-file
2737
+ // change set this same pass would apply. Paths + action + byte size
2738
+ // ONLY — never file contents or hashes. Nothing was written.
2739
+ // -----------------------------------------------------------------------
2740
+ // A dry run has finished every phase it runs at this point (no state write):
2741
+ // close the gauge BEFORE the plan so the final line stands on its own.
2742
+ if (dryRun) {
2743
+ progress?.done()
2744
+ if (preview) endGaugeLine()
2745
+ }
2746
+ if (preview) {
2747
+ // Project the terminal state write using the plan's stable timestamp so
2748
+ // saved-plan apply can validate its exact output fingerprint.
2749
+ const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
2750
+ let state = projectedState ?? readState(target)
2751
+ if (!state) state = createInitialState(packageVersion, planTimestamp)
2752
+ state.pantheon_version = packageVersion
2753
+ state.updated_at = planTimestamp
2754
+ state.schema_version = 2
2755
+ for (const component of ['agents', 'skills', 'plugins', 'runtime']) {
2756
+ if (!componentSet.has(component)) continue
2757
+ const componentStatus = component === 'runtime' && !runtimeHealthy ? 'failed' : 'installed'
2758
+ const componentVersion = state.components?.[component]?.version ?? 1
2759
+ setComponentState(state, component, componentVersion, componentStatus)
2760
+ }
2761
+ const stateContent = `${JSON.stringify(state, null, 2)}\n`
2762
+ // NOTE: this fingerprint is the PROJECTED terminal state, not a byte-exact
2763
+ // prediction of the state file an apply leaves behind. The apply writes
2764
+ // `install-state.json` only after `updateFileInventory()` has added the
2765
+ // verified-file entries, so the final bytes (and hash) differ from this
2766
+ // preview by design. Do not "fix" the fingerprint to match the audit run:
2767
+ // the inventory entries are an OUTPUT of the apply, not an input to it.
2768
+ recordChange(
2769
+ {
2770
+ path: join(target, '.pantheon', 'install-state.json'),
2771
+ action: hasState(target) ? ACTIONS.UPDATE : ACTIONS.CREATE,
2772
+ bytes: Buffer.byteLength(stateContent, 'utf8'),
2773
+ outputFingerprint: fingerprintOutput(stateContent),
2774
+ scored: false,
2775
+ },
2776
+ recorder,
2777
+ )
2778
+ const plan = summarizeChanges(preview.entries)
2779
+ // The MCP section is derived from the write path: `mcpServers` holds the
2780
+ // names `applyMcpServerEntries` seeded in THIS pass, in write order (empty
2781
+ // when the runtime component is not selected or failed its prerequisites).
2782
+ plan.mcpServers = mcpServers
2783
+ plan.versionAssumed = versionAssumed
2784
+ planFiles = plan.files
2785
+ planTotals = plan.totals
2786
+ plannedChanges = plan.totals.create + plan.totals.update + plan.totals.remove
2787
+ removalPaths = [
2788
+ ...new Set(
2789
+ preview.entries
2790
+ .filter((entry) => entry.action === ACTIONS.REMOVE)
2791
+ .map((entry) => resolve(entry.path)),
2792
+ ),
2793
+ ].sort()
2794
+ // Snapshot both net changes and every raw removal target. A later write can
2795
+ // make a removal path look unchanged in the net plan, but it still needs
2796
+ // review before the clean operation deletes and recreates it.
2797
+ const snapshotPaths = new Set([...plan.files.map((file) => file.path), ...removalPaths])
2798
+ plannedSnapshots = [...snapshotPaths].map((filePath) => ({
2799
+ path: filePath,
2800
+ ...snapshot(filePath),
2801
+ }))
2802
+ const statsDelta = {
2803
+ created: stats.created - statsBefore.created,
2804
+ skipped: stats.skipped - statsBefore.skipped,
2805
+ }
2806
+ const mismatch = planStatsMismatch(plan, statsDelta)
2807
+ if (mismatch) {
2808
+ // Development safety net: a writer that incremented THIS call's install
2809
+ // stats but never recorded a change would otherwise make the preview
2810
+ // silently incomplete. Surface it loudly instead of hiding it.
2811
+ warning(
2812
+ `Change-plan consistency mismatch: plan reports ${mismatch.changed} changed / ` +
2813
+ `${mismatch.unchanged} unchanged vs stats ${mismatch.recordedChanged}/${mismatch.recordedUnchanged}`,
2814
+ )
2815
+ }
2816
+ // Dry-run surface: by default a SUMMARY (counts + MCP servers + "No files
2817
+ // were written"), never one line per file — the gauge already answered
2818
+ // "is it moving?" and per-file detail is opt-in via --verbose. `[DRY-RUN]`
2819
+ // marks the header only; it no longer prefixes every line.
2820
+ // An internal snapshot pass on the apply path (`quietPlan`, e.g. an
2821
+ // authorized `--yes` run) computes the plan and snapshots but must NOT
2822
+ // echo it — a real apply is not a dry run.
2823
+ if (!opts.quietPlan) {
2824
+ const verbose = opts.verbose === true
2825
+ const planText = formatChangePlan(target, plan, { perFile: verbose })
2826
+ const planLines = planText.split('\n')
2827
+ console.log('')
2828
+ if (verbose && removalPaths.length > 0) {
2829
+ console.log(tag(`Removal review — ${removalPaths.length} path(s):`))
2830
+ for (const filePath of removalPaths) {
2831
+ console.log(` remove ${displayPath(target, filePath)}`)
2832
+ }
2833
+ console.log('')
2834
+ }
2835
+ console.log(tag(planLines[0]))
2836
+ for (const line of planLines.slice(1)) console.log(line)
2837
+ console.log('')
2838
+ }
1648
2839
  }
1649
2840
 
1650
2841
  // -----------------------------------------------------------------------
@@ -1653,6 +2844,7 @@ export async function installOpenCode(
1653
2844
  // -----------------------------------------------------------------------
1654
2845
 
1655
2846
  if (interactive && !dryRun) {
2847
+ endGaugeLine()
1656
2848
  const created = stats.created
1657
2849
  const skipped = stats.skipped
1658
2850
  const errors = stats.errors
@@ -1669,14 +2861,13 @@ export async function installOpenCode(
1669
2861
  process.stdout.write(
1670
2862
  ` ${colors.dim('\u2500'.repeat(Math.min(process.stdout.columns || 60, 60)))}\n`,
1671
2863
  )
1672
- process.stdout.write(` ${colors.green('\u2713')} ${created} component(s) installed\n`)
2864
+ process.stdout.write(` [OK] ${created} component(s) installed\n`)
1673
2865
  if (skipped > 0)
1674
2866
  process.stdout.write(` ${colors.dim('\u2014')} ${skipped} already up-to-date\n`)
1675
- if (errors > 0)
1676
- process.stdout.write(` ${colors.yellow('\u26a0')} ${errors} error(s) encountered\n`)
2867
+ if (errors > 0) process.stdout.write(` [WARN] ${errors} error(s) encountered\n`)
1677
2868
  if (warnings > 0)
1678
2869
  process.stdout.write(
1679
- ` ${colors.yellow('\u26a0')} ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
2870
+ ` [WARN] ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
1680
2871
  )
1681
2872
  process.stdout.write('\n')
1682
2873
  process.stdout.write(` ${colors.bold('Next steps:')}\n`)
@@ -1686,24 +2877,41 @@ export async function installOpenCode(
1686
2877
  ` ${colors.dim('\u2022')} Run 'opencode' to start using Pantheon agents\n`,
1687
2878
  )
1688
2879
  process.stdout.write('\n')
1689
- } else {
1690
- printSummary(target, ['opencode'], stats)
2880
+ printWorktreeGuidance({ projectRoot: process.cwd(), interactive: true })
1691
2881
  }
1692
2882
 
1693
2883
  // -----------------------------------------------------------------------
1694
- // 5. Model preset selection (--components agents). Interactive wizard runs
1695
- // unless autoYes (use defaults) or an explicit --preset was given.
2884
+ // 5. V1 model preset selection (--components agents). V2 ignores the legacy
2885
+ // active-preset marker, so it has no profile wizard or --preset support.
2886
+ // The V1 interactive wizard runs unless autoYes or an explicit preset was given.
1696
2887
  // Q1 default "herdar do chat" (inherit) writes no active-preset.json —
1697
2888
  // delegates inherit the parent chat model (native inheritance).
1698
2889
  // -----------------------------------------------------------------------
1699
- if (interactive && !dryRun && !autoYes && !opts.preset) {
2890
+ if (interactive && stdinTTY && version === 'v1' && !dryRun && !autoYes && !opts.preset) {
1700
2891
  const { runInitWizard } = await import('./model-picker.mjs')
1701
- await runInitWizard({ presetDir: target, logger: console })
2892
+ await runInitWizard({ presetDir: target, logger: console, prompts: opts.deps?.prompts })
1702
2893
  }
1703
2894
 
1704
2895
  if (opts.preset && !dryRun) {
1705
2896
  const { writeActivePreset } = await import('./model-picker.mjs')
1706
- writeActivePreset(target, opts.preset, { source: 'cli' })
2897
+ writeActivePreset(target, opts.preset, { source: 'cli', updatedAt: planTimestamp, recorder })
2898
+ }
2899
+
2900
+ // -----------------------------------------------------------------------
2901
+ // 5.5 Optional vision prompt (interactive TTY only). The default — automatic
2902
+ // discovery — writes nothing, and non-interactive flows (no TTY, --yes,
2903
+ // --headless, automated sandboxes) never reach this block, so no run
2904
+ // blocks on stdin and the default behavior is unchanged. A failure here
2905
+ // must never fail the install: vision stays optional.
2906
+ // -----------------------------------------------------------------------
2907
+ if (interactive && !dryRun && !autoYes) {
2908
+ const runVisionPrompt =
2909
+ opts.deps?.runVisionPrompt ?? (await import('./vision-prompt.mjs')).runVisionPrompt
2910
+ try {
2911
+ await runVisionPrompt({ logger: console })
2912
+ } catch (err) {
2913
+ warning(`Vision setup skipped: ${err instanceof Error ? err.message : String(err)}`)
2914
+ }
1707
2915
  }
1708
2916
 
1709
2917
  // Fail-closed: accumulated stats.errors (bad sources, missing requirements,
@@ -1718,18 +2926,69 @@ export async function installOpenCode(
1718
2926
  // to `doctor` forever. Unselected components retain their previous state.
1719
2927
  if (!dryRun) {
1720
2928
  const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
1721
- let state = readState(target)
2929
+ let state = projectedState ?? readState(target)
1722
2930
  if (!state && hasState(target)) {
1723
2931
  throw new Error('Installation state exists but cannot be read; refusing to replace it')
1724
2932
  }
1725
- state ??= createInitialState(packageVersion)
2933
+ state ??= createInitialState(packageVersion, planTimestamp)
1726
2934
  state.pantheon_version = packageVersion
2935
+ state.updated_at = planTimestamp
1727
2936
  for (const component of ['agents', 'skills', 'plugins', 'runtime']) {
1728
2937
  if (!componentSet.has(component)) continue
1729
2938
  const status = component === 'runtime' && !runtimeHealthy ? 'failed' : 'installed'
1730
2939
  const componentVersion = state.components?.[component]?.version ?? 1
1731
2940
  setComponentState(state, component, componentVersion, status)
1732
2941
  }
1733
- writeState(target, state)
2942
+ const verifiedFiles = summarizeChanges(ownRecorder?.entries ?? []).files.flatMap((file) => {
2943
+ if (!['create', 'update', 'unchanged'].includes(file.action) || !file.outputFingerprint)
2944
+ return []
2945
+ const owner = componentForInstalledPath(target, file.path, { isGlobal, version })
2946
+ if (!owner) return []
2947
+ return [
2948
+ {
2949
+ path: file.path,
2950
+ sha256: file.outputFingerprint,
2951
+ component: owner.component,
2952
+ layout: owner.layout,
2953
+ action: file.action,
2954
+ },
2955
+ ]
2956
+ })
2957
+ const stateStep = step(S.recordingState)
2958
+ updateFileInventory(state, target, {
2959
+ selectedComponents: [...componentSet],
2960
+ verifiedFiles,
2961
+ })
2962
+ writeState(target, state, { updatedAt: planTimestamp })
2963
+ stateStep(true)
2964
+ advancePhase()
1734
2965
  }
2966
+
2967
+ // The apply gauge ends before the human summary; a dry run already closed it
2968
+ // before its plan block (`done()` is idempotent). A preview must NOT print
2969
+ // the installed banner: bin/pantheon-init prints the preview-only line.
2970
+ progress?.done()
2971
+ if (!interactive && !dryRun && !opts.planOnly) {
2972
+ printSummary(target, ['opencode'], stats)
2973
+ }
2974
+
2975
+ // Beta 11 Setup phase 3: report whether this call APPLIED, so the caller can
2976
+ // avoid a success banner for a plan-only / unauthorized run. The dry pass also
2977
+ // returns the planned-target snapshots for the apply pass's drift check.
2978
+ return dryRun
2979
+ ? {
2980
+ ...stats,
2981
+ applied: false,
2982
+ reason: 'plan',
2983
+ planned: plannedChanges,
2984
+ snapshots: plannedSnapshots,
2985
+ files: planFiles,
2986
+ totals: planTotals,
2987
+ mcpServers,
2988
+ removals: removalPaths,
2989
+ target,
2990
+ openCodeVersion: version,
2991
+ versionAssumed,
2992
+ }
2993
+ : { ...stats, applied: true, reason: 'applied' }
1735
2994
  }