pantheon-opencode 1.6.0-beta.9 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +144 -365
  4. package/README.md +124 -607
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +504 -141
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +22 -13
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +850 -45
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +99 -383
  29. package/scripts/install/interrupt.mjs +78 -0
  30. package/scripts/install/migrate.mjs +49 -25
  31. package/scripts/install/model-picker.mjs +218 -250
  32. package/scripts/install/opencode-state.mjs +91 -0
  33. package/scripts/install/opencode-version.mjs +83 -21
  34. package/scripts/install/opencode.mjs +1675 -187
  35. package/scripts/install/plan-artifact.mjs +517 -0
  36. package/scripts/install/plan.mjs +475 -0
  37. package/scripts/install/plugin.mjs +214 -27
  38. package/scripts/install/prompt-result.mjs +2 -0
  39. package/scripts/install/run-record.mjs +115 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +93 -8
  43. package/scripts/install/v2-capabilities.mjs +205 -0
  44. package/scripts/install/venv.mjs +90 -47
  45. package/scripts/install/verify.mjs +128 -0
  46. package/scripts/install/vision-prompt.mjs +173 -0
  47. package/scripts/install-mcp.mjs +2 -2
  48. package/scripts/manifest-inventory.mjs +49 -3
  49. package/scripts/mcp_persistence.py +1535 -1050
  50. package/scripts/memory_mcp.py +12 -843
  51. package/scripts/node-engine-policy.mjs +85 -0
  52. package/scripts/package-evidence.mjs +10 -2
  53. package/scripts/postinstall.mjs +26 -26
  54. package/scripts/probe-pantheon-cost.mjs +118 -19
  55. package/scripts/prune.mjs +9 -3
  56. package/scripts/reconcile.mjs +325 -0
  57. package/scripts/release-gates.mjs +687 -0
  58. package/scripts/restore.mjs +222 -0
  59. package/scripts/run-node-tests.mjs +24 -8
  60. package/scripts/sync-artifacts.mjs +19 -7
  61. package/scripts/sync-tui.mjs +5 -1
  62. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  63. package/scripts/uninstall.mjs +369 -34
  64. package/scripts/update.mjs +164 -0
  65. package/scripts/validate-node-engine-policy.mjs +13 -0
  66. package/scripts/version-check.mjs +34 -1
  67. package/scripts/versioning.mjs +23 -3
  68. package/scripts/vision-status.mjs +682 -0
  69. package/skills-lock.json +8 -8
  70. package/src/agents/aphrodite.md +13 -10
  71. package/src/agents/apollo.md +4 -5
  72. package/src/agents/athena.md +74 -46
  73. package/src/agents/demeter.md +10 -7
  74. package/src/agents/gaia.md +0 -1
  75. package/src/agents/hephaestus.md +4 -3
  76. package/src/agents/hermes.md +10 -9
  77. package/src/agents/iris.md +6 -1
  78. package/src/agents/mnemosyne.md +10 -4
  79. package/src/agents/nyx.md +4 -4
  80. package/src/agents/prometheus.md +12 -11
  81. package/src/agents/talos.md +6 -0
  82. package/src/agents/zeus.md +84 -56
  83. package/src/instructions/agent-return-format.instructions.md +12 -41
  84. package/src/instructions/memory-protocol.instructions.md +5 -11
  85. package/src/instructions/test-economy.instructions.md +12 -0
  86. package/src/instructions/yagni.instructions.md +6 -15
  87. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  88. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  89. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  90. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  91. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  92. package/src/mcp/_pantheon_paths.py +24 -0
  93. package/src/mcp/mcp_codemap_module.py +86 -18
  94. package/src/mcp/mcp_persistence.py +1535 -1050
  95. package/src/mcp/memory_mcp.py +444 -94
  96. package/src/mcp/pantheon_vision.py +285 -41
  97. package/src/mcp/requirements-mcp.txt +6 -1
  98. package/src/mcp/requirements-vision.txt +1 -1
  99. package/src/pantheon/context-pruner.ts +541 -0
  100. package/src/pantheon/cost-command.ts +901 -60
  101. package/src/pantheon/delegation-enforce.ts +160 -23
  102. package/src/pantheon/goal-loop.ts +11 -8
  103. package/src/pantheon/guard-path.ts +162 -0
  104. package/src/pantheon/memory-context.ts +1017 -0
  105. package/src/pantheon/model-agents.ts +19 -0
  106. package/src/pantheon/model-command.ts +218 -56
  107. package/src/pantheon/model-pricing.ts +536 -0
  108. package/src/pantheon/presets.mjs +2 -0
  109. package/src/pantheon/task-result-guard.ts +50 -14
  110. package/src/pantheon/v2-bounded-read.ts +654 -0
  111. package/src/pantheon/v2-bridge.ts +27 -0
  112. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  113. package/src/pantheon/v2-execute-after.ts +135 -24
  114. package/src/pantheon/v2-model-overrides.ts +275 -0
  115. package/src/pantheon/v2-shell-hooks.ts +260 -0
  116. package/src/pantheon/v2-tools.ts +89 -35
  117. package/src/pantheon/v2-unsupported.mjs +34 -7
  118. package/src/pantheon/v2-vision.ts +622 -0
  119. package/src/pantheon/vision-local.ts +531 -0
  120. package/src/pantheon/vision.ts +1166 -116
  121. package/src/plugin-v2.ts +1039 -171
  122. package/src/plugin.ts +37 -13
  123. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  124. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  125. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  126. package/src/plugins/tui/dist/tui.js +1 -1
  127. package/src/plugins/tui/package-lock.json +15 -15
  128. package/src/plugins/tui/package.json +7 -5
  129. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  130. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  131. package/src/routing.yml +50 -5
  132. package/src/skills/agent-coordination/SKILL.md +7 -2
  133. package/src/skills/artifact-management/SKILL.md +5 -1
  134. package/src/skills/auto-continue/SKILL.md +14 -6
  135. package/src/skills/codemap/SKILL.md +1 -1
  136. package/src/skills/memory-bank/SKILL.md +21 -13
  137. package/src/skills/session-goal/SKILL.md +12 -22
  138. package/src/skills/spec-driven-development/SKILL.md +3 -1
  139. package/src/skills/worktrees/SKILL.md +30 -11
  140. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -12,27 +12,35 @@
12
12
  * scripts/install/opencode-version.mjs). Known V2 beta gaps handled here:
13
13
  * top-level `subagent_depth` is migrated to `experimental.subagent_depth`, and
14
14
  * the instruction content is consolidated into AGENTS.md, which both versions
15
- * load. Pass --version v2 to pantheon-init for an informational label; state
16
- * isolation is handled at runtime via OPENCODE_DB.
15
+ * load. Pass --version v2 to pantheon-init for an informational label.
16
+ *
17
+ * Nothing here isolates host STATE: both generations read one OpenCode store,
18
+ * and the resolver in scripts/install/opencode-state.mjs (not a literal in this
19
+ * file) is what the V2 notice reports.
17
20
  */
18
21
 
19
22
  import { createHash } from 'node:crypto'
20
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
23
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs'
21
24
  import { homedir } from 'node:os'
22
- import { dirname, isAbsolute, join, resolve } from 'node:path'
23
- import { listV2UnsupportedFeatures } from '../../src/pantheon/v2-unsupported.mjs'
24
- import { copyAgentPrompts } from '../build-agents-md.mjs'
25
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
26
+ import { copyAgentPrompts, writeAgentsMdManaged } from '../build-agents-md.mjs'
27
+ import { backupWarning, createBackupSet, previewBackupSet } from './backup.mjs'
25
28
  import {
26
29
  bullet,
27
30
  colors,
28
31
  configure,
32
+ gauge as createGauge,
33
+ endGaugeLine,
29
34
  error,
30
35
  info,
36
+ notice,
31
37
  printSummary,
38
+ printWorktreeGuidance,
32
39
  section,
33
40
  spinner,
34
41
  step,
35
42
  success,
43
+ tag,
36
44
  warning,
37
45
  } from './cli-ui.mjs'
