pantheon-opencode 1.6.0-beta.9 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -376
  4. package/README.md +83 -610
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +19 -11
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +828 -40
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +78 -383
  29. package/scripts/install/migrate.mjs +49 -25
  30. package/scripts/install/model-picker.mjs +218 -250
  31. package/scripts/install/opencode-version.mjs +83 -21
  32. package/scripts/install/opencode.mjs +1413 -154
  33. package/scripts/install/plan-artifact.mjs +517 -0
  34. package/scripts/install/plan.mjs +475 -0
  35. package/scripts/install/plugin.mjs +214 -27
  36. package/scripts/install/prompt-result.mjs +2 -0
  37. package/scripts/install/shared.mjs +256 -99
  38. package/scripts/install/state.mjs +63 -8
  39. package/scripts/install/strings.mjs +60 -4
  40. package/scripts/install/venv.mjs +90 -47
  41. package/scripts/install/verify.mjs +128 -0
  42. package/scripts/install/vision-prompt.mjs +173 -0
  43. package/scripts/install-mcp.mjs +2 -2
  44. package/scripts/manifest-inventory.mjs +49 -3
  45. package/scripts/mcp_persistence.py +1535 -1050
  46. package/scripts/memory_mcp.py +12 -843
  47. package/scripts/node-engine-policy.mjs +85 -0
  48. package/scripts/package-evidence.mjs +10 -2
  49. package/scripts/postinstall.mjs +26 -26
  50. package/scripts/probe-pantheon-cost.mjs +118 -19
  51. package/scripts/prune.mjs +9 -3
  52. package/scripts/reconcile.mjs +325 -0
  53. package/scripts/release-gates.mjs +682 -0
  54. package/scripts/restore.mjs +222 -0
  55. package/scripts/run-node-tests.mjs +24 -8
  56. package/scripts/sync-artifacts.mjs +19 -7
  57. package/scripts/sync-tui.mjs +5 -1
  58. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  59. package/scripts/uninstall.mjs +369 -34
  60. package/scripts/update.mjs +164 -0
  61. package/scripts/validate-node-engine-policy.mjs +13 -0
  62. package/scripts/version-check.mjs +34 -1
  63. package/scripts/versioning.mjs +23 -3
  64. package/scripts/vision-status.mjs +682 -0
  65. package/skills-lock.json +8 -8
  66. package/src/agents/aphrodite.md +13 -10
  67. package/src/agents/apollo.md +4 -5
  68. package/src/agents/athena.md +74 -46
  69. package/src/agents/demeter.md +10 -7
  70. package/src/agents/gaia.md +0 -1
  71. package/src/agents/hephaestus.md +4 -3
  72. package/src/agents/hermes.md +10 -9
  73. package/src/agents/iris.md +6 -1
  74. package/src/agents/mnemosyne.md +10 -4
  75. package/src/agents/nyx.md +4 -4
  76. package/src/agents/prometheus.md +12 -11
  77. package/src/agents/talos.md +6 -0
  78. package/src/agents/zeus.md +84 -56
  79. package/src/instructions/agent-return-format.instructions.md +12 -41
  80. package/src/instructions/memory-protocol.instructions.md +5 -11
  81. package/src/instructions/test-economy.instructions.md +12 -0
  82. package/src/instructions/yagni.instructions.md +6 -15
  83. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  84. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  85. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  86. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  87. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  88. package/src/mcp/_pantheon_paths.py +24 -0
  89. package/src/mcp/mcp_codemap_module.py +86 -18
  90. package/src/mcp/mcp_persistence.py +1535 -1050
  91. package/src/mcp/memory_mcp.py +444 -94
  92. package/src/mcp/pantheon_vision.py +285 -41
  93. package/src/mcp/requirements-mcp.txt +5 -0
  94. package/src/pantheon/context-pruner.ts +541 -0
  95. package/src/pantheon/cost-command.ts +814 -60
  96. package/src/pantheon/goal-loop.ts +11 -8
  97. package/src/pantheon/memory-context.ts +1017 -0
  98. package/src/pantheon/model-agents.ts +19 -0
  99. package/src/pantheon/model-command.ts +218 -56
  100. package/src/pantheon/model-pricing.ts +536 -0
  101. package/src/pantheon/presets.mjs +2 -0
  102. package/src/pantheon/task-result-guard.ts +50 -14
  103. package/src/pantheon/v2-bounded-read.ts +640 -0
  104. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  105. package/src/pantheon/v2-execute-after.ts +135 -24
  106. package/src/pantheon/v2-model-overrides.ts +275 -0
  107. package/src/pantheon/v2-tools.ts +89 -35
  108. package/src/pantheon/v2-unsupported.mjs +2 -3
  109. package/src/pantheon/v2-vision.ts +622 -0
  110. package/src/pantheon/vision-local.ts +531 -0
  111. package/src/pantheon/vision.ts +1160 -115
  112. package/src/plugin-v2.ts +654 -162
  113. package/src/plugin.ts +15 -11
  114. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  115. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  117. package/src/plugins/tui/dist/tui.js +1 -1
  118. package/src/plugins/tui/package-lock.json +6 -6
  119. package/src/plugins/tui/package.json +5 -4
  120. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  121. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  122. package/src/routing.yml +50 -5
  123. package/src/skills/agent-coordination/SKILL.md +7 -2
  124. package/src/skills/artifact-management/SKILL.md +5 -1
  125. package/src/skills/auto-continue/SKILL.md +14 -6
  126. package/src/skills/codemap/SKILL.md +1 -1
  127. package/src/skills/memory-bank/SKILL.md +21 -13
  128. package/src/skills/session-goal/SKILL.md +12 -22
  129. package/src/skills/spec-driven-development/SKILL.md +3 -1
  130. package/src/skills/worktrees/SKILL.md +30 -11
  131. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -6,6 +6,19 @@ import { homedir } from 'node:os'
