pantheon-opencode 1.6.0-beta.8 → 1.6.0

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