38
46
  import {
@@ -40,10 +48,28 @@ import {
40
48
  migrateMcpEntrypointPaths,
41
49
  migrateV1toV2,
42
50
  } from './config-migration.mjs'
51
+ import { componentForInstalledPath, updateFileInventory } from './file-inventory.mjs'
43
52
  import { healthCheck } from './health-check.mjs'
44
53
  import { detectVersion, runMigrations } from './migrate.mjs'
45
- import { resolveOpenCodeVersion } from './opencode-version.mjs'
54
+ import { describeSharedState } from './opencode-state.mjs'
55
+ import { DRY_RUN_PROBE_TIMEOUT_MS, resolveOpenCodeVersion } from './opencode-version.mjs'
56
+ import {
57
+ ACTIONS,
58
+ createRecorder,
59
+ displayPath,
60
+ fingerprintOutput,
61
+ formatChangePlan,
62
+ isRecording,
63
+ planStatsMismatch,
64
+ recordChange,
65
+ recordRemovalTree,
66
+ removeReviewedTree,
67
+ snapshot,
68
+ summarizeChanges,
69
+ } from './plan.mjs'
70
+ import { findPlanDrift } from './plan-artifact.mjs'
46
71
  import { copyPluginFiles, installPlugin, registerPlugin, unregisterPlugin } from './plugin.mjs'
72
+ import { PROMPT_CANCELED } from './prompt-result.mjs'
47
73
  import {
48
74
  checkRuntimePrerequisites,
49
75
  collectSkillNames,
@@ -58,8 +84,13 @@ import {
58
84
  } from './shared.mjs'
59
85
  import { createInitialState, hasState, readState, setComponentState, writeState } from './state.mjs'
60
86
  import { strings } from './strings.mjs'
61
-
87
+ import {
88
+ describePluginOptionsReachability,
89
+ formatV2CapabilityNotice,
90
+ v2Capabilities,
91
+ } from './v2-capabilities.mjs'
62
92
  import { setupVenv, venvPythonPath } from './venv.mjs'
93
+ import { assertNoSymlinkAncestors, assertPathWithin, assertSafeRemoval } from './verify.mjs'
63
94
 
64
95
  const COMPONENT_NAMES = [
65
96
  'agents',
@@ -71,6 +102,211 @@ const COMPONENT_NAMES = [
71
102
  'runtime',
72
103
  ]
73
104
 
105
+ /**
106
+ * The ordered phases one install invocation really runs, derived from the
107
+ * FINAL component selection (the interactive wizard may have changed it) and
108
+ * from dry-run semantics. `gauge.total` must be this length — never a fixed
109
+ * guess — so the counter can never drift from the work.
110
+ *
111
+ * * prerequisites run only on an apply with the runtime component;
112
+ * * the backup is planned (dry run) or created (apply);
113
+ * * venv setup runs in BOTH modes (a dry run reports what it would create);
114
+ * * the health check and the install-state write are apply-only.
115
+ *
116
+ * @param {{ components: Iterable<string>, dryRun: boolean }} options
117
+ * @returns {string[]} phase labels, in execution order
118
+ */
119
+ export function planInstallPhases({ components, dryRun }) {
120
+ const S = strings()
121
+ const selected = new Set(components)
122
+ const phases = []
123
+ if (selected.has('runtime') && !dryRun) phases.push(S.checkingPrerequisites)
124
+ phases.push(dryRun ? S.planningBackup : S.creatingBackup)
125
+ if (selected.has('agents')) phases.push(S.installingAgents)
126
+ if (selected.has('skills')) phases.push(S.installingSkills)
127
+ if (selected.has('instructions')) phases.push(S.installingInstructions)
128
+ if (selected.has('prompts')) phases.push(S.installingPrompts)
129
+ if (selected.has('commands')) phases.push(S.installingCommands)
130
+ if (selected.has('plugins')) phases.push(S.installingPlugins)
131
+ if (selected.has('runtime')) {
132
+ phases.push(S.installingRuntime)
133
+ phases.push(S.settingUpRuntime)
134
+ if (!dryRun) phases.push(S.runningHealthChecks)
135
+ }
136
+ phases.push(S.writingConfiguration)
137
+ if (selected.has('runtime')) phases.push(S.runningMigrations)
138
+ if (!dryRun) phases.push(S.recordingState)
139
+ return phases
140
+ }
141
+
142
+ /**
143
+ * MCP server scripts the runtime component installs. Hoisted so the backup-set
144
+ * enumeration and the runtime writer share one source of truth.
145
+ */
146
+ const MCP_SCRIPTS = [
147
+ 'mcp_resources.py',
148
+ 'code_mode.py',
149
+ 'memory_mcp.py',
150
+ 'scrub-secrets.py',
151
+ '_pantheon_paths.py',
152
+ 'mcp_codemap_module.py',
153
+ 'mcp_persistence.py',
154
+ 'pantheon_vision.py',
155
+ 'eval_store.py',
156
+ 'themis_heuristic_scan.py',
157
+ ]
158
+
159
+ /** Recursively list regular files under `root`, relative to `root`. */
160
+ function walkFiles(root, base = root, out = []) {
161
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
162
+ const full = join(root, entry.name)
163
+ if (entry.isDirectory()) walkFiles(full, base, out)
164
+ else if (entry.isFile()) out.push(relative(base, full))
165
+ }
166
+ return out
167
+ }
168
+
169
+ /**
170
+ * Enumerate what the backup set must preserve, derived from the selected
171
+ * components. It returns:
172
+ * - `entries`: paths (relative to `target`) the run can CREATE/UPDATE/REMOVE.
173
+ * For every managed destination tree we take the UNION of the files that
174
+ * already exist there (so a `--clean`, a stale removal, or an
175
+ * instructions-only refresh is captured) and the source-derived destination
176
+ * paths (so a file that will be created is recorded as absent). The union is
177
+ * a superset of the plan's changes — unchanged files are backed up too.
178
+ * - `notRevertible`: paths the run may delete or write but whose byte-for-byte
179
+ * copy is not feasible or is out of the config dir (bulk `.venv` / plugin
180
+ * `node_modules`, the global `tui.json` copies and the global vision config).
181
+ * These are recorded explicitly in the manifest rather than silently ignored.
182
+ * It never reads file contents.
183
+ *
184
+ * @param {string} target
185
+ * @param {Set<string>} componentSet
186
+ * @param {string} version
187
+ * @param {boolean} isGlobal
188
+ * @returns {{ entries: string[], notRevertible: string[] }}
189
+ */
190
+ function collectInstallBackupEntries(target, componentSet, version, isGlobal) {
191
+ const entries = []
192
+ const notRevertible = []
193
+ const rel = (abs) => relative(target, abs)
194
+ const addFile = (abs) => entries.push(rel(abs))
195
+ // Existing files under an in-target tree (covers removals / clean / refresh).
196
+ // `skipDirNames` prunes bulk subdirectories (e.g. plugin `node_modules`) so the
197
+ // walk stays cheap while everything else — including legacy files a clean pass
198
+ // deletes — is captured.
199
+ const addExisting = (dir, skipDirNames = null) => {
200
+ if (!existsSync(dir)) return
201
+ const walk = (base) => {
202
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
203
+ if (skipDirNames && entry.isDirectory() && skipDirNames.has(entry.name)) continue
204
+ const full = join(base, entry.name)
205
+ if (entry.isDirectory()) walk(full)
206
+ else if (entry.isFile()) addFile(full)
207
+ }
208
+ }
209
+ walk(dir)
210
+ }
211
+ // Destination paths derived from a source tree (covers files to be created).
212
+ const addSource = (srcDir, dstDir, filter = null) => {
213
+ if (!existsSync(srcDir)) return
214
+ for (const r of walkFiles(srcDir)) {
215
+ if (filter && !filter(r)) continue
216
+ addFile(join(dstDir, r))
217
+ }
218
+ }
219
+
220
+ const baseDir = isGlobal ? target : join(target, '.opencode')
221
+ const agentPrefix = isGlobal || version === 'v2' ? 'agents' : '.opencode/agents'
222
+ const agentDir = join(target, agentPrefix)
223
+
224
+ // Always touched.
225
+ addFile(join(target, 'opencode.json'))
226
+ addFile(join(target, '.pantheon', 'install-state.json'))
227
+ addFile(join(baseDir, 'opencode-vision.json'))
228
+ // The active-preset writer (writeActivePreset(target, …)) lives at
229
+ // <target>/.pantheon, NOT under <baseDir>, for both project and global scope.
230
+ addFile(join(target, '.pantheon', 'active-preset.json'))
231
+ addFile(join(target, '.pantheon', 'active-preset.json.bak'))
232
+
233
+ // The agent prompt dir is refreshed (existing-only) by an instructions-only
234
+ // run too, so enumerate it whenever EITHER component can write it.
235
+ if (componentSet.has('agents') || componentSet.has('instructions')) {
236
+ addExisting(agentDir)
237
+ }
238
+ if (componentSet.has('agents')) {
239
+ addFile(join(target, 'routing.yml'))
240
+ addSource(
241
+ join(ROOT, 'src', 'agents'),
242
+ agentDir,
243
+ (r) => r.endsWith('.md') && r.toLowerCase() !== 'readme.md',
244
+ )
245
+ }
246
+ if (componentSet.has('skills')) {
247
+ addExisting(join(baseDir, 'skills'))
248
+ addSource(join(ROOT, 'src', 'skills'), join(baseDir, 'skills'))
249
+ }
250
+ if (componentSet.has('instructions')) addFile(join(target, 'AGENTS.md'))
251
+ if (componentSet.has('prompts')) {
252
+ addExisting(join(target, 'prompts'))
253
+ addSource(join(ROOT, 'prompts'), join(target, 'prompts'))
254
+ }
255
+ if (componentSet.has('commands')) {
256
+ const commandDir = isGlobal || version === 'v2' ? 'commands' : '.opencode/commands'
257
+ addExisting(join(target, commandDir))
258
+ addSource(join(ROOT, 'commands'), join(target, commandDir), (r) => r.endsWith('.md'))
259
+ }
260
+ if (componentSet.has('plugins')) {
261
+ const dstPluginDir = isGlobal
262
+ ? join(target, 'plugins', 'pantheon-tui')
263
+ : join(target, '.opencode', 'plugins', 'pantheon-tui')
264
+ // Existing files under the installed plugin dir (legacy `index.tsx` /
265
+ // `dist/tui.tsx` and any extras a `--clean` run deletes) are captured, like
266
+ // every sibling tree — EXCEPT the bulk `node_modules`, which is regenerated
267
+ // by `npm ci` and listed as not revertible.
268
+ addExisting(dstPluginDir, new Set(['node_modules']))
269
+ addSource(join(ROOT, 'src', 'plugins', 'tui', 'dist'), join(dstPluginDir, 'dist'))
270
+ addFile(join(dstPluginDir, 'package.json'))
271
+ addFile(join(dstPluginDir, 'package-lock.json'))
272
+ addFile(join(dstPluginDir, 'tui.ts'))
273
+ addFile(join(dstPluginDir, 'index.ts'))
274
+ notRevertible.push(rel(join(dstPluginDir, 'node_modules')))
275
+ if (version === 'v1') {
276
+ const projectTui = join(baseDir, 'tui.json')
277
+ addFile(projectTui)
278
+ // Cross-location cleanup touches copies OUTSIDE the config dir.
279
+ for (const loc of tuiConfigLocations(target)) {
280
+ if (resolve(loc) !== resolve(projectTui)) notRevertible.push(loc)
281
+ }
282
+ }
283
+ // V2's single terminal-client config, which this install also edits (it
284
+ // cancels the builtin Context sidebar block). Captured so `restore` reverts
285
+ // it byte-for-byte like every other file we touch.
286
+ if (version === 'v2' && isGlobal) addFile(join(baseDir, V2_CLI_CONFIG_FILENAME))
287
+ }
288
+ if (componentSet.has('runtime')) {
289
+ const runtimeTarget = isGlobal ? target : join(target, '.opencode')
290
+ addExisting(join(runtimeTarget, 'scripts'))
291
+ for (const script of MCP_SCRIPTS) addFile(join(runtimeTarget, 'scripts', script))
292
+ addFile(join(runtimeTarget, 'requirements-vision.txt'))
293
+ addSource(join(ROOT, '.pantheon', 'code-mode'), join(runtimeTarget, '.pantheon', 'code-mode'))
294
+ addExisting(join(runtimeTarget, '.pantheon', 'code-mode'))
295
+ addFile(join(runtimeTarget, '.pantheon', 'tiers.json'))
296
+ // `--force` recreates the venv from scratch: bulk, not copied.
297
+ notRevertible.push(rel(join(target, '.venv')))
298
+ }
299
+
300
+ // The vision config is written GLOBALLY (outside the config dir).
301
+ const xdg = process.env.XDG_CONFIG_HOME || join(homedir(), '.config')
302
+ const globalVision = join(xdg, 'opencode', 'opencode-vision.json')
303
+ if (resolve(globalVision) !== resolve(join(baseDir, 'opencode-vision.json'))) {
304
+ notRevertible.push(globalVision)
305
+ }
306
+
307
+ return { entries, notRevertible }
308
+ }
309
+
74
310
  /**
75
311
  * The product defaults an install seeds into the user's `opencode.json`.
76
312
  *
@@ -136,14 +372,27 @@ export const MANAGED_FIELDS = Object.freeze([
136
372
  'disable_model_invocation',
137
373
  ])
138
374
 
139
- const PANTHEON_MCP_SERVERS = Object.freeze([
140
- 'pantheon-resources',
141
- 'pantheon-memory',
142
- 'pantheon-code-mode',
143
- 'pantheon-persistence',
144
- 'pantheon-vision',
375
+ /**
376
+ * The five managed MCP servers, in the ORDER the installer writes them.
377
+ *
378
+ * This table is the single source for both the write (`applyMcpServerEntries`)
379
+ * and the dry-run preview: the preview names the servers this pass seeds, so
380
+ * reordering a server here changes both in lockstep. `script` is the runtime
381
+ * entrypoint, relative to the runtime directory.
382
+ *
383
+ * @type {readonly {name: string, script: string}[]}
384
+ */
385
+ const PANTHEON_MCP_SERVER_ENTRIES = Object.freeze([
386
+ Object.freeze({ name: 'pantheon-resources', script: 'scripts/mcp_resources.py' }),
387
+ Object.freeze({ name: 'pantheon-code-mode', script: 'scripts/code_mode.py' }),
388
+ Object.freeze({ name: 'pantheon-memory', script: 'scripts/memory_mcp.py' }),
389
+ Object.freeze({ name: 'pantheon-persistence', script: 'scripts/mcp_persistence.py' }),
390
+ Object.freeze({ name: 'pantheon-vision', script: 'scripts/pantheon_vision.py' }),
145
391
  ])
146
392
 
393
+ /** The managed server names, in write order. */
394
+ const PANTHEON_MCP_SERVERS = Object.freeze(PANTHEON_MCP_SERVER_ENTRIES.map((entry) => entry.name))
395
+
147
396
  function normalizeMcpPermissionSegment(value) {
148
397
  return value.replace(/[^a-zA-Z0-9_]/g, '_')
149
398
  }
@@ -210,30 +459,40 @@ function deepClone(value) {
210
459
 
211
460
  /**
212
461
  * (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.
462
+ * script, and write it to the destination. This is the explicit installation
463
+ * opt-in: the MCP server only executes scripts listed here whose on-disk hash
464
+ * matches. Missing or empty source approves nothing — execution is never
465
+ * implicit.
466
+ *
467
+ * This function is the SINGLE owner of `manifest.json`: `syncDir` deliberately
468
+ * excludes it (see the runtime block), so exactly one writer and one stats
469
+ * count exist for that path. The payload is derived from the SOURCE scripts
470
+ * (what will be installed), then compared against the CURRENT installed
471
+ * manifest, so the preview action matches what apply writes — including on a
472
+ * script upgrade, where the installed manifest is stale.
473
+ *
474
+ * @returns {{ approved: number, status: 'created'|'skipped'|'conflict'|null }}
216
475
  */
217
- function writeCodeModeManifest(dir, dryRun) {
218
- if (!existsSync(dir)) return 0
476
+ function writeCodeModeManifest(srcDir, dstDir, dryRun, recorder = null) {
477
+ if (!existsSync(srcDir)) return { approved: 0, status: null }
219
478
  let names
220
479
  try {
221
- names = readdirSync(dir)
480
+ names = readdirSync(srcDir)
222
481
  .filter((name) => /\.(sh|py)$/i.test(name) && !name.startsWith('.'))
223
482
  .sort()
224
483
  } catch {
225
- return 0
484
+ return { approved: 0, status: null }
226
485
  }
227
- if (names.length === 0) return 0
486
+ if (names.length === 0) return { approved: 0, status: null }
228
487
  const scripts = {}
229
488
  for (const name of names) {
230
489
  scripts[name] = createHash('sha256')
231
- .update(readFileSync(join(dir, name)))
490
+ .update(readFileSync(join(srcDir, name)))
232
491
  .digest('hex')
233
492
  }
234
493
  const payload = `${JSON.stringify({ version: 1, scripts }, null, 2)}\n`
235
- writeIfChanged(join(dir, 'manifest.json'), payload, dryRun)
236
- return names.length
494
+ const status = writeIfChanged(join(dstDir, 'manifest.json'), payload, dryRun, { recorder })
495
+ return { approved: names.length, status }
237
496
  }
238
497
 
239
498
  function readJsonConfig(filePath) {
@@ -321,6 +580,78 @@ function normalizePluginRef(ref) {
321
580
  return typeof ref === 'string' ? ref.replaceAll('\\', '/').replace(/\/$/, '') : ref
322
581
  }
323
582
 
583
+ /**
584
+ * Whether a path-ish plugin ref is a filesystem path rather than a package spec.
585
+ *
586
+ * The V2 loader treats anything that is not an obvious path as an npm/GitHub
587
+ * spec and runs `npm install` on it — including `a/b`, which it reads as a
588
+ * GitHub repository and fails on (`NpmInstallFailedError`). A relative path is
589
+ * always spelled with `./` or `../`, so that spelling is the discriminator.
590
+ *
591
+ * @param {string} value
592
+ * @returns {boolean}
593
+ */
594
+ function looksLikePluginPath(value) {
595
+ if (value.startsWith('.') || value.startsWith('/') || value.startsWith('~')) return true
596
+ return /^[A-Za-z]:[\\/]/.test(value)
597
+ }
598
+
599
+ /**
600
+ * Whether the OpenCode V2 loader can load a `plugins` entry EXACTLY as written.
601
+ *
602
+ * This is the gate for the V1→V2 migration: the V1 singular `plugin` list is
603
+ * ignored by the V2 host, but moving an entry there into `plugins` only helps
604
+ * when the loader accepts it. The loader's contract (documented on
605
+ * PANTHEON_V2_PLUGIN and proven by sandbox probes) is:
606
+ * - a DIRECTORY containing a real index.ts/index.js loads;
607
+ * - a file path is rejected ("must be a directory");
608
+ * - a package shorthand is resolved through `npm install` and dies with
609
+ * NpmInstallFailedError.
610
+ * Migrating a file path or a shorthand would therefore convert "silently
611
+ * ignored" into "config fails to load", which is worse than leaving it alone.
612
+ *
613
+ * @param {unknown} entry the `plugins`/`plugin` entry
614
+ * @param {string} configDir the config directory the loader resolves against
615
+ * @returns {{ loadable: boolean, reason: 'directory'|'file'|'missing'|'npm-spec'|'unverifiable', resolved: string|null }}
616
+ */
617
+ export function v2PluginEntryLoadability(entry, configDir) {
618
+ if (typeof entry !== 'string' || entry.trim() === '') {
619
+ return { loadable: false, reason: 'unverifiable', resolved: null }
620
+ }
621
+ const value = entry.trim()
622
+ if (!looksLikePluginPath(value)) {
623
+ return { loadable: false, reason: 'npm-spec', resolved: null }
624
+ }
625
+ const resolved = isAbsolute(value) ? value : resolve(configDir, value)
626
+ if (!existsSync(resolved)) {
627
+ return { loadable: false, reason: 'missing', resolved }
628
+ }
629
+ try {
630
+ if (!statSync(resolved).isDirectory()) {
631
+ return { loadable: false, reason: 'file', resolved }
632
+ }
633
+ } catch {
634
+ return { loadable: false, reason: 'missing', resolved }
635
+ }
636
+ return { loadable: true, reason: 'directory', resolved }
637
+ }
638
+
639
+ /** Human explanation of a non-loadable entry, naming the exact failure mode. */
640
+ const V2_LOAD_FAILURES = {
641
+ 'npm-spec':
642
+ 'is a package/GitHub shorthand, which the V2 loader resolves through `npm install` and fails on (NpmInstallFailedError)',
643
+ file: 'is a file, and the V2 loader only accepts a directory containing index.ts ("must be a directory")',
644
+ missing:
645
+ 'does not exist, and the V2 loader only accepts an existing directory containing index.ts',
646
+ unverifiable:
647
+ 'is not a path this installer can verify, so it was left untouched rather than guessed at',
648
+ }
649
+
650
+ /** Render a plugin entry for a warning without ever printing a bare object. */
651
+ function describePluginEntry(entry) {
652
+ return typeof entry === 'string' ? entry : JSON.stringify(entry)
653
+ }
654
+
324
655
  const PANTHEON_V1_PLUGIN = 'src/plugin.ts'
325
656
  const PANTHEON_V1_HOOKS = 'src/plugins/pantheon-hooks.ts'
326
657
  // Canonical V2 entry is the plugin DIRECTORY (beta loader contract: entries
@@ -574,6 +905,249 @@ export function tuiConfigLocations(target) {
574
905
  return [...new Set([homeTui, xdgTui, projectTui])]
575
906
  }
576
907
 
908
+ /**
909
+ * V2 terminal-client config filename. V2 replaced the layered V1 `tui.json(c)`
910
+ * files with ONE GLOBAL client config (`~/.config/opencode/cli.json`); there is
911
+ * no project-local equivalent, so this file only ever lives in a config dir
912
+ * that is a global host config dir.
913
+ */
914
+ export const V2_CLI_CONFIG_FILENAME = 'cli.json'
915
+
916
+ /**
917
+ * Builtin V2 sidebar plugin that renders the Context block.
918
+ *
919
+ * Pantheon's TUI plugin renders its OWN Context block, so leaving the builtin
920
+ * enabled draws the block twice (nativo + nosso). The host cancels a plugin
921
+ * through an EXACT `-<id>` entry in the client config's `plugins` array; a
922
+ * wildcard (`-opencode.sidebar.*`) would also disable the mcp and footer blocks,
923
+ * so it is never used here.
924
+ */
925
+ export const CONTEXT_SIDEBAR_NEGATION = '-opencode.sidebar.context'
926
+
927
+ /**
928
+ * Bundle the V2 host loads from the copied TUI plugin dir (relative to it).
929
+ *
930
+ * The capability check below must read the bytes the host will ACTUALLY load,
931
+ * i.e. the copy under the config dir — never the in-package build artifact,
932
+ * which a package upgrade replaces independently of what was deployed.
933
+ */
934
+ export const TUI_V2_BUNDLE_RELATIVE_PATH = 'dist/tui-v2.js'
935
+
936
+ /**
937
+ * Stable marker proving the deployed TUI bundle renders Pantheon's own Context
938
+ * block.
939
+ *
940
+ * It is a named export of the bundle (`export { ..., contextBlockRows, ... }`).
941
+ * ESM export names are the module's public interface and CANNOT be mangled by
942
+ * tsdown/rolldown (or any minifier): mangling renames only non-exported
943
+ * bindings, because consumers resolve exports by name. The bundle also cannot
944
+ * tree-shake it away — the sidebar imports it, and
945
+ * `tests/tui-v2-sidebar.test.mjs` imports it from `dist/tui-v2.js`, so a build
946
+ * that drops the export fails the suite.
947
+ *
948
+ * A rebuild that changes the block's user-facing copy or internals keeps the
949
+ * export; only a rewrite that REMOVES the block drops it — which is exactly
950
+ * when the builtin Context block must stay enabled.
951
+ */
952
+ export const CONTEXT_BLOCK_BUNDLE_MARKER = 'contextBlockRows'
953
+
954
+ /**
955
+ * Path of the V2 TUI bundle inside an installed config dir.
956
+ *
957
+ * @param {string} configDir - OpenCode config directory
958
+ * @returns {string} absolute path of the copied `dist/tui-v2.js`
959
+ */
960
+ export function resolveInstalledTuiBundlePath(configDir) {
961
+ return join(resolveTuiCopyTarget(configDir), TUI_V2_BUNDLE_RELATIVE_PATH)
962
+ }
963
+
964
+ /**
965
+ * Pure capability test: does this bundle text provide Pantheon's Context block?
966
+ *
967
+ * Deliberately a plain byte scan: the answer must not depend on importing the
968
+ * bundle (the host API it needs is absent while installing).
969
+ *
970
+ * @param {unknown} bundleText - contents of the deployed `dist/tui-v2.js`
971
+ * @returns {{ ok: boolean, reason: string }} `reason` is empty when `ok`
972
+ */
973
+ export function bundleProvidesContextBlock(bundleText) {
974
+ if (typeof bundleText !== 'string') {
975
+ return { ok: false, reason: 'the TUI bundle could not be read as text' }
976
+ }
977
+ if (!new RegExp(`\\b${CONTEXT_BLOCK_BUNDLE_MARKER}\\b`).test(bundleText)) {
978
+ return {
979
+ ok: false,
980
+ reason:
981
+ `the deployed TUI bundle has no "${CONTEXT_BLOCK_BUNDLE_MARKER}" export, so it ` +
982
+ 'predates the Pantheon Context block',
983
+ }
984
+ }
985
+ return { ok: true, reason: '' }
986
+ }
987
+
988
+ /**
989
+ * Inspect the TUI bundle that the host will load for the given config dir.
990
+ *
991
+ * A dry run copies nothing, so it evaluates the in-package build artifact
992
+ * instead (what WOULD be deployed) and only falls back to an existing deployed
993
+ * copy — a preview must not report a capability failure that the real run
994
+ * would not have.
995
+ *
996
+ * @param {string} configDir - OpenCode config directory
997
+ * @param {object} [options]
998
+ * @param {boolean} [options.dryRun=false]
999
+ * @returns {{ ok: boolean, reason: string, bundlePath: string }}
1000
+ */
1001
+ export function inspectContextBlockCapability(configDir, { dryRun = false } = {}) {
1002
+ const installedPath = resolveInstalledTuiBundlePath(configDir)
1003
+ const sourcePath = join(ROOT, 'src', 'plugins', 'tui', TUI_V2_BUNDLE_RELATIVE_PATH)
1004
+ const bundlePath = dryRun && !existsSync(installedPath) ? sourcePath : installedPath
1005
+ let bundleText
1006
+ try {
1007
+ bundleText = readFileSync(bundlePath, 'utf8')
1008
+ } catch (cause) {
1009
+ return {
1010
+ ok: false,
1011
+ bundlePath,
1012
+ reason: `${bundlePath} is missing or unreadable (${cause.code ?? cause.message})`,
1013
+ }
1014
+ }
1015
+ return { ...bundleProvidesContextBlock(bundleText), bundlePath }
1016
+ }
1017
+
1018
+ /**
1019
+ * Remove {@link CONTEXT_SIDEBAR_NEGATION} from a V2 `plugins` array, preserving
1020
+ * every other entry and its order. Only the EXACT directive is removed: the
1021
+ * host honors nothing else, and a wildcard would also cancel the mcp and
1022
+ * footer blocks.
1023
+ *
1024
+ * Idempotent: an array without the directive is returned untouched.
1025
+ *
1026
+ * @param {unknown} plugins - current `plugins` value (may be absent or invalid)
1027
+ * @returns {{ plugins: unknown[], changed: boolean }}
1028
+ */
1029
+ export function withContextSidebarEnabled(plugins) {
1030
+ const current = Array.isArray(plugins) ? plugins : []
1031
+ const next = current.filter((entry) => entry !== CONTEXT_SIDEBAR_NEGATION)
1032
+ return { plugins: next, changed: next.length !== current.length }
1033
+ }
1034
+
1035
+ /**
1036
+ * Append {@link CONTEXT_SIDEBAR_NEGATION} to a V2 `plugins` array while
1037
+ * preserving every existing entry (plain strings and `{ package, options }`
1038
+ * objects) and their order.
1039
+ *
1040
+ * Idempotent: when the exact directive is already present the array is returned
1041
+ * untouched, so a second `init` never duplicates it.
1042
+ *
1043
+ * @param {unknown} plugins - current `plugins` value (may be absent or invalid)
1044
+ * @returns {{ plugins: unknown[], changed: boolean }}
1045
+ */
1046
+ export function withContextSidebarDisabled(plugins) {
1047
+ const current = Array.isArray(plugins) ? plugins : []
1048
+ if (current.includes(CONTEXT_SIDEBAR_NEGATION)) return { plugins: current, changed: false }
1049
+ return { plugins: [...current, CONTEXT_SIDEBAR_NEGATION], changed: true }
1050
+ }
1051
+
1052
+ /**
1053
+ * Reconcile the builtin Context sidebar block in the V2 terminal-client config
1054
+ * with the deployed TUI bundle.
1055
+ *
1056
+ * Cancelling the builtin block is only safe when the deployed bundle really
1057
+ * draws Pantheon's replacement (see {@link bundleProvidesContextBlock});
1058
+ * negating against a stale bundle removed the Context block from the sidebar
1059
+ * entirely. So the negation tracks the capability on EVERY run:
1060
+ *
1061
+ * capability present → add the exact negation (or leave it in place);
1062
+ * capability absent → remove a previously written negation, keeping the
1063
+ * native readout working, and warn with the reason and
1064
+ * the rebuild/redeploy step.
1065
+ *
1066
+ * Only the `plugins` array is merged; the rest of the user's `cli.json` (theme,
1067
+ * session, keybinds, anything else) is preserved verbatim, key order included,
1068
+ * and the write is skipped byte-for-byte when the array is already correct.
1069
+ * A file that cannot be parsed — or whose `plugins` is not an array — is NEVER
1070
+ * overwritten: the caller reports a warning and the install continues, because
1071
+ * clobbering a hand-edited client config is worse than a duplicated block.
1072
+ *
1073
+ * @param {string} configDir - config dir holding cli.json (global config dir)
1074
+ * @param {object} [options]
1075
+ * @param {boolean} [options.dryRun=false]
1076
+ * @param {(change: object) => void} [options.recorder=null] - preview recorder
1077
+ * @param {(message: string) => void} [options.warn] - warning sink
1078
+ * @param {{ ok: boolean, reason: string } | null} [options.capability=null]
1079
+ * pre-computed verdict (tests/preview); inspected from disk when omitted
1080
+ * @returns {'created'|'removed'|'skipped'|'unverified'|'invalid'|'conflict'}
1081
+ */
1082
+ export function applyContextSidebarNegation(
1083
+ configDir,
1084
+ { dryRun = false, recorder = null, warn = warning, capability = null } = {},
1085
+ ) {
1086
+ const cliConfigPath = join(configDir, V2_CLI_CONFIG_FILENAME)
1087
+ let config = {}
1088
+ let raw = null
1089
+ if (existsSync(cliConfigPath)) {
1090
+ raw = readFileSync(cliConfigPath, 'utf8')
1091
+ try {
1092
+ config = JSON.parse(raw)
1093
+ } catch {
1094
+ warn(
1095
+ `Left ${cliConfigPath} untouched: it is not valid JSON, so the builtin Context ` +
1096
+ 'sidebar block stays enabled (it may render twice alongside the Pantheon block).',
1097
+ )
1098
+ return 'invalid'
1099
+ }
1100
+ }
1101
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) {
1102
+ warn(`Left ${cliConfigPath} untouched: expected a JSON object at the top level.`)
1103
+ return 'invalid'
1104
+ }
1105
+ if (config.plugins !== undefined && !Array.isArray(config.plugins)) {
1106
+ // Never replace a value we do not understand: the user may have written it
1107
+ // by hand in a shape a future host accepts.
1108
+ warn(`Left ${cliConfigPath} untouched: its "plugins" value is not an array.`)
1109
+ return 'invalid'
1110
+ }
1111
+
1112
+ // The host only honours the exact directive, so `next` never invents one.
1113
+ const verdict = capability ?? inspectContextBlockCapability(configDir, { dryRun })
1114
+ const next = verdict.ok
1115
+ ? withContextSidebarDisabled(config.plugins)
1116
+ : withContextSidebarEnabled(config.plugins)
1117
+ const removing = !verdict.ok && next.changed
1118
+
1119
+ if (!verdict.ok) {
1120
+ // A silent negation here is the bug this check exists for: the native
1121
+ // readout disappears and nothing replaces it.
1122
+ warn(
1123
+ `Builtin Context sidebar block left ENABLED: ${verdict.reason}. ` +
1124
+ (removing
1125
+ ? `Removed ${CONTEXT_SIDEBAR_NEGATION} from ${cliConfigPath} so the native block ` +
1126
+ 'keeps rendering. '
1127
+ : '') +
1128
+ 'Rebuild the TUI bundle (npm run build --prefix src/plugins/tui) and redeploy ' +
1129
+ 'pantheon-tui, then re-run init to de-duplicate the Context block.',
1130
+ )
1131
+ }
1132
+ if (!next.changed) return verdict.ok ? 'skipped' : 'unverified'
1133
+ config.plugins = next.plugins
1134
+
1135
+ const content = `${JSON.stringify(config, null, 2)}\n`
1136
+ const status = writeConfigWithBackup(cliConfigPath, content, dryRun, {
1137
+ expectedContent: raw,
1138
+ recorder,
1139
+ })
1140
+ if (status === 'conflict') {
1141
+ warn(
1142
+ `Left ${cliConfigPath} untouched: it changed on disk during the install. ` +
1143
+ 'Re-run init to disable the builtin Context sidebar block.',
1144
+ )
1145
+ return 'conflict'
1146
+ }
1147
+ if (status !== 'created') return 'skipped'
1148
+ return removing ? 'removed' : 'created'
1149
+ }
1150
+
577
1151
  /**
578
1152
  * Sync the Pantheon TUI plugin payload and V1 registration. V2 discovers the
579
1153
  * copied local-plugin entrypoints and does not use a project tui.json.
@@ -594,11 +1168,19 @@ export function tuiConfigLocations(target) {
594
1168
  * @param {object} [opts]
595
1169
  * @param {boolean} [opts.isGlobal=false] - flat global layout vs .opencode/
596
1170
  * @param {boolean} [opts.dryRun=false]
1171
+ * @param {(change: object) => void} [opts.recorder] - optional change recorder for preview
597
1172
  * @returns {'created'|'skipped'} status for the target registration
598
1173
  */
599
1174
  export function syncTuiRegistration(
600
1175
  target,
601
- { isGlobal = false, dryRun = false, version = 'v1' } = {},
1176
+ {
1177
+ isGlobal = false,
1178
+ dryRun = false,
1179
+ version = 'v1',
1180
+ recorder = null,
1181
+ reviewedRemovals = null,
1182
+ reviewedSnapshots = null,
1183
+ } = {},
602
1184
  ) {
603
1185
  const configDir = isGlobal ? target : join(target, '.opencode')
604
1186
  const targetTuiConfigPath = join(configDir, 'tui.json')
@@ -607,8 +1189,26 @@ export function syncTuiRegistration(
607
1189
  // plugins/pantheon-tui. This keeps the installed entry hermetic.
608
1190
  const tuiSrcDir = join(ROOT, 'src', 'plugins', 'tui')
609
1191
  const tuiCopyDir = resolveTuiCopyTarget(configDir)
610
- if (existsSync(tuiSrcDir)) {
611
- copyPluginFiles(tuiSrcDir, tuiCopyDir, { dryRun, version })
1192
+ // Fail closed: silently skipping the copy left `plugins` "installed" with no
1193
+ // payload — the host then loads a tui.json entry that points at nothing.
1194
+ if (!existsSync(tuiSrcDir)) {
1195
+ throw new Error(
1196
+ `Pantheon TUI plugin source not found: ${tuiSrcDir}. The package payload is ` +
1197
+ 'incomplete — reinstall pantheon-opencode (the published tarball must ship ' +
1198
+ 'src/plugins/tui), then re-run init.',
1199
+ )
1200
+ }
1201
+ const copyResult = copyPluginFiles(tuiSrcDir, tuiCopyDir, {
1202
+ dryRun,
1203
+ version,
1204
+ recorder,
1205
+ reviewedRemovals,
1206
+ reviewedSnapshots,
1207
+ })
1208
+ if (copyResult.errors > 0) {
1209
+ throw new Error(
1210
+ `${copyResult.problems[0] ?? `TUI plugin payload could not be copied to ${tuiCopyDir}.`}`,
1211
+ )
612
1212
  }
613
1213
 
614
1214
  // 2. Clean stale Pantheon TUI refs from every location OpenCode reads.
@@ -621,6 +1221,7 @@ export function syncTuiRegistration(
621
1221
  unregisterPlugin(tuiConfigPath, 'plugins/pantheon-tui', {
622
1222
  dryRun,
623
1223
  knownPantheonPaths: [ownedCopy, tuiCopyDir],
1224
+ recorder,
624
1225
  })
625
1226
  }
626
1227
 
@@ -630,7 +1231,7 @@ export function syncTuiRegistration(
630
1231
  if (version === 'v2') return 'skipped'
631
1232
 
632
1233
  // 3. Register the copied directory in the selected target only.
633
- return registerPlugin(targetTuiConfigPath, tuiCopyDir, { dryRun })
1234
+ return registerPlugin(targetTuiConfigPath, tuiCopyDir, { dryRun, recorder })
634
1235
  }
635
1236
 
636
1237
  /**
@@ -639,32 +1240,79 @@ export function syncTuiRegistration(
639
1240
  * MCP entries from the config (entries pointing at a missing venv would
640
1241
  * make every MCP fail to launch). `deps` is injectable for tests.
641
1242
  */
642
- export function setupRuntimePhase(target, { dryRun, clean, isGlobal }, stats, deps = {}) {
1243
+ export function setupRuntimePhase(
1244
+ target,
1245
+ {
1246
+ dryRun,
1247
+ clean,
1248
+ isGlobal,
1249
+ recorder = null,
1250
+ reviewedRemovals = null,
1251
+ reviewedSnapshots = null,
1252
+ onVenvDone = null,
1253
+ onHealthDone = null,
1254
+ },
1255
+ stats,
1256
+ deps = {},
1257
+ ) {
643
1258
  const S = strings()
644
1259
  const setup = deps.setupVenv ?? setupVenv
645
1260
  const check = deps.healthCheck ?? healthCheck
1261
+ let stopProgress
646
1262
  try {
647
- const venvSpinner = spinner(S.settingUpRuntime)
648
- setup(target, { dryRun, force: clean })
649
- venvSpinner(true)
1263
+ stopProgress = spinner(S.settingUpRuntime)
1264
+ try {
1265
+ setup(target, {
1266
+ dryRun,
1267
+ force: clean,
1268
+ recorder,
1269
+ reviewedRemovals,
1270
+ reviewedSnapshots,
1271
+ })
1272
+ } finally {
1273
+ // Count the phase even when setup throws: it DID run (and failed). The
1274
+ // failure is reported below as a warning, not as a missing phase.
1275
+ onVenvDone?.()
1276
+ }
1277
+ stopProgress(true)
1278
+ stopProgress = null
1279
+
1280
+ // A dry run creates no venv and installs no dependencies, so there is
1281
+ // nothing to verify yet. Running the health check here reported the
1282
+ // PRE-install target as broken and flipped runtimeHealthy=false, which
1283
+ // silently dropped every MCP entry from the previewed plan while the real
1284
+ // apply wrote them. Say what will happen instead of probing.
1285
+ if (dryRun) {
1286
+ info(S.runtimeVerifiedAfterApply)
1287
+ return true
1288
+ }
1289
+
650
1290
  const runtimeTarget = isGlobal ? target : join(target, '.opencode')
651
- const health = check(runtimeTarget, { dryRun, pythonTarget: target })
1291
+ let health
1292
+ try {
1293
+ health = check(runtimeTarget, { dryRun, pythonTarget: target })
1294
+ } finally {
1295
+ onHealthDone?.()
1296
+ }
652
1297
 
653
- section(`\uD83D\uDD0D ${S.healthSection}`)
654
- const healthStep = step(S.runningHealthChecks)
1298
+ section(S.healthSection)
1299
+ stopProgress = step(S.runningHealthChecks)
655
1300
  for (const p of health.passed) success(`${p.check}: ${p.detail}`)
656
1301
  for (const w of health.warnings) warning(`${w.check}: ${w.detail}`)
657
1302
  for (const f of health.failed) error(`${f.check}: ${f.detail}`)
658
1303
 
659
1304
  if (health.failed.length > 0) {
660
- healthStep(false)
1305
+ stopProgress(false)
1306
+ stopProgress = null
661
1307
  warning(`${health.failed.length} check(s) failed — review above`)
662
1308
  stats.warnings += health.failed.length
663
1309
  return false
664
1310
  }
665
- healthStep(true)
1311
+ stopProgress(true)
1312
+ stopProgress = null
666
1313
  return true
667
1314
  } catch (err) {
1315
+ stopProgress?.(false)
668
1316
  error(S.runtimeFailed(err.message))
669
1317
  warning(S.runtimeSkippedMcp)
670
1318
  stats.warnings += 1
@@ -683,10 +1331,13 @@ export function setupRuntimePhase(target, { dryRun, clean, isGlobal }, stats, de
683
1331
  * config in place — the migration that makes the rename non-breaking.
684
1332
  *
685
1333
  * @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
1334
+ * @param {{ runtimeTarget: string, venvPython: string, version?: 'v1' | 'v2' }} ctx
1335
+ * @returns {{ healed: number, warnings: string[], servers: string[] }} number of
1336
+ * stale path strings rewritten, one warning per MCP permission the host
1337
+ * cannot enforce, and the server names this call actually seeded (write
1338
+ * order) — the dry-run preview reports exactly these
688
1339
  */
689
- export function applyMcpServerEntries(config, { runtimeTarget, venvPython }) {
1340
+ export function applyMcpServerEntries(config, { runtimeTarget, venvPython, version = 'v2' }) {
690
1341
  config.mcp = config.mcp || {}
691
1342
  // MCP stays a flat named-server map for BOTH V1 and V2: OpenCode 1.18.x has
692
1343
  // no `mcp.servers` wrapper and rejects one with "Missing key
@@ -694,49 +1345,29 @@ export function applyMcpServerEntries(config, { runtimeTarget, venvPython }) {
694
1345
  // wrapper-shaped entries back to the flat map.
695
1346
  const healed = migrateMcpEntrypointPaths(config.mcp)
696
1347
 
697
- // Only add if not already configured by user
698
- if (!config.mcp['pantheon-resources']) {
699
- config.mcp['pantheon-resources'] = {
1348
+ // Only add if not already configured by user.
1349
+ const servers = []
1350
+ for (const entry of PANTHEON_MCP_SERVER_ENTRIES) {
1351
+ if (config.mcp[entry.name]) continue
1352
+ config.mcp[entry.name] = {
700
1353
  type: 'local',
701
1354
  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'] = {
724
- type: 'local',
725
- 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'],
1355
+ command: [venvPython, entry.script],
735
1356
  enabled: true,
736
1357
  }
1358
+ servers.push(entry.name)
737
1359
  }
738
1360
 
739
- // Default MCP permissions
1361
+ // Default MCP permissions.
1362
+ //
1363
+ // WARNING: on OpenCode 2.x, `permission.mcp.<server>` is NOT enforced. The
1364
+ // host evaluates an MCP call as the action `<server>_<tool>` with resources
1365
+ // ["*"]; `permission.mcp.<server>` and `action:"mcp"` are inert (measured on
1366
+ // 2.0.29–2.1.3). These defaults are kept for V1 compatibility, but `ask` does
1367
+ // not prompt and `allow` grants nothing it did not already have — every `ask`
1368
+ // server below is reported to the user as unenforced. The enforceable form is
1369
+ // `{ action: "<server>_*", resource: "*", effect: "deny" }`; `ask` there
1370
+ // HIDES the tool instead of asking, so it is never emitted as a default.
740
1371
  config.permission = config.permission || {}
741
1372
  config.permission.mcp = config.permission.mcp || {}
742
1373
  if (!config.permission.mcp['pantheon-resources']) {
@@ -755,56 +1386,228 @@ export function applyMcpServerEntries(config, { runtimeTarget, venvPython }) {
755
1386
  config.permission.mcp['pantheon-vision'] = 'ask'
756
1387
  }
757
1388
 
758
- return { healed }
1389
+ // Report every `ask` entry, whether just seeded or left by a previous
1390
+ // install: the config claims a gate the host does not apply. V1's MCP
1391
+ // permission semantics were not measured, so the warning is V2-only.
1392
+ const S = strings()
1393
+ const warnings =
1394
+ version === 'v2'
1395
+ ? Object.entries(config.permission.mcp)
1396
+ .filter(([, effect]) => effect === 'ask')
1397
+ .map(([server]) => S.mcpAskNotEnforceable(server))
1398
+ : []
1399
+
1400
+ return { healed, warnings, servers }
1401
+ }
1402
+
1403
+ /**
1404
+ * Phase 4 drift detection: the planned targets whose on-disk state changed
1405
+ * between the plan pass (snapshots) and the apply pass. A path counts as drifted
1406
+ * when its existence, content hash, size, or mode differs — which includes a
1407
+ * planned-NEW path that now exists. Returns the absolute paths (empty = no
1408
+ * drift); callers print only these paths, never contents or hashes.
1409
+ */
1410
+ function detectSnapshotDrift(snapshots) {
1411
+ if (!Array.isArray(snapshots)) return []
1412
+ const changed = []
1413
+ for (const before of snapshots) {
1414
+ const now = snapshot(before.path)
1415
+ if (
1416
+ now.exists !== before.exists ||
1417
+ now.sha256 !== before.sha256 ||
1418
+ now.size !== before.size ||
1419
+ now.mode !== before.mode
1420
+ ) {
1421
+ changed.push(before.path)
1422
+ }
1423
+ }
1424
+ return changed
759
1425
  }
760
1426
 
1427
+ /**
1428
+ * Phase 5 failure semantics. `installPass` is the whole installer; this thin
1429
+ * wrapper reports a mid-apply failure HONESTLY: it aborts the remaining writes
1430
+ * (the throw), relies on each writer to clean up only its own temporary file,
1431
+ * reports the PATHS already applied (never contents), prints the recovery
1432
+ * path, and re-throws so the CLI exits non-zero. There is NO automatic rollback — the
1433
+ * exact backup set + `pantheon-opencode restore` is the recovery.
1434
+ *
1435
+ * Progress is tracked in `_lastRun` (set only by a non-dry pass, so the nested
1436
+ * dry plan pass never clobbers it). The RESOLVED target is read back from
1437
+ * `_lastRun.target` so the report and the sweep work when the caller passed
1438
+ * `undefined` (the default global install resolves to `~/.config/opencode`).
1439
+ */
1440
+ let _lastRun = null
1441
+ // The gauge of the install currently running (never the nested plan pass), so
1442
+ // an exception can close it with `✖ reason` instead of leaving a half line.
1443
+ let _activeGauge = null
1444
+
761
1445
  export async function installOpenCode(
762
1446
  target,
763
1447
  dryRun = false,
764
1448
  clean = false,
765
1449
  components = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime'],
766
1450
  opts = {},
1451
+ ) {
1452
+ // Reset per-call so a stale run can never leak into a fresh failure report.
1453
+ if (!dryRun) _lastRun = null
1454
+ // The installer is a PROGRESS surface: the gauge replaces per-step logs
1455
+ // unless --verbose asks for them back. Doctor and the other CLIs never set
1456
+ // verbose, so their output is untouched; restore it on the way out.
1457
+ const previousUi = configure({ verbose: opts.verbose === true })
1458
+ try {
1459
+ return await installPass(target, dryRun, clean, components, opts)
1460
+ } catch (err) {
1461
+ _activeGauge?.fail(err instanceof Error ? err.message : String(err))
1462
+ const run = dryRun ? null : _lastRun
1463
+ if (run) {
1464
+ const S = strings()
1465
+ const paths = summarizeChanges(run.entries ?? [])
1466
+ .files.filter((f) => f.action !== ACTIONS.UNCHANGED && f.action !== ACTIONS.CONFLICT)
1467
+ .map((f) => displayPath(run.target, f.path))
1468
+ error(S.applyFailed(err instanceof Error ? err.message : String(err)))
1469
+ if (paths.length > 0) {
1470
+ warning(S.alreadyApplied)
1471
+ for (const p of paths) warning(` ${p}`)
1472
+ }
1473
+ warning(run.backupDir ? S.restoreRecoveryHint(run.backupDir) : S.restoreNoBackup)
1474
+ }
1475
+ throw err
1476
+ } finally {
1477
+ // An early return (canceled/declined preview) leaves the gauge mid-line on
1478
+ // a TTY; clear it without claiming completion. `done()`/`fail()` already
1479
+ // set `finished`, so this is a no-op on every normal path.
1480
+ if (_activeGauge && !_activeGauge.finished) _activeGauge.cancel()
1481
+ _activeGauge = null
1482
+ configure(previousUi)
1483
+ }
1484
+ }
1485
+
1486
+ async function installPass(
1487
+ target,
1488
+ dryRun = false,
1489
+ clean = false,
1490
+ components = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime'],
1491
+ opts = {},
767
1492
  ) {
768
1493
  // Default target if not provided (global ~/.config/opencode)
769
1494
  if (!target) {
770
1495
  target = join(homedir(), '.config', 'opencode')
771
1496
  }
772
1497
 
773
- const componentSet = new Set(components)
1498
+ const componentSet = new Set(
1499
+ opts.noMcp ? components.filter((component) => component !== 'runtime') : components,
1500
+ )
774
1501
  const stats = summary.opencode
1502
+ // Per-call baseline. `stats` is the module-level cumulative summary, so the
1503
+ // consistency guard must compare against THIS call's delta, not the total.
1504
+ const statsBefore = { created: stats.created, skipped: stats.skipped }
1505
+ // Number of planned changes, filled by a dry plan pass (used by the gate).
1506
+ let plannedChanges = 0
1507
+ let planFiles = []
1508
+ let planTotals = null
1509
+ let removalPaths = []
1510
+ // MCP servers this pass seeds into opencode.json, in write order. Filled by
1511
+ // applyMcpServerEntries so the preview names exactly what the apply writes.
1512
+ let mcpServers = []
1513
+ const planTimestamp = opts.planTimestamp ?? new Date().toISOString()
1514
+ let projectedState = null
1515
+ // Phase 4: planned-target snapshots from the plan pass, used for drift checks.
1516
+ let plannedSnapshots = null
1517
+ let reviewedRemovals = null
1518
+ let reviewedSnapshots = null
775
1519
  const S = strings()
776
1520
 
1521
+ // Configure the UI channel BEFORE any output: the version resolver below
1522
+ // warns when a dry run skips the host probe, and a quiet preview (doctor's
1523
+ // internal preflight, --json) must not print it. Quiet used to be applied
1524
+ // much later, so that one warning escaped every silent preview.
1525
+ configure({ dryRun, quiet: opts.quiet === true })
1526
+
1527
+ // Beta 11 (Setup phase 1): a dry pass records every writer's intended change
1528
+ // so we can print the REAL per-file plan without writing anything. A recorder
1529
+ // ALWAYS runs now: a dry pass builds the preview/plan from it, and an apply
1530
+ // pass uses it to report which PATHS were already written if a writer throws
1531
+ // (Phase 5 failure semantics). The default is the module-level no-op recorder,
1532
+ // so an uninstrumented caller stays byte-identical.
1533
+ const ownRecorder = opts.recorder ? null : createRecorder()
1534
+ const preview = dryRun && ownRecorder ? ownRecorder : null
1535
+ let recorder = opts.recorder ?? ownRecorder.recorder
1536
+ // Test-only failure seam: throw after N recorded writes so the failure path is
1537
+ // deterministic. Never reachable from production callers (opts.deps is not a
1538
+ // CLI flag) and never applied to the internal dry plan pass.
1539
+ if (!dryRun && typeof opts.deps?.failAfter === 'number') {
1540
+ const base = recorder
1541
+ const limit = opts.deps.failAfter
1542
+ let applied = 0
1543
+ recorder = (change) => {
1544
+ base(change)
1545
+ if (++applied >= limit) throw new Error('injected failure (test-only failAfter seam)')
1546
+ }
1547
+ }
1548
+ // Track this apply so the wrapper can report the paths written on a failure.
1549
+ if (!dryRun) _lastRun = { target, entries: ownRecorder?.entries ?? [], backupDir: null }
1550
+
777
1551
  // V1/V2 dual-version awareness (Phase 3): the installer builds a unified
778
1552
  // config, then applies V2-native migration (migrateV1toV2) when
779
- // --opencode-version=v2. V2 normalizes V1 fields in memory (no rewrite) and
780
- // isolates its state DB via OPENCODE_DB (~/.local/share/opencode/opencode-v2.db)
781
- // with a distinct service port (49375 vs V1's 49374).
1553
+ // --opencode-version=v2. V2 normalizes V1 fields in memory (no rewrite).
1554
+ // Neither generation isolates state: both read the same OpenCode store, so
1555
+ // the V2 notice reports the path an actual resolver returns instead of a
1556
+ // literal, and claims no service port because nothing binds one.
782
1557
  // Default to 'auto' so a flagless run resolves against the actual host. A
783
1558
  // hardcoded 'v1' here (or in bin/pantheon-init.mjs) is what shipped the bug:
784
1559
  // the V1 branch writes .ts file paths that a 2.x host drops from the config.
785
1560
  // `opts` is forwarded as the resolver's options bag so a caller (and CI) can
786
1561
  // pin env/probe instead of spawning a real host binary.
787
- const version = resolveOpenCodeVersion(opts.version ?? 'auto', opts)
788
- if (version === 'v2') {
789
- info(
790
- 'OpenCode V2 target — shared config; state isolated via OPENCODE_DB ' +
791
- '(~/.local/share/opencode/opencode-v2.db), service port 49375',
792
- )
793
- // Say what the V2 contract does NOT give you, at the moment the user picks
794
- // it. The V2 surface is 3 tools (hashline_edit, pantheon_cost,
795
- // pantheon_model); V1's is 6 plus the BackgroundJobBoard, the three goal
796
- // tools and the caller/target delegation matrix. This list was previously
797
- // reachable only through `getUnsupportedFeatures()`, which no production
798
- // code called — a user migrating hit the reduction with no warning at all.
799
- //
800
- // The markers are read from the same seed `getUnsupportedFeatures()` is
801
- // built from (src/pantheon/v2-unsupported.mjs), so this notice cannot drift
802
- // from what the plugin reports. Advisory: a V2 install is a supported
803
- // configuration, not a failure.
804
- info(
805
- `V2 plugin generation — reduced surface. Unsupported features: ${listV2UnsupportedFeatures().join(', ')}`,
1562
+ //
1563
+ // A DRY RUN probes the host too. It used to pass `skipProbe` and assume V1,
1564
+ // so `init --dry-run` on a 2.x host previewed the V1 plan (target `tui.json`,
1565
+ // removed `index.ts`) while the apply wrote `index.ts` and no `tui.json` —
1566
+ // a preview that contradicted the apply. The probe runs in a throwaway state
1567
+ // directory, and the dry run bounds it with the shorter
1568
+ // DRY_RUN_PROBE_TIMEOUT_MS so a hanging host cannot stall a preview. When the
1569
+ // probe still fails, V1 is assumed and `versionAssumed` marks the plan as
1570
+ // such (text + --json).
1571
+ let versionFallback = null
1572
+ const version = resolveOpenCodeVersion(opts.version ?? 'auto', {
1573
+ ...opts,
1574
+ probeTimeoutMs: dryRun ? DRY_RUN_PROBE_TIMEOUT_MS : undefined,
1575
+ onFallback: (reason) => {
1576
+ versionFallback = reason
1577
+ },
1578
+ })
1579
+ if (version === 'v2' && opts.preset) {
1580
+ throw new Error(
1581
+ '--preset is not supported for OpenCode V2 because V2 ignores the legacy active-preset marker. ' +
1582
+ 'Configure models using V2-native OpenCode configuration instead.',
806
1583
  )
807
1584
  }
1585
+ const versionAssumed = dryRun && versionFallback !== null
1586
+ // Both V2 notices belong to the run the USER started, not to the internal
1587
+ // plan pass the gate spawns. That pass runs with the same output channel, so
1588
+ // an ungated notice printed twice on the unauthorized-preview path (`init`
1589
+ // without --yes: plan pass, then the outer apply pass, both loud). The
1590
+ // sibling `warning()` for a sibling opencode.jsonc is gated the same way;
1591
+ // a real --dry-run is not a plan pass, so it still prints them once.
1592
+ if (version === 'v2' && !opts.planOnly) {
1593
+ // The notice states only what this installer actually does and what the
1594
+ // host actually reads. It previously claimed an isolated state database and
1595
+ // a dedicated service port: nothing in this package sets OPENCODE_DB, no
1596
+ // install creates a per-generation file, nothing binds that port, and the
1597
+ // repo's own database consumer documents the opposite
1598
+ // (src/pantheon/cost-command.ts). The path below comes from the shared
1599
+ // resolver, so the sentence cannot drift from the code.
1600
+ notice(`OpenCode V2 target — ${describeSharedState()}`)
1601
+ // Say what the V2 contract gives you AND what it does not, at the moment
1602
+ // the user picks it. "Reduced surface" alone is misleading in both
1603
+ // directions: V2 registers real hooks, transforms and events, and it also
1604
+ // drops the goal tools. The not-registered half is the same SEED
1605
+ // `getUnsupportedFeatures()` is built from (imported, never restated), so
1606
+ // this notice cannot drift from what the plugin reports; the notice says
1607
+ // so, because the live list is a superset that grows at runtime. Advisory:
1608
+ // a V2 install is a supported configuration, not a failure.
1609
+ notice(formatV2CapabilityNotice())
1610
+ }
808
1611
 
809
1612
  // Interactive mode handling
810
1613
  const stdinTTY = process.stdin.isTTY && process.stdout.isTTY
@@ -815,24 +1618,65 @@ export async function installOpenCode(
815
1618
 
816
1619
  if (interactive && !dryRun) {
817
1620
  const { runInteractiveInstall } = await import('./interactive.mjs')
1621
+ const hasRequestedComponents = Array.isArray(opts.requestedComponents)
1622
+ const promptComponents = hasRequestedComponents ? opts.requestedComponents : components
1623
+ const promptDefaults = hasRequestedComponents
1624
+ ? []
1625
+ : opts.noMcp
1626
+ ? COMPONENT_NAMES.filter((component) => component !== 'runtime')
1627
+ : COMPONENT_NAMES
818
1628
  const result = await runInteractiveInstall({
819
- components,
820
- defaultComponents: COMPONENT_NAMES,
1629
+ components: promptComponents,
1630
+ defaultComponents: promptDefaults,
1631
+ noMcp: opts.noMcp === true,
1632
+ prompts: opts.deps?.prompts,
1633
+ isTTY: opts.deps?.isTTY,
821
1634
  })
822
1635
 
823
- if (!result.confirmed && !autoYes) {
824
- info('Installation canceled.')
825
- return stats
1636
+ // Resolve the location from the SELECTION before any cancel return: a
1637
+ // cancel after the user picked "Current project" must record that
1638
+ // directory, not the global default the caller would fall back to. The
1639
+ // recorded target is where the user was installing, not where a file was
1640
+ // written (nothing was written either way).
1641
+ const selectedTarget = result.target === 'project' ? process.cwd() : target
1642
+
1643
+ if (result.canceled) {
1644
+ // The named point is what makes the message explainable. The interactive
1645
+ // module already printed the single cancel line through the prompt
1646
+ // library's own cancel channel, so printing another one here was the
1647
+ // duplicate the issue reports: the user saw the same sentence twice and
1648
+ // learned nothing about WHERE it stopped.
1649
+ return {
1650
+ ...stats,
1651
+ applied: false,
1652
+ reason: 'canceled',
1653
+ cancelPoint: result.cancelPoint ?? 'components',
1654
+ target: selectedTarget,
1655
+ }
1656
+ }
1657
+
1658
+ if (!result.confirmed) {
1659
+ // Answering "No" at the pre-install confirmation is not the prompt
1660
+ // library's cancel channel, so nothing was printed yet: this is the one
1661
+ // message, and it names the point.
1662
+ notice(S.canceledAt(S.cancelPoints.confirmation))
1663
+ return {
1664
+ ...stats,
1665
+ applied: false,
1666
+ reason: 'canceled',
1667
+ cancelPoint: 'confirmation',
1668
+ target: selectedTarget,
1669
+ }
826
1670
  }
827
1671
 
828
1672
  // Map target selection to actual path
829
- const newComponents = [...result.components]
1673
+ const newComponents = [...result.components].filter(
1674
+ (component) => !opts.noMcp || component !== 'runtime',
1675
+ )
830
1676
  componentSet.clear()
831
1677
  for (const c of newComponents) componentSet.add(c)
832
1678
 
833
- if (result.target === 'project') {
834
- target = process.cwd()
835
- }
1679
+ target = selectedTarget
836
1680
  }
837
1681
 
838
1682
  // Product defaults live in code (PRODUCT_CONFIG_DEFAULTS). A repository-root
@@ -848,6 +1692,25 @@ export async function installOpenCode(
848
1692
  const pantheonConfigPath =
849
1693
  typeof mergeDevConfigOpt === 'string' ? resolve(mergeDevConfigOpt) : null
850
1694
  const targetConfigPath = join(target, 'opencode.json')
1695
+ // The installer reads and writes ONLY `opencode.json`, but the V2 host also
1696
+ // loads a sibling `opencode.jsonc` and unions arrays from both. A Pantheon
1697
+ // entry there is invisible to this installer, so a "second config" is a real
1698
+ // ambiguity the user has to resolve — name it instead of leaving the two
1699
+ // files to disagree silently.
1700
+ const siblingJsonc = join(target, 'opencode.jsonc')
1701
+ const configAdvisories = []
1702
+ if (version === 'v2' && existsSync(siblingJsonc)) {
1703
+ configAdvisories.push(
1704
+ `Both ${targetConfigPath} and ${siblingJsonc} exist and an OpenCode V2 host merges ` +
1705
+ 'them (scalars from the .jsonc win, arrays are unioned). The installer reads and ' +
1706
+ 'writes only opencode.json, so anything plugin-related in the .jsonc — including a ' +
1707
+ 'Pantheon entry — is neither seen nor changed by this install. Move those entries ' +
1708
+ 'into opencode.json and delete the .jsonc, or edit both by hand.',
1709
+ )
1710
+ // The internal plan pass is not a user-facing report; the apply pass (and a
1711
+ // real --dry-run) prints it once.
1712
+ if (!opts.planOnly) warning(configAdvisories[0])
1713
+ }
851
1714
  const { config, raw: configRaw } = readJsonConfigWithRaw(targetConfigPath)
852
1715
  const pantheonConfig =
853
1716
  pantheonConfigPath !== null && existsSync(pantheonConfigPath)
@@ -869,11 +1732,208 @@ export async function installOpenCode(
869
1732
  // active config directory is the project root and its agent loader scans
870
1733
  // <config-dir>/{agent,agents}/**, so V2 project agents must be at ./agents.
871
1734
  // Global installs are flat for both versions.
872
- const isGlobal = isGlobalConfigDir(target)
1735
+ const isGlobal = opts.global ?? isGlobalConfigDir(target)
873
1736
  const _subDir = isGlobal ? '' : '.opencode'
874
1737
  const agentPrefix = isGlobal || version === 'v2' ? 'agents' : '.opencode/agents'
875
1738
 
876
- configure({ dryRun })
1739
+ // -----------------------------------------------------------------------
1740
+ // Plan pass + apply gate + drift check (Beta 11 Setup phases 3-4).
1741
+ // * the plan pass (a dry run — writes nothing) prints the plan and
1742
+ // snapshots every planned target;
1743
+ // * applying requires explicit authorization (Phase 3): a declined or
1744
+ // unauthorized run writes NOTHING;
1745
+ // * drift (Phase 4) aborts BEFORE any write if a planned target changed
1746
+ // between the plan pass and now.
1747
+ // A result with `applied: false` means the caller must not print success.
1748
+ // -----------------------------------------------------------------------
1749
+ const applyRequested = !dryRun
1750
+ if (applyRequested) {
1751
+ const savedStats = { ...stats }
1752
+ let planned
1753
+ try {
1754
+ // Use the LIVE selection: the wizard above may have changed componentSet.
1755
+ // An AUTHORIZED apply (`--yes`) is not a preview: compute the plan +
1756
+ // snapshots but stay silent. The gate path (no `--yes`) still prints the
1757
+ // plan for the review / decline preview.
1758
+ planned = await installOpenCode(target, true, clean, [...componentSet], {
1759
+ ...opts,
1760
+ // Hand the RESOLVED generation to the plan pass. Re-resolving would
1761
+ // probe the host a second time and could land on a different answer
1762
+ // (a transient probe failure), making the plan disagree with the
1763
+ // apply it is about to authorize.
1764
+ version,
1765
+ planTimestamp,
1766
+ planOnly: true,
1767
+ quiet: autoYes,
1768
+ quietPlan: autoYes,
1769
+ })
1770
+ } finally {
1771
+ Object.assign(stats, savedStats)
1772
+ // The plan pass left the UI in dry-run mode; restore this run's mode.
1773
+ configure({ dryRun, quiet: opts.quiet === true })
1774
+ }
1775
+ plannedSnapshots = planned?.snapshots ?? null
1776
+
1777
+ if (opts.expectedPlan) {
1778
+ const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
1779
+ const drift = findPlanDrift(opts.expectedPlan, {
1780
+ target,
1781
+ packageRoot: ROOT,
1782
+ packageVersion,
1783
+ files: planned?.files ?? [],
1784
+ snapshots: planned?.snapshots ?? [],
1785
+ })
1786
+ if (drift.length > 0) {
1787
+ warning('Reviewed install plan drifted; no files were written.')
1788
+ for (const item of drift) warning(` ${item}`)
1789
+ return { ...stats, applied: false, reason: 'drift', drift }
1790
+ }
1791
+ }
1792
+
1793
+ if (!autoYes) {
1794
+ const injected = opts.deps?.promptReview
1795
+ const canPrompt = typeof injected === 'function' || interactive
1796
+ if (canPrompt) {
1797
+ const { promptReview } = await import('./interactive.mjs')
1798
+ const ask = typeof injected === 'function' ? injected : promptReview
1799
+ const accepted = await ask(`Apply these ${planned?.planned ?? 0} changes?`, {
1800
+ default: false,
1801
+ prompts: opts.deps?.prompts,
1802
+ isTTY: opts.deps?.isTTY,
1803
+ })
1804
+ if (accepted === PROMPT_CANCELED) {
1805
+ // The real prompt already printed the one cancel line through clack's
1806
+ // own cancel channel. An INJECTED reviewer (tests, other callers)
1807
+ // prints nothing, so this is the single place that guarantees the
1808
+ // message exists exactly once, and it names the point.
1809
+ if (typeof injected === 'function') notice(S.canceledAt(S.cancelPoints.review))
1810
+ return { ...stats, applied: false, reason: 'canceled', cancelPoint: 'review' }
1811
+ }
1812
+ if (!accepted) {
1813
+ // Answering "No" is not a cancel: it used to reach the caller as a
1814
+ // silent `reason: 'declined'` and exit 0 with "Nothing applied." and
1815
+ // no explanation at all.
1816
+ notice(S.declinedAt(S.cancelPoints.review))
1817
+ return { ...stats, applied: false, reason: 'declined', cancelPoint: 'review' }
1818
+ }
1819
+ } else {
1820
+ notice(S.planOnlyNoYes)
1821
+ return { ...stats, applied: false, reason: 'not-authorized' }
1822
+ }
1823
+ }
1824
+
1825
+ // Test seam: mutate a target between the plan/authorization and the drift
1826
+ // check. Absent in production callers.
1827
+ if (typeof opts.deps?.betweenPlanAndApply === 'function') opts.deps.betweenPlanAndApply()
1828
+
1829
+ const drifted = detectSnapshotDrift(plannedSnapshots)
1830
+ if (drifted.length > 0) {
1831
+ warning(S.driftHeader)
1832
+ for (const p of drifted) warning(` ${displayPath(target, p)}`)
1833
+ warning(S.driftAbort)
1834
+ return {
1835
+ ...stats,
1836
+ applied: false,
1837
+ reason: 'drift',
1838
+ drift: drifted.map((p) => displayPath(target, p)),
1839
+ }
1840
+ }
1841
+ reviewedRemovals = new Set((planned?.removals ?? []).map((filePath) => resolve(filePath)))
1842
+ reviewedSnapshots = new Map(
1843
+ (plannedSnapshots ?? []).map((before) => [resolve(before.path), before]),
1844
+ )
1845
+ }
1846
+
1847
+ // -----------------------------------------------------------------------
1848
+ // Progress gauge: the user sees progress, not a log. The phase list is
1849
+ // derived from the FINAL component selection, so total == work performed.
1850
+ // `--verbose` keeps the old step-by-step output and draws no gauge; the
1851
+ // internal plan pass (`planOnly`) never owns the terminal.
1852
+ // -----------------------------------------------------------------------
1853
+ const phases = planInstallPhases({ components: componentSet, dryRun })
1854
+ let phaseCursor = 0
1855
+ const progress =
1856
+ opts.planOnly || opts.verbose === true ? null : createGauge({ total: phases.length })
1857
+ if (progress) _activeGauge = progress
1858
+ const advancePhase = (label) => {
1859
+ const phase = label ?? phases[phaseCursor]
1860
+ // Defensive: a phase that the code path skipped must not reprint the last
1861
+ // label at the clamped counter.
1862
+ if (phase === undefined) return
1863
+ phaseCursor += 1
1864
+ progress?.advance(1, phase)
1865
+ }
1866
+ // Prerequisites already ran above (apply + runtime only); account for it.
1867
+ if (phases[0] === S.checkingPrerequisites) advancePhase()
1868
+
1869
+ // -----------------------------------------------------------------------
1870
+ // 0. Exact backup (Beta 11 Setup phase 2): preserve the CURRENT state of
1871
+ // every regular file this run can modify/remove INSIDE the config dir,
1872
+ // byte-for-byte, BEFORE the first modifying write. Bulk directories and
1873
+ // out-of-target global files are recorded in the manifest as
1874
+ // `notRevertible`. A dry run records the planned backup-manifest path only.
1875
+ // -----------------------------------------------------------------------
1876
+ if (componentSet.has('agents')) {
1877
+ const agentTarget = join(target, agentPrefix)
1878
+ assertPathWithin(target, agentTarget)
1879
+ assertNoSymlinkAncestors(agentTarget)
1880
+ }
1881
+ if (componentSet.has('skills')) {
1882
+ const skillsTarget = isGlobal ? join(target, 'skills') : join(target, '.opencode', 'skills')
1883
+ assertPathWithin(target, skillsTarget)
1884
+ assertNoSymlinkAncestors(skillsTarget)
1885
+ }
1886
+ const backupPlan = collectInstallBackupEntries(target, componentSet, version, isGlobal)
1887
+ const pkgVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
1888
+ if (dryRun) {
1889
+ const preview = previewBackupSet({
1890
+ configDir: target,
1891
+ entries: backupPlan.entries,
1892
+ notRevertible: backupPlan.notRevertible,
1893
+ packageVersion: pkgVersion,
1894
+ clock: () => new Date(planTimestamp),
1895
+ })
1896
+ if (isRecording(recorder)) {
1897
+ for (const file of preview.files) {
1898
+ recordChange(
1899
+ {
1900
+ path: file.path,
1901
+ action: ACTIONS.CREATE,
1902
+ bytes: file.bytes,
1903
+ outputFingerprint: file.outputFingerprint,
1904
+ scored: false,
1905
+ },
1906
+ recorder,
1907
+ )
1908
+ }
1909
+ recordChange(
1910
+ {
1911
+ path: preview.manifestPath,
1912
+ action: ACTIONS.CREATE,
1913
+ bytes: preview.manifestBytes,
1914
+ outputFingerprint: preview.manifestFingerprint,
1915
+ scored: false,
1916
+ },
1917
+ recorder,
1918
+ )
1919
+ }
1920
+ } else {
1921
+ const backupStep = step(S.creatingBackup)
1922
+ const { dir: backupDir } = createBackupSet({
1923
+ configDir: target,
1924
+ entries: backupPlan.entries,
1925
+ notRevertible: backupPlan.notRevertible,
1926
+ packageVersion: pkgVersion,
1927
+ clock: () => new Date(planTimestamp),
1928
+ })
1929
+ backupStep(true)
1930
+ if (_lastRun && _lastRun.target === target) _lastRun.backupDir = backupDir
1931
+ // Secret-safe: the path only. The exact wording is fixed (once per apply).
1932
+ // Close the gauge line first: this notice must never be appended to it.
1933
+ endGaugeLine()
1934
+ console.warn(backupWarning(backupDir))
1935
+ }
1936
+ advancePhase()
877
1937
 
878
1938
  if (isGlobal) {
879
1939
  info(S.globalLayout)
@@ -883,7 +1943,7 @@ export async function installOpenCode(
883
1943
  // 1. Install agents (--components agents)
884
1944
  // -----------------------------------------------------------------------
885
1945
  if (componentSet.has('agents')) {
886
- section('\uD83D\uDCE6 Agents')
1946
+ section('Agents')
887
1947
  const srcDir = join(ROOT, 'src', 'agents')
888
1948
  if (!sourceDirValid(srcDir)) {
889
1949
  warning(`Agent source directory not found: ${srcDir}`)
@@ -891,14 +1951,26 @@ export async function installOpenCode(
891
1951
  } else {
892
1952
  const agentStep = step(S.installingAgents)
893
1953
  const dstDir = join(target, agentPrefix)
894
- if (!dryRun) mkdirSync(dstDir, { recursive: true })
895
- if (clean && existsSync(dstDir) && !dryRun) {
1954
+ assertPathWithin(target, dstDir)
1955
+ assertNoSymlinkAncestors(dstDir)
1956
+ if (!dryRun) {
1957
+ mkdirSync(dstDir, { recursive: true })
1958
+ assertNoSymlinkAncestors(dstDir)
1959
+ }
1960
+ if (clean && existsSync(dstDir)) {
1961
+ assertNoSymlinkAncestors(dstDir)
896
1962
  const existing = readdirSync(dstDir)
897
1963
  for (const f of existing) {
898
- rmSync(join(dstDir, f), { recursive: true, force: true })
1964
+ const agentPath = join(dstDir, f)
1965
+ assertSafeRemoval(dstDir, agentPath)
1966
+ if (dryRun) {
1967
+ recordRemovalTree(agentPath, recorder)
1968
+ } else {
1969
+ removeReviewedTree(agentPath, reviewedRemovals, reviewedSnapshots)
1970
+ }
899
1971
  }
900
1972
  }
901
- const { created, skipped } = copyAgentPrompts(srcDir, dstDir, dryRun)
1973
+ const { created, skipped } = copyAgentPrompts(srcDir, dstDir, dryRun, false, recorder)
902
1974
  stats.created += created
903
1975
  stats.skipped += skipped
904
1976
  agentStep(true)
@@ -912,25 +1984,37 @@ export async function installOpenCode(
912
1984
  const srcRouting = join(ROOT, 'src', 'routing.yml')
913
1985
  const dstRouting = join(target, 'routing.yml')
914
1986
  if (existsSync(srcRouting)) {
915
- const routingStatus = writeIfChanged(dstRouting, readFileSync(srcRouting, 'utf8'), dryRun)
1987
+ const routingStatus = writeIfChanged(dstRouting, readFileSync(srcRouting, 'utf8'), dryRun, {
1988
+ recorder,
1989
+ })
916
1990
  if (routingStatus === 'created') stats.created++
917
1991
  else stats.skipped++
918
1992
  }
919
1993
  }
1994
+ if (componentSet.has('agents')) advancePhase()
920
1995
 
921
1996
  // -----------------------------------------------------------------------
922
1997
  // 2. Install skills (--components skills)
923
1998
  // -----------------------------------------------------------------------
924
1999
  if (componentSet.has('skills')) {
925
- section('\uD83D\uDCDA Skills')
2000
+ section('Skills')
926
2001
  const skillNames = collectSkillNames()
927
2002
  if (skillNames.length > 0) {
928
2003
  const skillStep = step(`Installing ${skillNames.length} skills`)
929
2004
  const dstSkillsDir = isGlobal ? join(target, 'skills') : join(target, '.opencode', 'skills')
930
- if (clean && existsSync(dstSkillsDir) && !dryRun) {
2005
+ assertPathWithin(target, dstSkillsDir)
2006
+ assertNoSymlinkAncestors(dstSkillsDir)
2007
+ if (clean && existsSync(dstSkillsDir)) {
2008
+ assertNoSymlinkAncestors(dstSkillsDir)
931
2009
  const existing = readdirSync(dstSkillsDir)
932
2010
  for (const s of existing) {
933
- rmSync(join(dstSkillsDir, s), { recursive: true, force: true })
2011
+ const skillPath = join(dstSkillsDir, s)
2012
+ assertSafeRemoval(dstSkillsDir, skillPath)
2013
+ if (dryRun) {
2014
+ recordRemovalTree(skillPath, recorder)
2015
+ } else {
2016
+ removeReviewedTree(skillPath, reviewedRemovals, reviewedSnapshots)
2017
+ }
934
2018
  }
935
2019
  }
936
2020
  const installSubDir = isGlobal ? '' : '.opencode'
@@ -939,32 +2023,46 @@ export async function installOpenCode(
939
2023
  target,
940
2024
  dryRun,
941
2025
  installSubDir,
2026
+ recorder,
2027
+ reviewedRemovals,
2028
+ reviewedSnapshots,
2029
+ clean,
942
2030
  )
943
2031
  stats.created += sCreated
944
2032
  stats.skipped += sSkipped
945
2033
  skillStep(true)
946
2034
  }
947
2035
  }
2036
+ if (componentSet.has('skills')) advancePhase()
948
2037
 
949
2038
  // -----------------------------------------------------------------------
950
2039
  // 2.5 Install shared instructions: AGENTS.md (--components instructions)
951
2040
  // -----------------------------------------------------------------------
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).
2041
+ // Both AGENTS.md artifacts are managed regions (scripts/build-agents-md.mjs).
2042
+ // A GLOBAL config dir receives the repo-agnostic global artifact (agent
2043
+ // table + shared rules); a PROJECT layout keeps the repository artifact.
2044
+ // writeAgentsMdManaged is conservative: content outside the managed region
2045
+ // is never deleted, and a legacy fully-generated file upgrades in place.
958
2046
  if (componentSet.has('instructions')) {
959
- section('\uD83D\uDCCB Instructions')
960
- // AGENTS.md
961
- const srcAgentsMd = join(ROOT, 'AGENTS.md')
2047
+ section('Instructions')
2048
+ const srcAgentsMd = isGlobal ? join(ROOT, 'AGENTS.global.md') : join(ROOT, 'AGENTS.md')
962
2049
  const dstAgentsMd = join(target, 'AGENTS.md')
963
2050
  if (existsSync(srcAgentsMd)) {
964
2051
  const content = readFileSync(srcAgentsMd, 'utf8')
965
- const status = writeIfChanged(dstAgentsMd, content, dryRun)
966
- if (status === 'created') stats.created++
967
- else stats.skipped++
2052
+ const status = writeAgentsMdManaged(dstAgentsMd, content, dryRun, recorder)
2053
+ if (status === 'skipped') stats.skipped++
2054
+ else {
2055
+ stats.created++
2056
+ if (status === 'merged') {
2057
+ warning(
2058
+ `AGENTS.md had non-generated content — it was preserved around the ` +
2059
+ `Pantheon managed region in ${dstAgentsMd}. Review and merge manually.`,
2060
+ )
2061
+ }
2062
+ }
2063
+ } else {
2064
+ warning(`AGENTS.md artifact not found in the package: ${srcAgentsMd}`)
2065
+ stats.errors++
968
2066
  }
969
2067
  // An instruction-only upgrade must also refresh selective guidance on
970
2068
  // already-installed Pantheon agents, but must not create agents the user
@@ -973,32 +2071,43 @@ export async function installOpenCode(
973
2071
  const installedAgents = join(target, agentPrefix)
974
2072
  const sourceAgents = join(ROOT, 'src', 'agents')
975
2073
  if (existsSync(installedAgents) && existsSync(sourceAgents)) {
976
- const refreshed = copyAgentPrompts(sourceAgents, installedAgents, dryRun, true)
2074
+ const refreshed = copyAgentPrompts(sourceAgents, installedAgents, dryRun, true, recorder)
977
2075
  stats.created += refreshed.created
978
2076
  stats.skipped += refreshed.skipped
979
2077
  }
980
2078
  }
981
2079
  }
2080
+ if (componentSet.has('instructions')) advancePhase()
982
2081
 
983
2082
  // -----------------------------------------------------------------------
984
2083
  // 2.6 Install prompts (--components prompts)
985
2084
  // -----------------------------------------------------------------------
986
2085
  if (componentSet.has('prompts')) {
987
- section('\uD83D\uDCAC Prompts')
2086
+ section('Prompts')
988
2087
  const srcPrompts = join(ROOT, 'prompts')
989
2088
  const dstPrompts = join(target, 'prompts')
990
2089
  if (existsSync(srcPrompts)) {
991
- const promptsResult = syncDir(srcPrompts, dstPrompts, dryRun, clean)
2090
+ const promptsResult = syncDir(
2091
+ srcPrompts,
2092
+ dstPrompts,
2093
+ dryRun,
2094
+ clean,
2095
+ null,
2096
+ recorder,
2097
+ reviewedRemovals,
2098
+ reviewedSnapshots,
2099
+ )
992
2100
  stats.created += promptsResult.created
993
2101
  stats.skipped += promptsResult.skipped
994
2102
  }
995
2103
  }
2104
+ if (componentSet.has('prompts')) advancePhase()
996
2105
 
997
2106
  // -----------------------------------------------------------------------
998
2107
  // 2.7 Install commands (--components commands)
999
2108
  // -----------------------------------------------------------------------
1000
2109
  if (componentSet.has('commands')) {
1001
- section('\u26A1 Commands')
2110
+ section('Commands')
1002
2111
  const srcCmds = join(ROOT, 'commands')
1003
2112
  // V2 project sandboxes use OPENCODE_CONFIG_DIR=<project root>, so OpenCode
1004
2113
  // discovers custom commands from <target>/commands. V1 project installs
@@ -1006,11 +2115,21 @@ export async function installOpenCode(
1006
2115
  const commandDir = isGlobal || version === 'v2' ? 'commands' : '.opencode/commands'
1007
2116
  const dstCmds = join(target, commandDir)
1008
2117
  if (existsSync(srcCmds)) {
1009
- const cmdResult = syncDir(srcCmds, dstCmds, dryRun, clean, (f) => f.endsWith('.md'))
2118
+ const cmdResult = syncDir(
2119
+ srcCmds,
2120
+ dstCmds,
2121
+ dryRun,
2122
+ clean,
2123
+ (f) => f.endsWith('.md'),
2124
+ recorder,
2125
+ reviewedRemovals,
2126
+ reviewedSnapshots,
2127
+ )
1010
2128
  stats.created += cmdResult.created
1011
2129
  stats.skipped += cmdResult.skipped
1012
2130
  }
1013
2131
  }
2132
+ if (componentSet.has('commands')) advancePhase()
1014
2133
 
1015
2134
  // -----------------------------------------------------------------------
1016
2135
  // -----------------------------------------------------------------------
@@ -1024,15 +2143,23 @@ export async function installOpenCode(
1024
2143
  // 2.8 Install TUI plugins (--components plugins)
1025
2144
  // -----------------------------------------------------------------------
1026
2145
  if (componentSet.has('plugins')) {
1027
- section('\uD83D\uDD0C Plugins')
2146
+ section('Plugins')
1028
2147
  const srcPluginDir = join(ROOT, 'src', 'plugins', 'tui')
1029
2148
  const dstPluginDir = isGlobal
1030
2149
  ? join(target, 'plugins', 'pantheon-tui')
1031
2150
  : join(target, '.opencode', 'plugins', 'pantheon-tui')
1032
- const pluginStats = installPlugin(srcPluginDir, dstPluginDir, { dryRun, clean, version })
2151
+ const pluginStats = installPlugin(srcPluginDir, dstPluginDir, {
2152
+ dryRun,
2153
+ clean,
2154
+ version,
2155
+ recorder,
2156
+ reviewedRemovals,
2157
+ reviewedSnapshots,
2158
+ })
1033
2159
  stats.created += pluginStats.created
1034
2160
  stats.skipped += pluginStats.skipped
1035
2161
  stats.errors += pluginStats.errors
2162
+ for (const problem of pluginStats.problems ?? []) error(problem)
1036
2163
  }
1037
2164
 
1038
2165
  // -----------------------------------------------------------------------
@@ -1041,7 +2168,14 @@ export async function installOpenCode(
1041
2168
  if (componentSet.has('plugins')) {
1042
2169
  let tuiStatus
1043
2170
  try {
1044
- tuiStatus = syncTuiRegistration(target, { isGlobal, dryRun, version })
2171
+ tuiStatus = syncTuiRegistration(target, {
2172
+ isGlobal,
2173
+ dryRun,
2174
+ version,
2175
+ recorder,
2176
+ reviewedRemovals,
2177
+ reviewedSnapshots,
2178
+ })
1045
2179
  } catch (cause) {
1046
2180
  error(`TUI plugin setup failed: ${cause.message}`)
1047
2181
  stats.errors++
@@ -1050,28 +2184,39 @@ export async function installOpenCode(
1050
2184
  if (tuiStatus === 'created') stats.created++
1051
2185
  else stats.skipped++
1052
2186
  }
2187
+ // -----------------------------------------------------------------------
2188
+ // 2.9b V2 terminal-client config: cancel the builtin Context sidebar block
2189
+ // -----------------------------------------------------------------------
2190
+ // The directive belongs in the V2 client config, which exists ONLY globally
2191
+ // (V2 has no project-local client config), so a project install must not
2192
+ // create one. Keeping it in the installer is what makes the de-duplication
2193
+ // durable: a hand edit in ~/.config/opencode/cli.json would be lost as soon as
2194
+ // the user re-runs init, and the Context block would render twice again.
2195
+ if (componentSet.has('plugins') && version === 'v2' && isGlobal) {
2196
+ try {
2197
+ const cliStatus = applyContextSidebarNegation(target, { dryRun, recorder })
2198
+ if (cliStatus === 'created') stats.created++
2199
+ else if (cliStatus === 'removed' || cliStatus === 'unverified') stats.warnings++
2200
+ else stats.skipped++
2201
+ } catch (cause) {
2202
+ // A client config we cannot update is not a failed install: the plugin
2203
+ // payload and the host config are already in place.
2204
+ warning(`Could not disable the builtin Context sidebar block: ${cause.message}`)
2205
+ stats.warnings++
2206
+ }
2207
+ }
2208
+ if (componentSet.has('plugins')) advancePhase()
1053
2209
 
1054
2210
  // -----------------------------------------------------------------------
1055
2211
  // 2.10 Install runtime infrastructure (--components runtime)
1056
2212
  // MCP server scripts, code-mode scripts, tiers.json
1057
2213
  // -----------------------------------------------------------------------
1058
2214
  if (componentSet.has('runtime')) {
1059
- section('\u2699\uFE0F Runtime')
2215
+ section('Runtime')
1060
2216
  const runtimeTarget = isGlobal ? target : join(target, '.opencode')
1061
2217
 
1062
2218
  // ── 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
- ]
2219
+ const mcpScripts = MCP_SCRIPTS
1075
2220
  const srcScriptsDir = join(ROOT, 'scripts')
1076
2221
  // Canonical MCP server sources live in src/mcp/. Map them explicitly so the
1077
2222
  // sync always copies from the canonical source, never from the stale root
@@ -1099,7 +2244,7 @@ export async function installOpenCode(
1099
2244
  }
1100
2245
  const content = readFileSync(src, 'utf8')
1101
2246
  const dst = join(dstScriptsDir, script)
1102
- const status = writeIfChanged(dst, content, dryRun)
2247
+ const status = writeIfChanged(dst, content, dryRun, { recorder })
1103
2248
  if (status === 'created') {
1104
2249
  stats.created++
1105
2250
  // Make executable
@@ -1117,7 +2262,9 @@ export async function installOpenCode(
1117
2262
  const visionRequirements = join(ROOT, 'src', 'mcp', 'requirements-vision.txt')
1118
2263
  if (existsSync(visionRequirements)) {
1119
2264
  const destination = join(runtimeTarget, 'requirements-vision.txt')
1120
- const status = writeIfChanged(destination, readFileSync(visionRequirements, 'utf8'), dryRun)
2265
+ const status = writeIfChanged(destination, readFileSync(visionRequirements, 'utf8'), dryRun, {
2266
+ recorder,
2267
+ })
1121
2268
  if (status === 'created') stats.created++
1122
2269
  else stats.skipped++
1123
2270
  } else {
@@ -1129,7 +2276,19 @@ export async function installOpenCode(
1129
2276
  const srcCodeModeDir = join(ROOT, '.pantheon', 'code-mode')
1130
2277
  const dstCodeModeDir = join(runtimeTarget, '.pantheon', 'code-mode')
1131
2278
  if (existsSync(srcCodeModeDir)) {
1132
- const cmResult = syncDir(srcCodeModeDir, dstCodeModeDir, dryRun, clean)
2279
+ // manifest.json is owned by writeCodeModeManifest (below), not by the dir
2280
+ // sync. Excluding it here keeps exactly ONE writer/count for that path,
2281
+ // so the preview action and the install summary can never diverge.
2282
+ const cmResult = syncDir(
2283
+ srcCodeModeDir,
2284
+ dstCodeModeDir,
2285
+ dryRun,
2286
+ clean,
2287
+ (f) => f !== 'manifest.json',
2288
+ recorder,
2289
+ reviewedRemovals,
2290
+ reviewedSnapshots,
2291
+ )
1133
2292
  stats.created += cmResult.created
1134
2293
  stats.skipped += cmResult.skipped
1135
2294
  } else {
@@ -1140,13 +2299,18 @@ export async function installOpenCode(
1140
2299
  warning(`Code-mode source not found: ${srcCodeModeDir} — creating empty ${dstCodeModeDir}`)
1141
2300
  if (!dryRun) mkdirSync(dstCodeModeDir, { recursive: true })
1142
2301
  stats.created++
2302
+ // The empty runtime dir is a real create counted by `stats.created`, so
2303
+ // record it too (or the preview under-reports on this fallback path).
2304
+ recordChange({ path: dstCodeModeDir, action: ACTIONS.CREATE, bytes: 0 }, recorder)
1143
2305
  }
1144
2306
 
1145
2307
  // B3-08: explicit installation mode — seed the manifest with SHA-256
1146
2308
  // 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`)
2309
+ const manifest = writeCodeModeManifest(srcCodeModeDir, dstCodeModeDir, dryRun, recorder)
2310
+ if (manifest.status === 'created') stats.created++
2311
+ else if (manifest.status === 'skipped') stats.skipped++
2312
+ if (manifest.approved > 0) {
2313
+ info(`Code-mode manifest: ${manifest.approved} script(s) approved`)
1150
2314
  }
1151
2315
 
1152
2316
  // ── tiers.json ──
@@ -1154,11 +2318,12 @@ export async function installOpenCode(
1154
2318
  const dstTiers = join(runtimeTarget, '.pantheon', 'tiers.json')
1155
2319
  if (existsSync(srcTiers)) {
1156
2320
  const content = readFileSync(srcTiers, 'utf8')
1157
- const status = writeIfChanged(dstTiers, content, dryRun)
2321
+ const status = writeIfChanged(dstTiers, content, dryRun, { recorder })
1158
2322
  if (status === 'created') stats.created++
1159
2323
  else stats.skipped++
1160
2324
  }
1161
2325
  }
2326
+ if (componentSet.has('runtime')) advancePhase()
1162
2327
 
1163
2328
  // -----------------------------------------------------------------------
1164
2329
  // 2.11 Setup virtual environment + health check (--components runtime)
@@ -1168,7 +2333,24 @@ export async function installOpenCode(
1168
2333
  // -----------------------------------------------------------------------
1169
2334
  let runtimeHealthy = !componentSet.has('runtime')
1170
2335
  if (componentSet.has('runtime')) {
1171
- runtimeHealthy = setupRuntimePhase(target, { dryRun, clean, isGlobal }, stats)
2336
+ runtimeHealthy = setupRuntimePhase(
2337
+ target,
2338
+ {
2339
+ dryRun,
2340
+ clean,
2341
+ isGlobal,
2342
+ recorder,
2343
+ reviewedRemovals,
2344
+ reviewedSnapshots,
2345
+ // Two distinct gauge phases share this one call: the venv setup and
2346
+ // the health check. Hooks keep the gauge honest without leaking the
2347
+ // UI object into the runtime module.
2348
+ onVenvDone: () => advancePhase(S.settingUpRuntime),
2349
+ onHealthDone: () => advancePhase(S.runningHealthChecks),
2350
+ },
2351
+ stats,
2352
+ opts.deps,
2353
+ )
1172
2354
  }
1173
2355
 
1174
2356
  // -----------------------------------------------------------------------
@@ -1386,11 +2568,55 @@ export async function installOpenCode(
1386
2568
  }
1387
2569
 
1388
2570
  if (version === 'v2') {
1389
- // V2 loads the plural `plugins` list. Keep third-party V1 entries in the
1390
- // legacy list for users who still use them, but never leave a Pantheon V1
1391
- // entry configured alongside the V2 package export.
2571
+ // V2 loads the plural `plugins` list, and the singular `plugin` key is dead
2572
+ // on this host. Migrating a V1 config therefore means deciding, entry by
2573
+ // entry, whether the V2 loader can load it AT ALL: a directory can, a file
2574
+ // path is rejected ("must be a directory") and a package shorthand dies in
2575
+ // `npm install`. Copying every entry across would turn "silently ignored"
2576
+ // into "config fails to load", so only loadable entries move; the rest stay
2577
+ // where they are and the warning names the exact failure mode.
1392
2578
  if (Array.isArray(config.plugin)) {
2579
+ // Strip Pantheon refs FIRST, exactly as the V1 branch does: a stale V1
2580
+ // .ts path is not a registrable entry on this host and must not be moved.
1393
2581
  config.plugin = removePantheonPluginReferences(config.plugin)
2582
+ if (!Array.isArray(config.plugins)) config.plugins = []
2583
+ const migrated = []
2584
+ const blocked = []
2585
+ for (const plugin of config.plugin) {
2586
+ const verdict = v2PluginEntryLoadability(plugin, target)
2587
+ if (!verdict.loadable) {
2588
+ blocked.push({ plugin, reason: verdict.reason })
2589
+ continue
2590
+ }
2591
+ if (!hasPluginReference(config.plugins, plugin)) {
2592
+ config.plugins.push(deepClone(plugin))
2593
+ migrated.push(plugin)
2594
+ }
2595
+ }
2596
+ if (migrated.length > 0) {
2597
+ warning(
2598
+ `V2 host ignores the singular "plugin" key; also registered ${migrated.length} ` +
2599
+ `third-party entr${migrated.length === 1 ? 'y' : 'ies'} under "plugins" so ` +
2600
+ `they keep loading: ${migrated.map(describePluginEntry).join(', ')}. ` +
2601
+ 'Remove any that only support the V1 plugin API.',
2602
+ )
2603
+ }
2604
+ if (blocked.length > 0) {
2605
+ warning(
2606
+ 'V2 host ignores the singular "plugin" key; these entries were left in it ' +
2607
+ `because the V2 loader cannot load them, so they will NOT be active: ${blocked
2608
+ .map(
2609
+ ({ plugin, reason }) =>
2610
+ `${describePluginEntry(plugin)} ${V2_LOAD_FAILURES[reason]}`,
2611
+ )
2612
+ .join('; ')}.`,
2613
+ )
2614
+ }
2615
+ // Pantheon refs are already gone. An emptied array is not configuration:
2616
+ // drop the dead key entirely so the written config points at the list the
2617
+ // V2 host actually reads. A surviving V1 list is the user's own data and
2618
+ // is left in place (a downgrade still finds it).
2619
+ if (config.plugin.length === 0) delete config.plugin
1394
2620
  }
1395
2621
  if (!Array.isArray(config.plugins)) config.plugins = []
1396
2622
  // Preserve any options already set on the Pantheon V2 entry across the
@@ -1429,11 +2655,49 @@ export async function installOpenCode(
1429
2655
  config.plugins = config.plugins.filter(
1430
2656
  (plugin) => pluginReferenceIdentity(plugin) !== pluginReferenceIdentity(resolvedV2),
1431
2657
  )
1432
- config.plugins.push(
1433
- existingV2Options === null
1434
- ? resolvedV2
1435
- : { package: resolvedV2, options: deepClone(existingV2Options) },
2658
+ // ALWAYS the object form, even on a fresh install with nothing to preserve.
2659
+ // The host hands a plugin its `options` only from `{ package, options }`,
2660
+ // and the opt-in features (`context_pruner`, `memory_injection`) read
2661
+ // `ctx.options`. Emitting a bare string — which a fresh install used to do —
2662
+ // left those features unreachable for anyone who did not already know the
2663
+ // object syntax from the docs, so the shape (with an empty options bag) is
2664
+ // written from the start and a user's hand-added keys survive a re-run.
2665
+ config.plugins.push({
2666
+ package: resolvedV2,
2667
+ options: existingV2Options === null ? {} : deepClone(existingV2Options),
2668
+ })
2669
+
2670
+ // A path that LOOKS like a Pantheon V2 entry but is not one this package
2671
+ // can prove it owns (managedPluginIdentity only recognizes installed copies
2672
+ // and this package's own paths) would now be registered twice: the host
2673
+ // would run both copies' hooks. Retiring it on a guess could delete a
2674
+ // third-party plugin, so say what is happening instead of guessing.
2675
+ const lookalikes = config.plugins.filter(
2676
+ (ref) =>
2677
+ !isPantheonPluginReference(ref) &&
2678
+ pluginMetadataReferences(ref).some((reference) =>
2679
+ /(^|\/)plugin-v2(?:\.ts)?$/.test(normalizePluginRef(reference)),
2680
+ ),
1436
2681
  )
2682
+ if (lookalikes.length > 0) {
2683
+ warning(
2684
+ 'This config also points at another copy of the Pantheon V2 plugin, which this ' +
2685
+ 'installer cannot prove it owns: ' +
2686
+ `${lookalikes.map(describePluginEntry).join(', ')}. With the entry registered in ` +
2687
+ 'this install, BOTH copies would load and their hooks would run twice. Remove that ' +
2688
+ 'entry by hand if it is an older Pantheon installation; it is left alone because a ' +
2689
+ 'third-party plugin could share the path.',
2690
+ )
2691
+ }
2692
+ }
2693
+
2694
+ // Report whether the entry the host will read can actually carry options.
2695
+ // Computed here, from the config this pass is about to write, so it answers
2696
+ // the installed state rather than an assumption.
2697
+ const v2PluginOptions =
2698
+ version === 'v2' ? describePluginOptionsReachability(config.plugins) : null
2699
+ if (v2PluginOptions !== null && !v2PluginOptions.reachable && !opts.planOnly) {
2700
+ warning(`Pantheon V2 plugin options are not reachable: ${v2PluginOptions.detail}`)
1437
2701
  }
1438
2702
 
1439
2703
  if (pantheonConfig !== null) {
@@ -1569,10 +2833,19 @@ export async function installOpenCode(
1569
2833
  // Point the config at the venv even on a first install; setupVenv runs
1570
2834
  // later in this function and creates this path before OpenCode starts.
1571
2835
  const runtimeTarget = isGlobal ? target : join(target, '.opencode')
1572
- applyMcpServerEntries(config, {
2836
+ const mcp = applyMcpServerEntries(config, {
1573
2837
  runtimeTarget,
1574
2838
  venvPython: venvPythonPath(target),
2839
+ version,
1575
2840
  })
2841
+ mcpServers = mcp.servers
2842
+ // `permission.mcp.<server>: ask` is inert on OpenCode 2.x. Never leave the
2843
+ // user believing the default gated anything: report each unenforced entry
2844
+ // and point at the enforceable form.
2845
+ for (const message of mcp.warnings ?? []) {
2846
+ warning(message)
2847
+ stats.warnings += 1
2848
+ }
1576
2849
  }
1577
2850
 
1578
2851
  // ── V2 native migration ──
@@ -1580,6 +2853,10 @@ export async function installOpenCode(
1580
2853
  // before writing. V1 path is untouched (zero regression).
1581
2854
  let configToWrite = config
1582
2855
  if (version === 'v2') {
2856
+ // The V2 converters can emit raw console warnings (ambiguous legacy
2857
+ // values). Close the gauge line first so they are not printed on top of it
2858
+ // and then erased by the next `\r` clear.
2859
+ endGaugeLine()
1583
2860
  info(S.v2Migrating)
1584
2861
  configToWrite = migrateV1toV2(config)
1585
2862
 
@@ -1611,25 +2888,30 @@ export async function installOpenCode(
1611
2888
  }
1612
2889
 
1613
2890
  const configContent = `${JSON.stringify(configToWrite, null, 2)}\n`
2891
+ const configStep = step(S.writingConfig)
1614
2892
  const status = writeConfigWithBackup(targetConfigPath, configContent, dryRun, {
1615
2893
  expectedContent: configRaw,
1616
2894
  // Test seam: lets a test simulate a concurrent writer landing between the
1617
2895
  // initial config read and the pre-swap recheck. Absent in production.
1618
2896
  beforeRecheck: opts.deps?.beforeRecheck,
2897
+ recorder,
1619
2898
  })
1620
2899
  if (status === 'conflict') {
2900
+ configStep(false)
1621
2901
  // The user's config changed under the installer between the read and the
1622
2902
  // swap. Treating this as an ordinary skipped write would report a
1623
2903
  // successful install over a file we never actually updated — fail loudly
1624
- // and leave the target and its `.bak` byte-identical instead.
2904
+ // and leave the target byte-identical instead.
1625
2905
  throw new Error(
1626
2906
  `Installation aborted: ${targetConfigPath} changed on disk during install ` +
1627
2907
  '(it no longer matches the content that was read); refusing to overwrite it. ' +
1628
2908
  'Re-run the installer once the file is stable.',
1629
2909
  )
1630
2910
  }
2911
+ configStep(true)
1631
2912
  if (status === 'created') stats.created++
1632
2913
  else stats.skipped++
2914
+ advancePhase()
1633
2915
 
1634
2916
  // -----------------------------------------------------------------------
1635
2917
  // 3.5 Run migrations (--components runtime)
@@ -1637,7 +2919,14 @@ export async function installOpenCode(
1637
2919
  if (componentSet.has('runtime')) {
1638
2920
  const currentVersion = detectVersion(target)
1639
2921
  if (currentVersion) {
1640
- const migration = runMigrations(target, currentVersion, { dryRun })
2922
+ const migrationStep = step(S.runningMigrations)
2923
+ const migration = runMigrations(target, currentVersion, {
2924
+ dryRun,
2925
+ recorder,
2926
+ updatedAt: planTimestamp,
2927
+ })
2928
+ migrationStep(true)
2929
+ if (migration.plannedState) projectedState = migration.plannedState
1641
2930
  if (migration.applied > 0) {
1642
2931
  success(`Applied ${migration.applied} migration(s)`)
1643
2932
  for (const msg of migration.messages) {
@@ -1645,6 +2934,125 @@ export async function installOpenCode(
1645
2934
  }
1646
2935
  }
1647
2936
  }
2937
+ // Counted even when there is nothing to migrate: the phase ran its check.
2938
+ advancePhase()
2939
+ }
2940
+
2941
+ if (opts.preset && dryRun) {
2942
+ const { writeActivePreset } = await import('./model-picker.mjs')
2943
+ writeActivePreset(target, opts.preset, {
2944
+ dryRun: true,
2945
+ source: 'cli',
2946
+ updatedAt: planTimestamp,
2947
+ recorder,
2948
+ logger: { log() {} },
2949
+ })
2950
+ }
2951
+
2952
+ // -----------------------------------------------------------------------
2953
+ // 3.75 Preview summary (Beta 11 Setup phase 1): print the REAL per-file
2954
+ // change set this same pass would apply. Paths + action + byte size
2955
+ // ONLY — never file contents or hashes. Nothing was written.
2956
+ // -----------------------------------------------------------------------
2957
+ // A dry run has finished every phase it runs at this point (no state write):
2958
+ // close the gauge BEFORE the plan so the final line stands on its own.
2959
+ if (dryRun) {
2960
+ progress?.done()
2961
+ if (preview) endGaugeLine()
2962
+ }
2963
+ if (preview) {
2964
+ // Project the terminal state write using the plan's stable timestamp so
2965
+ // saved-plan apply can validate its exact output fingerprint.
2966
+ const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
2967
+ let state = projectedState ?? readState(target)
2968
+ if (!state) state = createInitialState(packageVersion, planTimestamp)
2969
+ state.pantheon_version = packageVersion
2970
+ state.updated_at = planTimestamp
2971
+ state.schema_version = 2
2972
+ for (const component of ['agents', 'skills', 'plugins', 'runtime']) {
2973
+ if (!componentSet.has(component)) continue
2974
+ const componentStatus = component === 'runtime' && !runtimeHealthy ? 'failed' : 'installed'
2975
+ const componentVersion = state.components?.[component]?.version ?? 1
2976
+ setComponentState(state, component, componentVersion, componentStatus)
2977
+ }
2978
+ const stateContent = `${JSON.stringify(state, null, 2)}\n`
2979
+ // NOTE: this fingerprint is the PROJECTED terminal state, not a byte-exact
2980
+ // prediction of the state file an apply leaves behind. The apply writes
2981
+ // `install-state.json` only after `updateFileInventory()` has added the
2982
+ // verified-file entries, so the final bytes (and hash) differ from this
2983
+ // preview by design. Do not "fix" the fingerprint to match the audit run:
2984
+ // the inventory entries are an OUTPUT of the apply, not an input to it.
2985
+ recordChange(
2986
+ {
2987
+ path: join(target, '.pantheon', 'install-state.json'),
2988
+ action: hasState(target) ? ACTIONS.UPDATE : ACTIONS.CREATE,
2989
+ bytes: Buffer.byteLength(stateContent, 'utf8'),
2990
+ outputFingerprint: fingerprintOutput(stateContent),
2991
+ scored: false,
2992
+ },
2993
+ recorder,
2994
+ )
2995
+ const plan = summarizeChanges(preview.entries)
2996
+ // The MCP section is derived from the write path: `mcpServers` holds the
2997
+ // names `applyMcpServerEntries` seeded in THIS pass, in write order (empty
2998
+ // when the runtime component is not selected or failed its prerequisites).
2999
+ plan.mcpServers = mcpServers
3000
+ plan.versionAssumed = versionAssumed
3001
+ planFiles = plan.files
3002
+ planTotals = plan.totals
3003
+ plannedChanges = plan.totals.create + plan.totals.update + plan.totals.remove
3004
+ removalPaths = [
3005
+ ...new Set(
3006
+ preview.entries
3007
+ .filter((entry) => entry.action === ACTIONS.REMOVE)
3008
+ .map((entry) => resolve(entry.path)),
3009
+ ),
3010
+ ].sort()
3011
+ // Snapshot both net changes and every raw removal target. A later write can
3012
+ // make a removal path look unchanged in the net plan, but it still needs
3013
+ // review before the clean operation deletes and recreates it.
3014
+ const snapshotPaths = new Set([...plan.files.map((file) => file.path), ...removalPaths])
3015
+ plannedSnapshots = [...snapshotPaths].map((filePath) => ({
3016
+ path: filePath,
3017
+ ...snapshot(filePath),
3018
+ }))
3019
+ const statsDelta = {
3020
+ created: stats.created - statsBefore.created,
3021
+ skipped: stats.skipped - statsBefore.skipped,
3022
+ }
3023
+ const mismatch = planStatsMismatch(plan, statsDelta)
3024
+ if (mismatch) {
3025
+ // Development safety net: a writer that incremented THIS call's install
3026
+ // stats but never recorded a change would otherwise make the preview
3027
+ // silently incomplete. Surface it loudly instead of hiding it.
3028
+ warning(
3029
+ `Change-plan consistency mismatch: plan reports ${mismatch.changed} changed / ` +
3030
+ `${mismatch.unchanged} unchanged vs stats ${mismatch.recordedChanged}/${mismatch.recordedUnchanged}`,
3031
+ )
3032
+ }
3033
+ // Dry-run surface: by default a SUMMARY (counts + MCP servers + "No files
3034
+ // were written"), never one line per file — the gauge already answered
3035
+ // "is it moving?" and per-file detail is opt-in via --verbose. `[DRY-RUN]`
3036
+ // marks the header only; it no longer prefixes every line.
3037
+ // An internal snapshot pass on the apply path (`quietPlan`, e.g. an
3038
+ // authorized `--yes` run) computes the plan and snapshots but must NOT
3039
+ // echo it — a real apply is not a dry run.
3040
+ if (!opts.quietPlan) {
3041
+ const verbose = opts.verbose === true
3042
+ const planText = formatChangePlan(target, plan, { perFile: verbose })
3043
+ const planLines = planText.split('\n')
3044
+ console.log('')
3045
+ if (verbose && removalPaths.length > 0) {
3046
+ console.log(tag(`Removal review — ${removalPaths.length} path(s):`))
3047
+ for (const filePath of removalPaths) {
3048
+ console.log(` remove ${displayPath(target, filePath)}`)
3049
+ }
3050
+ console.log('')
3051
+ }
3052
+ console.log(tag(planLines[0]))
3053
+ for (const line of planLines.slice(1)) console.log(line)
3054
+ console.log('')
3055
+ }
1648
3056
  }
1649
3057
 
1650
3058
  // -----------------------------------------------------------------------
@@ -1653,6 +3061,7 @@ export async function installOpenCode(
1653
3061
  // -----------------------------------------------------------------------
1654
3062
 
1655
3063
  if (interactive && !dryRun) {
3064
+ endGaugeLine()
1656
3065
  const created = stats.created
1657
3066
  const skipped = stats.skipped
1658
3067
  const errors = stats.errors
@@ -1669,14 +3078,13 @@ export async function installOpenCode(
1669
3078
  process.stdout.write(
1670
3079
  ` ${colors.dim('\u2500'.repeat(Math.min(process.stdout.columns || 60, 60)))}\n`,
1671
3080
  )
1672
- process.stdout.write(` ${colors.green('\u2713')} ${created} component(s) installed\n`)
3081
+ process.stdout.write(` [OK] ${created} component(s) installed\n`)
1673
3082
  if (skipped > 0)
1674
3083
  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`)
3084
+ if (errors > 0) process.stdout.write(` [WARN] ${errors} error(s) encountered\n`)
1677
3085
  if (warnings > 0)
1678
3086
  process.stdout.write(
1679
- ` ${colors.yellow('\u26a0')} ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
3087
+ ` [WARN] ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
1680
3088
  )
1681
3089
  process.stdout.write('\n')
1682
3090
  process.stdout.write(` ${colors.bold('Next steps:')}\n`)
@@ -1686,24 +3094,41 @@ export async function installOpenCode(
1686
3094
  ` ${colors.dim('\u2022')} Run 'opencode' to start using Pantheon agents\n`,
1687
3095
  )
1688
3096
  process.stdout.write('\n')
1689
- } else {
1690
- printSummary(target, ['opencode'], stats)
3097
+ printWorktreeGuidance({ projectRoot: process.cwd(), interactive: true })
1691
3098
  }
1692
3099
 
1693
3100
  // -----------------------------------------------------------------------
1694
- // 5. Model preset selection (--components agents). Interactive wizard runs
1695
- // unless autoYes (use defaults) or an explicit --preset was given.
3101
+ // 5. V1 model preset selection (--components agents). V2 ignores the legacy
3102
+ // active-preset marker, so it has no profile wizard or --preset support.
3103
+ // The V1 interactive wizard runs unless autoYes or an explicit preset was given.
1696
3104
  // Q1 default "herdar do chat" (inherit) writes no active-preset.json —
1697
3105
  // delegates inherit the parent chat model (native inheritance).
1698
3106
  // -----------------------------------------------------------------------
1699
- if (interactive && !dryRun && !autoYes && !opts.preset) {
3107
+ if (interactive && stdinTTY && version === 'v1' && !dryRun && !autoYes && !opts.preset) {
1700
3108
  const { runInitWizard } = await import('./model-picker.mjs')
1701
- await runInitWizard({ presetDir: target, logger: console })
3109
+ await runInitWizard({ presetDir: target, logger: console, prompts: opts.deps?.prompts })
1702
3110
  }
1703
3111
 
1704
3112
  if (opts.preset && !dryRun) {
1705
3113
  const { writeActivePreset } = await import('./model-picker.mjs')
1706
- writeActivePreset(target, opts.preset, { source: 'cli' })
3114
+ writeActivePreset(target, opts.preset, { source: 'cli', updatedAt: planTimestamp, recorder })
3115
+ }
3116
+
3117
+ // -----------------------------------------------------------------------
3118
+ // 5.5 Optional vision prompt (interactive TTY only). The default — automatic
3119
+ // discovery — writes nothing, and non-interactive flows (no TTY, --yes,
3120
+ // --headless, automated sandboxes) never reach this block, so no run
3121
+ // blocks on stdin and the default behavior is unchanged. A failure here
3122
+ // must never fail the install: vision stays optional.
3123
+ // -----------------------------------------------------------------------
3124
+ if (interactive && !dryRun && !autoYes) {
3125
+ const runVisionPrompt =
3126
+ opts.deps?.runVisionPrompt ?? (await import('./vision-prompt.mjs')).runVisionPrompt
3127
+ try {
3128
+ await runVisionPrompt({ logger: console })
3129
+ } catch (err) {
3130
+ warning(`Vision setup skipped: ${err instanceof Error ? err.message : String(err)}`)
3131
+ }
1707
3132
  }
1708
3133
 
1709
3134
  // Fail-closed: accumulated stats.errors (bad sources, missing requirements,
@@ -1718,18 +3143,81 @@ export async function installOpenCode(
1718
3143
  // to `doctor` forever. Unselected components retain their previous state.
1719
3144
  if (!dryRun) {
1720
3145
  const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
1721
- let state = readState(target)
3146
+ let state = projectedState ?? readState(target)
1722
3147
  if (!state && hasState(target)) {
1723
3148
  throw new Error('Installation state exists but cannot be read; refusing to replace it')
1724
3149
  }
1725
- state ??= createInitialState(packageVersion)
3150
+ state ??= createInitialState(packageVersion, planTimestamp)
1726
3151
  state.pantheon_version = packageVersion
3152
+ state.updated_at = planTimestamp
1727
3153
  for (const component of ['agents', 'skills', 'plugins', 'runtime']) {
1728
3154
  if (!componentSet.has(component)) continue
1729
3155
  const status = component === 'runtime' && !runtimeHealthy ? 'failed' : 'installed'
1730
3156
  const componentVersion = state.components?.[component]?.version ?? 1
1731
3157
  setComponentState(state, component, componentVersion, status)
1732
3158
  }
1733
- writeState(target, state)
3159
+ const verifiedFiles = summarizeChanges(ownRecorder?.entries ?? []).files.flatMap((file) => {
3160
+ if (!['create', 'update', 'unchanged'].includes(file.action) || !file.outputFingerprint)
3161
+ return []
3162
+ const owner = componentForInstalledPath(target, file.path, { isGlobal, version })
3163
+ if (!owner) return []
3164
+ return [
3165
+ {
3166
+ path: file.path,
3167
+ sha256: file.outputFingerprint,
3168
+ component: owner.component,
3169
+ layout: owner.layout,
3170
+ action: file.action,
3171
+ },
3172
+ ]
3173
+ })
3174
+ const stateStep = step(S.recordingState)
3175
+ updateFileInventory(state, target, {
3176
+ selectedComponents: [...componentSet],
3177
+ verifiedFiles,
3178
+ })
3179
+ writeState(target, state, { updatedAt: planTimestamp })
3180
+ stateStep(true)
3181
+ advancePhase()
3182
+ }
3183
+
3184
+ // The apply gauge ends before the human summary; a dry run already closed it
3185
+ // before its plan block (`done()` is idempotent). A preview must NOT print
3186
+ // the installed banner: bin/pantheon-init prints the preview-only line.
3187
+ progress?.done()
3188
+ if (!interactive && !dryRun && !opts.planOnly) {
3189
+ printSummary(target, ['opencode'], stats)
1734
3190
  }
3191
+
3192
+ // Beta 11 Setup phase 3: report whether this call APPLIED, so the caller can
3193
+ // avoid a success banner for a plan-only / unauthorized run. The dry pass also
3194
+ // returns the planned-target snapshots for the apply pass's drift check.
3195
+ return dryRun
3196
+ ? {
3197
+ ...stats,
3198
+ applied: false,
3199
+ reason: 'plan',
3200
+ planned: plannedChanges,
3201
+ snapshots: plannedSnapshots,
3202
+ files: planFiles,
3203
+ totals: planTotals,
3204
+ mcpServers,
3205
+ removals: removalPaths,
3206
+ target,
3207
+ openCodeVersion: version,
3208
+ versionAssumed,
3209
+ configAdvisories,
3210
+ v2Capabilities: version === 'v2' ? v2Capabilities() : null,
3211
+ pluginOptions: v2PluginOptions,
3212
+ }
3213
+ : {
3214
+ ...stats,
3215
+ applied: true,
3216
+ reason: 'applied',
3217
+ target,
3218
+ openCodeVersion: version,
3219
+ configAdvisories,
3220
+ v2Capabilities: version === 'v2' ? v2Capabilities() : null,
3221
+ pluginOptions: v2PluginOptions,
3222
+ }
1735
3223
  }