6
6
  import { basename, join, relative, resolve } from 'node:path'
7
7
  import { createInterface } from 'node:readline'
8
8
  import { isatty } from 'node:tty'
9
+ import { backupWarning, createBackupSet } from './install/backup.mjs'
10
+ import {
11
+ CONTEXT_SIDEBAR_NEGATION,
12
+ V2_CLI_CONFIG_FILENAME,
13
+ withContextSidebarEnabled,
14
+ } from './install/opencode.mjs'
15
+ import { snapshot } from './install/plan.mjs'
16
+ import { writeConfigWithBackup } from './install/shared.mjs'
17
+ import {
18
+ assertNoSymlinkAncestors,
19
+ verifyPathRemoved,
20
+ verifyRegularFile,
21
+ } from './install/verify.mjs'
9
22
 
10
23
  const AGENT_NAMES = new Set([
11
24
  'zeus',
@@ -26,12 +39,18 @@ const AGENT_NAMES = new Set([
26
39
  const OWNERSHIP_MARKER =
27
40
  /(?:pantheon-opencode|pantheon[- ]agent system|managed[- ]by[: ]+pantheon|pantheon-(?:resources|memory|persistence|code-mode|tui|hooks))/i
28
41
  const stats = { removed: 0, skipped: 0, errors: 0 }
42
+ let touchedPaths = new Set()
43
+ // Paths that survive the uninstall but were REWRITTEN (not removed), so the
44
+ // plan summary can label them UPDATE instead of REMOVE without guessing from
45
+ // the basename.
46
+ let rewrittenPaths = new Set()
47
+ let quietPreview = false
29
48
 
30
49
  function showHelp() {
31
50
  console.log(`
32
51
 
33
52
  Usage:
34
- node scripts/uninstall.mjs [--project|--global] [--target /path] [--dry-run] [--force]
53
+ node scripts/uninstall.mjs [--project|--global] [--target /path] [--dry-run] [--force] [--purge-data]
35
54
 
36
55
  Target may be a project directory (containing .opencode), or a flat global
37
56
  OpenCode directory (~/.config/opencode or ~/.opencode). Symlinks are rejected.
@@ -39,7 +58,14 @@ OpenCode directory (~/.config/opencode or ~/.opencode). Symlinks are rejected.
39
58
  }
40
59
 
41
60
  function parseArgs(argv) {
42
- const args = { target: process.cwd(), dryRun: false, force: false, help: false, scope: 'project' }
61
+ const args = {
62
+ target: process.cwd(),
63
+ dryRun: false,
64
+ force: false,
65
+ purgeData: false,
66
+ help: false,
67
+ scope: 'project',
68
+ }
43
69
  let explicitTarget = false
44
70
  for (let index = 2; index < argv.length; index += 1) {
45
71
  const option = argv[index]
@@ -55,6 +81,7 @@ function parseArgs(argv) {
55
81
  args.scope = 'global'
56
82
  } else if (option === '--dry-run') args.dryRun = true
57
83
  else if (option === '--force') args.force = true
84
+ else if (option === '--purge-data') args.purgeData = true
58
85
  else if (option === '--help') args.help = true
59
86
  else if (option === '--platforms')
60
87
  throw new Error('--platforms was removed; this uninstaller supports OpenCode only')
@@ -131,8 +158,19 @@ function isPantheonRouting(path) {
131
158
  }
132
159
  }
133
160
 
134
- function removePath(path, dryRun, root, label = path) {
135
- if (!isInside(path, root) || isSymlink(path)) {
161
+ function assertReviewedPath(path, reviewedPaths) {
162
+ if (reviewedPaths && !reviewedPaths.has(path)) {
163
+ throw new Error(`Uninstall operation set drifted; refusing unreviewed path: ${path}`)
164
+ }
165
+ }
166
+
167
+ function removePath(path, dryRun, root, label = path, reviewedPaths = null) {
168
+ if (!isInside(path, root)) {
169
+ stats.skipped += 1
170
+ return false
171
+ }
172
+ assertNoSymlinkAncestors(path, { includeLeaf: false })
173
+ if (isSymlink(path)) {
136
174
  stats.skipped += 1
137
175
  return false
138
176
  }
@@ -141,10 +179,15 @@ function removePath(path, dryRun, root, label = path) {
141
179
  stats.skipped += 1
142
180
  return false
143
181
  }
144
- if (dryRun) console.log(` ~ Would remove ${label}`)
145
- else {
182
+ assertReviewedPath(path, reviewedPaths)
183
+ touchedPaths.add(path)
184
+ if (dryRun) {
185
+ if (!quietPreview) console.log(` ~ Would remove ${label}`)
186
+ } else {
146
187
  try {
188
+ assertNoSymlinkAncestors(path, { includeLeaf: false })
147
189
  rmSync(path, { recursive: info.isDirectory(), force: false })
190
+ verifyPathRemoved(path)
148
191
  } catch (error) {
149
192
  console.error(` ⚠️ Failed to remove ${path}: ${error.message}`)
150
193
  stats.errors += 1
@@ -155,7 +198,8 @@ function removePath(path, dryRun, root, label = path) {
155
198
  return true
156
199
  }
157
200
 
158
- function removeMatchingEntries(directory, predicate, dryRun, root) {
201
+ function removeMatchingEntries(directory, predicate, dryRun, root, reviewedPaths = null) {
202
+ assertNoSymlinkAncestors(directory, { includeLeaf: false })
159
203
  const info = lstat(directory)
160
204
  if (!info || info.isSymbolicLink() || !info.isDirectory()) {
161
205
  stats.skipped += 1
@@ -168,12 +212,19 @@ function removeMatchingEntries(directory, predicate, dryRun, root) {
168
212
  stats.skipped += 1
169
213
  continue
170
214
  }
171
- if (predicate(path, entry)) removePath(path, dryRun, root, path)
172
- else if (child.isDirectory()) removeMatchingEntries(path, predicate, dryRun, root)
215
+ if (predicate(path, entry)) removePath(path, dryRun, root, path, reviewedPaths)
216
+ else if (child.isDirectory())
217
+ removeMatchingEntries(path, predicate, dryRun, root, reviewedPaths)
173
218
  }
174
219
  const remaining = lstat(directory)
175
- if (remaining?.isDirectory() && readdirSync(directory).length === 0)
176
- removePath(directory, dryRun, root, directory)
220
+ const scheduledRemaining = readdirSync(directory).filter(
221
+ (entry) => !touchedPaths.has(join(directory, entry)),
222
+ )
223
+ if (
224
+ remaining?.isDirectory() &&
225
+ (dryRun ? scheduledRemaining.length === 0 : readdirSync(directory).length === 0)
226
+ )
227
+ removePath(directory, dryRun, root, directory, reviewedPaths)
177
228
  }
178
229
 
179
230
  function readJson(path) {
@@ -214,7 +265,7 @@ function ownedMcpEntry(name, value) {
214
265
  )
215
266
  }
216
267
 
217
- function cleanOpenCodeConfig(target, dryRun, ownedRoot = target) {
268
+ function cleanOpenCodeConfig(target, dryRun, ownedRoot = target, reviewedPaths = null) {
218
269
  const configPath = join(target, 'opencode.json')
219
270
  const config = readJson(configPath)
220
271
  if (!config) {
@@ -286,8 +337,17 @@ function cleanOpenCodeConfig(target, dryRun, ownedRoot = target) {
286
337
  stats.skipped += 1
287
338
  return
288
339
  }
289
- if (dryRun) console.log(' ~ Would update opencode.json (remove Pantheon-owned entries)')
290
- else writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
340
+ assertReviewedPath(configPath, reviewedPaths)
341
+ touchedPaths.add(configPath)
342
+ rewrittenPaths.add(configPath)
343
+ const content = `${JSON.stringify(config, null, 2)}\n`
344
+ if (dryRun) {
345
+ if (!quietPreview) console.log(' ~ Would update opencode.json (remove Pantheon-owned entries)')
346
+ } else {
347
+ assertNoSymlinkAncestors(configPath)
348
+ writeFileSync(configPath, content, 'utf8')
349
+ verifyRegularFile(configPath, content)
350
+ }
291
351
  stats.removed += 1
292
352
  }
293
353
 
@@ -299,9 +359,39 @@ function configDirFor(target) {
299
359
  : join(target, '.opencode')
300
360
  }
301
361
 
302
- function uninstallOpenCode(target, dryRun) {
362
+ function verifiedInstallState(root) {
363
+ const statePath = join(root, '.pantheon', 'install-state.json')
364
+ assertNoSymlinkAncestors(statePath)
365
+ const info = lstat(statePath)
366
+ if (!info) return null
367
+ if (info.isSymbolicLink() || !info.isFile()) {
368
+ throw new Error('Refusing to purge install state that is not a regular file')
369
+ }
370
+ let state
371
+ try {
372
+ state = JSON.parse(readFileSync(statePath, 'utf8'))
373
+ } catch {
374
+ throw new Error('Refusing to purge unverified install state')
375
+ }
376
+ if (
377
+ state?.schema_version !== 2 ||
378
+ typeof state.pantheon_version !== 'string' ||
379
+ !state.components ||
380
+ typeof state.components !== 'object' ||
381
+ Array.isArray(state.components)
382
+ )
383
+ throw new Error('Refusing to purge unverified install state')
384
+ return statePath
385
+ }
386
+
387
+ function runUninstallPass(target, dryRun, { purgeData = false, reviewedPaths = null } = {}) {
303
388
  const root = resolve(target)
304
- if (isSymlink(root)) throw new Error(`Target must not be a symlink: ${root}`)
389
+ assertNoSymlinkAncestors(root)
390
+ const rootInfo = lstat(root)
391
+ if (!rootInfo?.isDirectory() || rootInfo.isSymbolicLink()) {
392
+ throw new Error(`Target must be a directory and not a symlink: ${root}`)
393
+ }
394
+ const statePath = purgeData ? verifiedInstallState(root) : null
305
395
  const configDir = configDirFor(root)
306
396
  const configInfo = lstat(configDir)
307
397
  if (configInfo?.isSymbolicLink()) {
@@ -309,29 +399,57 @@ function uninstallOpenCode(target, dryRun) {
309
399
  return
310
400
  }
311
401
  const ownedRoot = root
312
- cleanOpenCodeConfig(root, dryRun, ownedRoot)
402
+ cleanOpenCodeConfig(root, dryRun, ownedRoot, reviewedPaths)
313
403
  removeMatchingEntries(
314
404
  join(configDir, 'agents'),
315
405
  (_path, name) => AGENT_NAMES.has(name.replace(/\.md$/, '')) && isPantheonContent(_path),
316
406
  dryRun,
317
407
  ownedRoot,
408
+ reviewedPaths,
318
409
  )
319
410
  for (const directory of ['skills', 'commands', 'plugins'])
320
- removeMatchingEntries(join(configDir, directory), isPantheonContent, dryRun, ownedRoot)
411
+ removeMatchingEntries(
412
+ join(configDir, directory),
413
+ isPantheonContent,
414
+ dryRun,
415
+ ownedRoot,
416
+ reviewedPaths,
417
+ )
321
418
  for (const file of ['package.json', 'tsconfig.json', 'routing.yml']) {
322
419
  const path = join(configDir, file)
323
420
  if (file === 'routing.yml' ? isPantheonRouting(path) : isPantheonContent(path))
324
- removePath(path, dryRun, ownedRoot, path)
421
+ removePath(path, dryRun, ownedRoot, path, reviewedPaths)
325
422
  }
326
423
  const tui = join(configDir, 'tui.json')
327
- cleanTuiConfig(tui, dryRun, ownedRoot)
424
+ cleanTuiConfig(tui, dryRun, ownedRoot, reviewedPaths)
425
+ cleanV2CliConfig(configDir, dryRun, ownedRoot, reviewedPaths)
328
426
  const agentsMd = join(root, 'AGENTS.md')
329
- if (isPantheonContent(agentsMd)) removePath(agentsMd, dryRun, ownedRoot, agentsMd)
330
- if (configInfo?.isDirectory() && readdirSync(configDir).length === 0)
331
- removePath(configDir, dryRun, ownedRoot, configDir)
427
+ if (isPantheonContent(agentsMd)) removePath(agentsMd, dryRun, ownedRoot, agentsMd, reviewedPaths)
428
+ const scheduledConfigEntries = configInfo?.isDirectory()
429
+ ? readdirSync(configDir).filter((entry) => !touchedPaths.has(join(configDir, entry)))
430
+ : []
431
+ // A flat global target is also the backup store's config root. Keep it so
432
+ // backups remain discoverable/restorable after uninstall; only nested
433
+ // project `.opencode` directories are eligible for removal here.
434
+ if (
435
+ configInfo?.isDirectory() &&
436
+ resolve(configDir) !== root &&
437
+ (dryRun ? scheduledConfigEntries.length === 0 : readdirSync(configDir).length === 0)
438
+ )
439
+ removePath(configDir, dryRun, ownedRoot, configDir, reviewedPaths)
440
+ if (statePath) {
441
+ assertReviewedPath(statePath, reviewedPaths)
442
+ touchedPaths.add(statePath)
443
+ if (dryRun) {
444
+ if (!quietPreview) console.log(` ~ Would purge verified install state ${statePath}`)
445
+ } else {
446
+ removePath(statePath, false, ownedRoot, statePath, reviewedPaths)
447
+ }
448
+ }
449
+ return [...touchedPaths]
332
450
  }
333
451
 
334
- function cleanTuiConfig(path, dryRun, root) {
452
+ function cleanTuiConfig(path, dryRun, root, reviewedPaths = null) {
335
453
  const config = readJson(path)
336
454
  if (!config || !Array.isArray(config.plugin)) {
337
455
  stats.skipped += 1
@@ -345,17 +463,215 @@ function cleanTuiConfig(path, dryRun, root) {
345
463
  return
346
464
  }
347
465
  config.plugin = plugin
348
- if (dryRun) console.log(' ~ Would update tui.json (remove Pantheon-owned plugin references)')
349
- else writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
466
+ assertReviewedPath(path, reviewedPaths)
467
+ touchedPaths.add(path)
468
+ rewrittenPaths.add(path)
469
+ const content = `${JSON.stringify(config, null, 2)}\n`
470
+ if (dryRun) {
471
+ if (!quietPreview)
472
+ console.log(' ~ Would update tui.json (remove Pantheon-owned plugin references)')
473
+ } else {
474
+ assertNoSymlinkAncestors(path)
475
+ writeFileSync(path, content, 'utf8')
476
+ verifyRegularFile(path, content)
477
+ }
350
478
  stats.removed += 1
351
479
  }
352
480
 
481
+ /**
482
+ * Undo the V2 client-config directive that cancels the builtin Context block.
483
+ *
484
+ * `init` (V2, global, `plugins` component) appends
485
+ * {@link CONTEXT_SIDEBAR_NEGATION} to `<configDir>/cli.json` so Pantheon's TUI
486
+ * plugin can draw the Context block itself. Leaving that negation behind while
487
+ * removing the TUI plugin does not just leave a stale entry: it DISABLES the
488
+ * host's native block with no replacement installed, and `cli.json` is not a
489
+ * file the remaining cleanup would ever revisit. So uninstall must undo exactly
490
+ * the same edit install made.
491
+ *
492
+ * Mirrors {@link applyContextSidebarNegation} on the write path: only the exact
493
+ * directive is dropped (`withContextSidebarEnabled`), every other entry — plain
494
+ * strings and `{ package, options }` objects — and every other key keeps its
495
+ * order, and the write goes through `writeConfigWithBackup` with the raw text
496
+ * as `expectedContent`, so a concurrent edit is never clobbered.
497
+ *
498
+ * Removal policy:
499
+ * - only the negation present → nothing to do, skipped;
500
+ * - after the removal `plugins` is empty AND it was the only key → the file
501
+ * carries nothing but our directive, so the whole file goes;
502
+ * - otherwise the file stays (it is the user's config, possibly with other
503
+ * plugins and keys).
504
+ *
505
+ * Unparseable JSON — or a `plugins` value that is not an array — is never
506
+ * touched: warn and continue.
507
+ *
508
+ * @param {string} configDir - config dir that holds cli.json
509
+ * @param {boolean} dryRun - report the action without writing
510
+ * @param {string} root - target root every removal must stay inside
511
+ * @param {Set<string>|null} [reviewedPaths] - paths reviewed in the plan
512
+ */
513
+ function cleanV2CliConfig(configDir, dryRun, root, reviewedPaths = null) {
514
+ const path = join(configDir, V2_CLI_CONFIG_FILENAME)
515
+ const info = lstat(path)
516
+ if (!info?.isFile() || info.isSymbolicLink()) {
517
+ stats.skipped += 1
518
+ return
519
+ }
520
+ let raw
521
+ try {
522
+ raw = readFileSync(path, 'utf8')
523
+ } catch {
524
+ stats.skipped += 1
525
+ return
526
+ }
527
+ let config
528
+ try {
529
+ config = JSON.parse(raw)
530
+ } catch {
531
+ if (!quietPreview) console.warn(` ⚠️ Left ${path} untouched: it is not valid JSON.`)
532
+ stats.skipped += 1
533
+ return
534
+ }
535
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
536
+ stats.skipped += 1
537
+ return
538
+ }
539
+ if (!Array.isArray(config.plugins)) {
540
+ stats.skipped += 1
541
+ return
542
+ }
543
+
544
+ const next = withContextSidebarEnabled(config.plugins)
545
+ if (!next.changed) {
546
+ stats.skipped += 1
547
+ return
548
+ }
549
+ assertReviewedPath(path, reviewedPaths)
550
+
551
+ // `{ plugins: [] }` and nothing else is the stub this installer created; an
552
+ // empty leftover would be orphaned by the rest of the uninstall.
553
+ if (next.plugins.length === 0 && Object.keys(config).length === 1) {
554
+ removePath(path, dryRun, root, path, reviewedPaths)
555
+ return
556
+ }
557
+
558
+ config.plugins = next.plugins
559
+ const content = `${JSON.stringify(config, null, 2)}\n`
560
+ touchedPaths.add(path)
561
+ rewrittenPaths.add(path)
562
+ if (dryRun) {
563
+ if (!quietPreview)
564
+ console.log(` ~ Would update ${V2_CLI_CONFIG_FILENAME} (remove ${CONTEXT_SIDEBAR_NEGATION})`)
565
+ stats.removed += 1
566
+ return
567
+ }
568
+ const status = writeConfigWithBackup(path, content, dryRun, { expectedContent: raw })
569
+ if (status === 'conflict') {
570
+ // Edited under us between the read and the swap: keep the newer bytes.
571
+ console.warn(` ⚠️ Left ${path} untouched: it changed during the uninstall.`)
572
+ stats.skipped += 1
573
+ return
574
+ }
575
+ stats.removed += 1
576
+ }
577
+
578
+ function resetRunState() {
579
+ stats.removed = 0
580
+ stats.skipped = 0
581
+ stats.errors = 0
582
+ touchedPaths = new Set()
583
+ rewrittenPaths = new Set()
584
+ }
585
+
586
+ function collectUninstallPlan(target, options = {}) {
587
+ resetRunState()
588
+ const previousQuiet = quietPreview
589
+ quietPreview = true
590
+ try {
591
+ const paths = runUninstallPass(target, true, options) ?? []
592
+ return {
593
+ paths,
594
+ snapshots: paths.map((path) => ({ path, ...snapshot(path) })),
595
+ }
596
+ } finally {
597
+ quietPreview = previousQuiet
598
+ }
599
+ }
600
+
601
+ function uninstallOpenCode(target, dryRun, options = {}) {
602
+ resetRunState()
603
+ if (dryRun) {
604
+ const paths = runUninstallPass(target, true, options) ?? []
605
+ return { paths, snapshots: paths.map((path) => ({ path, ...snapshot(path) })) }
606
+ }
607
+
608
+ const reviewed = options.reviewedPlan ?? collectUninstallPlan(target, options)
609
+ const root = resolve(target)
610
+ const reviewedPaths = new Set(reviewed.paths)
611
+ if (reviewedPaths.size !== reviewed.paths.length) {
612
+ throw new Error('Uninstall reviewed plan contains duplicate paths')
613
+ }
614
+ const reviewedSnapshotPaths = new Set(reviewed.snapshots.map((item) => item.path))
615
+ if (
616
+ reviewedSnapshotPaths.size !== reviewed.snapshots.length ||
617
+ reviewedSnapshotPaths.size !== reviewedPaths.size ||
618
+ [...reviewedPaths].some((path) => !reviewedSnapshotPaths.has(path))
619
+ ) {
620
+ throw new Error('Uninstall reviewed plan operation set is invalid')
621
+ }
622
+ const currentPlan = collectUninstallPlan(target, options)
623
+ const currentPaths = [...currentPlan.paths].sort()
624
+ const expectedPaths = [...reviewedPaths].sort()
625
+ if (JSON.stringify(currentPaths) !== JSON.stringify(expectedPaths)) {
626
+ throw new Error('Uninstall operation set drifted before backup')
627
+ }
628
+ for (const expected of reviewed.snapshots) {
629
+ if (!isInside(expected.path, root))
630
+ throw new Error(`Uninstall path escaped target: ${expected.path}`)
631
+ const current = { path: expected.path, ...snapshot(expected.path) }
632
+ if (JSON.stringify(current) !== JSON.stringify(expected)) {
633
+ throw new Error(`Uninstall target drifted before backup: ${expected.path}`)
634
+ }
635
+ }
636
+
637
+ const backupEntries = reviewed.paths.filter((path) => {
638
+ const info = lstat(path)
639
+ return info?.isFile() && !info.isSymbolicLink()
640
+ })
641
+ let backupDir = null
642
+ if (backupEntries.length > 0) {
643
+ const backup = createBackupSet({
644
+ configDir: root,
645
+ entries: backupEntries.map((path) => relative(root, path)),
646
+ packageVersion: 'uninstall',
647
+ keep: 0,
648
+ })
649
+ backupDir = backup.dir
650
+ console.warn(backupWarning(backup.dir))
651
+ }
652
+
653
+ const applyPlan = collectUninstallPlan(target, options)
654
+ if (JSON.stringify([...applyPlan.paths].sort()) !== JSON.stringify(expectedPaths)) {
655
+ throw new Error('Uninstall operation set drifted after backup')
656
+ }
657
+ for (const expected of reviewed.snapshots) {
658
+ const current = { path: expected.path, ...snapshot(expected.path) }
659
+ if (JSON.stringify(current) !== JSON.stringify(expected)) {
660
+ throw new Error(`Uninstall target drifted after backup: ${expected.path}`)
661
+ }
662
+ }
663
+
664
+ resetRunState()
665
+ const paths = runUninstallPass(target, false, { ...options, reviewedPaths }) ?? []
666
+ return { paths, backupDir }
667
+ }
668
+
353
669
  function dirname(path) {
354
670
  return path.slice(0, path.lastIndexOf('/'))
355
671
  }
356
672
 
357
673
  async function confirmPrompt(message) {
358
- if (!isatty(process.stdin.fd)) return true
674
+ if (!isatty(process.stdin.fd) || !isatty(process.stdout.fd)) return false
359
675
  const readline = createInterface({ input: process.stdin, output: process.stdout })
360
676
  return new Promise((answer) =>
361
677
  readline.question(message, (value) => {
@@ -371,14 +687,33 @@ async function main() {
371
687
  const info = lstat(args.target)
372
688
  if (!info?.isDirectory() || info.isSymbolicLink())
373
689
  throw new Error(`Target directory does not exist or is a symlink: ${args.target}`)
374
- if (
375
- !args.dryRun &&
376
- !args.force &&
377
- !(await confirmPrompt(`⚠️ Remove Pantheon OpenCode artifacts from ${args.target}? [y/N] `))
378
- )
379
- return console.log('❌ Uninstall cancelled.')
690
+ const reviewedPlan = collectUninstallPlan(args.target, { purgeData: args.purgeData })
691
+ const hasChanges = reviewedPlan.paths.length > 0
380
692
  console.log(`${args.dryRun ? '🔍 Dry-run' : '🗑️ Uninstall'}: OpenCode/Pantheon only`)
381
- uninstallOpenCode(args.target, args.dryRun)
693
+ for (const path of reviewedPlan.paths) {
694
+ const purge =
695
+ args.purgeData && path === join(resolve(args.target), '.pantheon', 'install-state.json')
696
+ const update = rewrittenPaths.has(path) && !purge
697
+ console.log(` ${purge ? 'PURGE DATA' : update ? 'UPDATE' : 'REMOVE'} ${path}`)
698
+ }
699
+ if (args.dryRun) {
700
+ console.log(
701
+ `✅ ${stats.removed} would change, ${stats.skipped} skipped, ${stats.errors} errors`,
702
+ )
703
+ return
704
+ }
705
+ if (hasChanges && !args.force) {
706
+ if (!isatty(process.stdin.fd) || !isatty(process.stdout.fd)) {
707
+ console.error('❌ Non-interactive uninstall requires explicit --force authorization.')
708
+ process.exitCode = 2
709
+ return
710
+ }
711
+ if (!(await confirmPrompt(`⚠️ Apply this uninstall plan for ${args.target}? [y/N] `))) {
712
+ console.log('❌ Uninstall cancelled; no files were changed.')
713
+ return
714
+ }
715
+ }
716
+ uninstallOpenCode(args.target, false, { purgeData: args.purgeData, reviewedPlan })
382
717
  console.log(`✅ ${stats.removed} removed, ${stats.skipped} skipped, ${stats.errors} errors`)
383
718
  if (stats.errors) process.exitCode = 1
384
719
  }
@@ -0,0 +1,164 @@
1
+ import { spawnSync as nodeSpawnSync } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { assertNoSymlinkAncestors } from './install/verify.mjs'
5
+
6
+ function parseVersion(version) {
7
+ const match = String(version)
8
+ .trim()
9
+ .match(/^(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?$/)
10
+ if (!match) return null
11
+ return {
12
+ core: [+match[1], +match[2], +match[3]],
13
+ beta: match[4] === undefined ? Number.POSITIVE_INFINITY : +match[4],
14
+ }
15
+ }
16
+
17
+ function compareVersions(left, right) {
18
+ const a = parseVersion(left)
19
+ const b = parseVersion(right)
20
+ if (!a || !b) return 0
21
+ for (let index = 0; index < 3; index += 1) {
22
+ if (a.core[index] !== b.core[index]) return a.core[index] - b.core[index]
23
+ }
24
+ return a.beta - b.beta
25
+ }
26
+
27
+ /** Update only the authorized global installation, then refresh its config. */
28
+ export function runUpdate(
29
+ args,
30
+ {
31
+ root,
32
+ currentVersion,
33
+ runningScript = process.argv[1],
34
+ execPath = process.execPath,
35
+ spawnSync = nodeSpawnSync,
36
+ refresh,
37
+ },
38
+ ) {
39
+ const channel = args.includes('--stable') ? 'latest' : 'beta'
40
+ const globalRootResult = spawnSync('npm', ['root', '-g'], {
41
+ encoding: 'utf8',
42
+ timeout: 10_000,
43
+ })
44
+ let globalPackageRoot = null
45
+ let runningPackageRoot = null
46
+ let runningScriptPath = null
47
+ try {
48
+ const npmGlobalRoot = (globalRootResult.stdout || '').trim()
49
+ if (globalRootResult.status === 0 && npmGlobalRoot) {
50
+ // Check the lexical npm root before realpath: a linked ancestor can make
51
+ // a workspace path look identical to an actual global package after
52
+ // canonicalization.
53
+ assertNoSymlinkAncestors(npmGlobalRoot)
54
+ const actualGlobalRoot = fs.realpathSync(npmGlobalRoot)
55
+ const installedEntry = path.join(actualGlobalRoot, 'pantheon-opencode')
56
+ const installedEntryStat = fs.lstatSync(installedEntry)
57
+ const runningRootStat = fs.lstatSync(path.resolve(root))
58
+ const runningScriptStat = fs.lstatSync(path.resolve(runningScript))
59
+ // A global npm link into a checkout resolves to the same realpath as the
60
+ // running source. Do not treat that provenance as a global installation.
61
+ if (
62
+ installedEntryStat.isSymbolicLink() ||
63
+ !installedEntryStat.isDirectory() ||
64
+ runningRootStat.isSymbolicLink() ||
65
+ !runningRootStat.isDirectory() ||
66
+ runningScriptStat.isSymbolicLink() ||
67
+ !runningScriptStat.isFile()
68
+ ) {
69
+ throw new Error('Global package identity is not a regular installed package')
70
+ }
71
+ globalPackageRoot = fs.realpathSync(installedEntry)
72
+ runningPackageRoot = fs.realpathSync(path.resolve(root))
73
+ runningScriptPath = fs.realpathSync(path.resolve(runningScript))
74
+ }
75
+ } catch {
76
+ // Missing, linked, or uncertain package identity is not authorized.
77
+ }
78
+ if (
79
+ !globalPackageRoot ||
80
+ path.resolve(root) !== globalPackageRoot ||
81
+ globalPackageRoot !== runningPackageRoot ||
82
+ runningScriptPath !== path.join(globalPackageRoot, 'bin', 'pantheon-init.mjs')
83
+ ) {
84
+ console.error(
85
+ '❌ update is available only from the global Pantheon installation; local, workspace, and npx copies are refused. ' +
86
+ 'Install globally with `npm install -g pantheon-opencode@beta`, then run `pantheon-opencode update`.',
87
+ )
88
+ return 1
89
+ }
90
+
91
+ console.log(`Pantheon OpenCode v${currentVersion} — checking the "${channel}" channel...`)
92
+ const view = spawnSync('npm', ['view', `pantheon-opencode@${channel}`, 'version'], {
93
+ encoding: 'utf8',
94
+ timeout: 30_000,
95
+ })
96
+ const latest = (view.stdout || '').trim().split('\n').filter(Boolean).pop()
97
+ if (view.status !== 0 || !latest) {
98
+ console.error(
99
+ `❌ Could not reach the npm registry: ${(view.stderr || view.stdout || '').trim() || 'no version returned'}`,
100
+ )
101
+ return 1
102
+ }
103
+
104
+ if (compareVersions(latest, currentVersion) <= 0) {
105
+ console.log(
106
+ `✅ Already up to date (installed v${currentVersion}; ${channel} channel: v${latest}).`,
107
+ )
108
+ return 0
109
+ }
110
+
111
+ console.log(`Updating v${currentVersion} → v${latest} (channel: ${channel})...`)
112
+ const install = spawnSync('npm', ['install', '-g', `pantheon-opencode@${channel}`], {
113
+ stdio: 'inherit',
114
+ })
115
+ if (install.status !== 0) {
116
+ console.error(
117
+ '❌ npm install failed; npm global replacement is not atomic and may have partially changed the package. ' +
118
+ 'Verify the global install with `pantheon-opencode --version` or reinstall the package.',
119
+ )
120
+ return install.status ?? 1
121
+ }
122
+
123
+ let refreshedPackageRoot = null
124
+ let refreshedVersion = null
125
+ try {
126
+ const refreshedRootResult = spawnSync('npm', ['root', '-g'], {
127
+ encoding: 'utf8',
128
+ timeout: 10_000,
129
+ })
130
+ if (refreshedRootResult.status === 0) {
131
+ const refreshedGlobalRoot = fs.realpathSync((refreshedRootResult.stdout || '').trim())
132
+ const refreshedEntry = path.join(refreshedGlobalRoot, 'pantheon-opencode')
133
+ const refreshedEntryStat = fs.lstatSync(refreshedEntry)
134
+ if (refreshedEntryStat.isSymbolicLink() || !refreshedEntryStat.isDirectory()) {
135
+ throw new Error('Refreshed global package identity is not a regular installed package')
136
+ }
137
+ refreshedPackageRoot = fs.realpathSync(refreshedEntry)
138
+ refreshedVersion = JSON.parse(
139
+ fs.readFileSync(path.join(refreshedPackageRoot, 'package.json'), 'utf8'),
140
+ ).version
141
+ }
142
+ } catch {
143
+ // The post-install check reports an incomplete package refresh.
144
+ }
145
+ if (refreshedVersion !== latest || !refreshedPackageRoot) {
146
+ console.error(
147
+ `❌ npm reported success, but the global package is v${refreshedVersion ?? 'unknown'} (expected v${latest}); config refresh was not run.`,
148
+ )
149
+ return 1
150
+ }
151
+
152
+ const globalEntry = path.join(refreshedPackageRoot, 'bin', 'pantheon-init.mjs')
153
+ const init = refresh
154
+ ? refresh(globalEntry)
155
+ : spawnSync(execPath, [globalEntry, 'init', '--yes', '--headless'], { stdio: 'inherit' })
156
+ if (init.status !== 0 || init.error) {
157
+ console.error(
158
+ '⚠️ Updated, but the config refresh did not complete — run `npx pantheon-opencode init` manually.',
159
+ )
160
+ return init.status ?? 1
161
+ }
162
+ console.log(`✅ Updated to v${latest}.`)
163
+ return 0
164
+ }