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
@@ -20,27 +20,57 @@
20
20
  * "skills": { "version": 1, "status": "installed" },
21
21
  * "plugins": { "version": 1, "status": "installed" },
22
22
  * "runtime": { "version": 1, "status": "installed" }
23
+ * },
24
+ * "file_inventory": {
25
+ * "schema_version": 1, "target_root": "/absolute/target",
26
+ * "legacy_unknown": false, "entries": []
23
27
  * }
24
28
  * }
25
29
  */
26
30
 
27
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
28
- import { join } from 'node:path'
31
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
32
+ import { join, resolve } from 'node:path'
33
+ import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
29
34
 
30
35
  const STATE_FILE = 'install-state.json'
31
36
  const STATE_DIR = '.pantheon'
32
37
 
38
+ function emptyFileInventory(legacyUnknown = true) {
39
+ return {
40
+ schema_version: 1,
41
+ target_root: null,
42
+ legacy_unknown: legacyUnknown,
43
+ entries: [],
44
+ }
45
+ }
46
+
47
+ function invalidFileInventory() {
48
+ return { schema_version: 0, target_root: null, legacy_unknown: true, entries: [] }
49
+ }
50
+
51
+ function normalizeFileInventory(state) {
52
+ if (!Object.hasOwn(state, 'file_inventory')) return emptyFileInventory(true)
53
+ if (
54
+ !state.file_inventory ||
55
+ typeof state.file_inventory !== 'object' ||
56
+ Array.isArray(state.file_inventory)
57
+ ) {
58
+ return invalidFileInventory()
59
+ }
60
+ return state.file_inventory
61
+ }
62
+
33
63
  /**
34
64
  * Create a fresh v2 state object for a new install.
35
65
  * @param {string} version - Pantheon version string
36
66
  * @returns {object} v2 state
37
67
  */
38
- export function createInitialState(version) {
68
+ export function createInitialState(version, updatedAt = new Date().toISOString()) {
39
69
  return {
40
70
  schema_version: 2,
41
71
  pantheon_version: version || '0.0.0',
42
72
  previous_version: null,
43
- updated_at: new Date().toISOString(),
73
+ updated_at: updatedAt,
44
74
  migration_checkpoint: null,
45
75
  applied_migrations: [],
46
76
  components: {
@@ -49,6 +79,7 @@ export function createInitialState(version) {
49
79
  plugins: { version: 1, status: 'pending' },
50
80
  runtime: { version: 1, status: 'pending' },
51
81
  },
82
+ file_inventory: emptyFileInventory(false),
52
83
  }
53
84
  }
54
85
 
@@ -104,6 +135,7 @@ export function upgradeStateV1toV2(state) {
104
135
  plugins: { version: 1, status: 'unknown' },
105
136
  runtime: { version: 1, status: 'unknown' },
106
137
  },
138
+ file_inventory: normalizeFileInventory(state),
107
139
  }
108
140
  }
109
141
 
@@ -129,6 +161,14 @@ function ensureV2Shape(state) {
129
161
  ) {
130
162
  state.components = upgradeStateV1toV2(state).components
131
163
  }
164
+ if (!Object.hasOwn(state, 'file_inventory')) state.file_inventory = emptyFileInventory(true)
165
+ else if (
166
+ !state.file_inventory ||
167
+ typeof state.file_inventory !== 'object' ||
168
+ Array.isArray(state.file_inventory)
169
+ ) {
170
+ state.file_inventory = invalidFileInventory()
171
+ }
132
172
  return state
133
173
  }
134
174
 
@@ -149,15 +189,30 @@ function normalizeState(state) {
149
189
  * @param {string} target - Installation directory
150
190
  * @param {object} state - v2 state object
151
191
  */
152
- export function writeState(target, state) {
192
+ export function writeState(target, state, options = {}) {
153
193
  const stateDir = join(target, STATE_DIR)
194
+ const stateFile = join(stateDir, STATE_FILE)
195
+ assertNoSymlinkAncestors(stateFile)
154
196
  if (!existsSync(stateDir)) {
155
197
  mkdirSync(stateDir, { recursive: true })
156
198
  }
157
- const stateFile = join(stateDir, STATE_FILE)
158
- state.updated_at = new Date().toISOString()
199
+ assertNoSymlinkAncestors(stateFile)
200
+ state.updated_at = options.updatedAt ?? new Date().toISOString()
159
201
  state.schema_version = 2
160
- writeFileSync(stateFile, `${JSON.stringify(state, null, 2)}\n`, 'utf8')
202
+ if (!Object.hasOwn(state, 'file_inventory')) {
203
+ state.file_inventory = emptyFileInventory(true)
204
+ } else if (
205
+ !state.file_inventory ||
206
+ typeof state.file_inventory !== 'object' ||
207
+ Array.isArray(state.file_inventory)
208
+ ) {
209
+ state.file_inventory = invalidFileInventory()
210
+ }
211
+ if (state.file_inventory.target_root == null) {
212
+ state.file_inventory.target_root = resolve(target)
213
+ }
214
+ const content = `${JSON.stringify(state, null, 2)}\n`
215
+ writeFileAtomically(stateFile, content)
161
216
  }
162
217
 
163
218
  /**
@@ -16,13 +16,17 @@ const TABLE = {
16
16
  dryRun: 'DRY RUN',
17
17
  canceled: 'Installation canceled — nothing was broken; run init again anytime.',
18
18
  canceledShort: 'Installation canceled.',
19
- installFailed: (msg) => `❌ Installation failed: ${msg}`,
19
+ installFailed: (msg) => `Installation failed: ${msg}`,
20
20
  failHintNoMcp:
21
21
  ' Run with --no-mcp to skip Python dependencies:\n npx pantheon-opencode init --no-mcp',
22
22
  failHintForce:
23
23
  ' Or retry with --force to recreate the venv:\n npx pantheon-opencode init --force',
24
24
  runningHealthCheck: 'Running health check...',
25
- installedTitle: (v) => `✅ Pantheon OpenCode v${v} installed!`,
25
+ healthCheckFinished: (seconds, status) =>
26
+ `Health check finished in ${seconds}s (exit ${status})`,
27
+ healthCheckExit: (seconds, status) =>
28
+ `Health check finished in ${seconds}s and reported problems (exit ${status}); the installation itself completed`,
29
+ installedTitle: (v) => `Pantheon OpenCode v${v} installed.`,
26
30
  nextSteps: 'Next steps:',
27
31
  nextVerify: '1. Verify installation:\n npx pantheon-opencode doctor',
28
32
  nextLaunch: '2. Launch OpenCode',
@@ -37,7 +41,17 @@ const TABLE = {
37
41
  installingPrompts: 'Installing prompts',
38
42
  installingCommands: 'Installing commands',
39
43
  installingPlugins: 'Installing plugins',
44
+ installingTuiDeps: 'Installing TUI dependencies',
45
+ creatingBackup: 'Creating exact backup set',
46
+ planningBackup: 'Planning backup set',
47
+ checkingPrerequisites: 'Checking prerequisites',
48
+ installingRuntime: 'Installing runtime',
49
+ writingConfiguration: 'Writing configuration',
50
+ writingConfig: 'Writing opencode.json',
51
+ runningMigrations: 'Running migrations',
52
+ recordingState: 'Recording install state',
40
53
  settingUpRuntime: 'Setting up Python virtual environment',
54
+ runtimeVerifiedAfterApply: 'Python runtime will be verified after apply',
41
55
  healthSection: 'Health Check',
42
56
  runningHealthChecks: 'Running health checks',
43
57
  runtimeFailed: (msg) => `Python runtime setup failed: ${msg}`,
@@ -46,7 +60,21 @@ const TABLE = {
46
60
  'Fix python3 (or free disk space) and re-run init to add them; everything else was installed.',
47
61
  prereqMissing:
48
62
  'runtime prerequisites missing — install the tools above, or re-run with --no-mcp to install without Python MCP servers',
63
+ mcpAskNotEnforceable: (server) =>
64
+ `MCP permission "permission.mcp.${server} = ask" is not enforceable on OpenCode 2.x: ` +
65
+ `the server's tools remain available and no permission prompt is shown. ` +
66
+ `Use "deny" with action "${server}_*" in "permissions", or disable the server in the host MCP config.`,
49
67
  v2Migrating: 'Migrating config to V2 native format...',
68
+ nothingApplied: 'Nothing applied.',
69
+ planOnlyNoYes: 'Plan only — re-run with --yes to apply.',
70
+ driftHeader: 'State changed since preview — aborting before any write:',
71
+ driftAbort: 'No files were written. Re-run to re-review.',
72
+ applyFailed: (msg) => `Apply failed: ${msg}`,
73
+ alreadyApplied: 'Paths already applied — no automatic rollback:',
74
+ restoreRecoveryHint: (dir) => `Recover with: pantheon-opencode restore (backup at ${dir})`,
75
+ restoreNoBackup:
76
+ 'No backup was created (the failure occurred before the first write); the target is unchanged.',
77
+ dryRunNothingWritten: 'Preview only — no files were written.',
50
78
  // summary (printSummary)
51
79
  summaryInstalled: (target) => `OpenCode installed in ${target}`,
52
80
  summaryWithErrors: (target) => `Installation finished WITH ERRORS in ${target}`,
@@ -64,13 +92,17 @@ const TABLE = {
64
92
  dryRun: 'SIMULAÇÃO',
65
93
  canceled: 'Instalação cancelada — nada foi quebrado; rode init de novo quando quiser.',
66
94
  canceledShort: 'Instalação cancelada.',
67
- installFailed: (msg) => `❌ Instalação falhou: ${msg}`,
95
+ installFailed: (msg) => `Instalação falhou: ${msg}`,
68
96
  failHintNoMcp:
69
97
  ' Rode com --no-mcp para pular dependências Python:\n npx pantheon-opencode init --no-mcp',
70
98
  failHintForce:
71
99
  ' Ou tente de novo com --force para recriar a venv:\n npx pantheon-opencode init --force',
72
100
  runningHealthCheck: 'Rodando verificação de saúde...',
73
- installedTitle: (v) => `✅ Pantheon OpenCode v${v} instalado!`,
101
+ healthCheckFinished: (seconds, status) =>
102
+ `Verificação de saúde concluída em ${seconds}s (exit ${status})`,
103
+ healthCheckExit: (seconds, status) =>
104
+ `Verificação de saúde concluída em ${seconds}s e reportou problemas (exit ${status}); a instalação em si foi concluída`,
105
+ installedTitle: (v) => `Pantheon OpenCode v${v} instalado.`,
74
106
  nextSteps: 'Próximos passos:',
75
107
  nextVerify: '1. Verifique a instalação:\n npx pantheon-opencode doctor',
76
108
  nextLaunch: '2. Abra o OpenCode',
@@ -85,7 +117,17 @@ const TABLE = {
85
117
  installingPrompts: 'Instalando prompts',
86
118
  installingCommands: 'Instalando comandos',
87
119
  installingPlugins: 'Instalando plugins',
120
+ installingTuiDeps: 'Instalando dependências da TUI',
121
+ creatingBackup: 'Criando conjunto de backup exato',
122
+ planningBackup: 'Planejando conjunto de backup',
123
+ checkingPrerequisites: 'Verificando pré-requisitos',
124
+ installingRuntime: 'Instalando runtime',
125
+ writingConfiguration: 'Escrevendo configuração',
126
+ writingConfig: 'Escrevendo opencode.json',
127
+ runningMigrations: 'Executando migrações',
128
+ recordingState: 'Registrando estado da instalação',
88
129
  settingUpRuntime: 'Configurando ambiente virtual Python',
130
+ runtimeVerifiedAfterApply: 'O runtime Python será verificado após a aplicação',
89
131
  healthSection: 'Verificação de saúde',
90
132
  runningHealthChecks: 'Rodando verificações de saúde',
91
133
  runtimeFailed: (msg) => `Falha ao configurar o runtime Python: ${msg}`,
@@ -94,7 +136,21 @@ const TABLE = {
94
136
  'Corrija o python3 (ou libere espaço em disco) e rode init de novo para adicioná-los; todo o resto foi instalado.',
95
137
  prereqMissing:
96
138
  'pré-requisitos do runtime ausentes — instale as ferramentas acima, ou rode de novo com --no-mcp para instalar sem os MCPs Python',
139
+ mcpAskNotEnforceable: (server) =>
140
+ `A permissão MCP "permission.mcp.${server} = ask" não é aplicável no OpenCode 2.x: ` +
141
+ `as tools do servidor continuam disponíveis e nenhum prompt de permissão é exibido. ` +
142
+ `Use "deny" com a action "${server}_*" em "permissions", ou desative o servidor na config de MCP do host.`,
97
143
  v2Migrating: 'Migrando config para o formato nativo V2...',
144
+ nothingApplied: 'Nada foi aplicado.',
145
+ planOnlyNoYes: 'Apenas o plano — rode de novo com --yes para aplicar.',
146
+ driftHeader: 'O estado mudou desde o preview — abortando antes de qualquer escrita:',
147
+ driftAbort: 'Nenhum arquivo foi escrito. Rode de novo para revisar.',
148
+ applyFailed: (msg) => `Falha ao aplicar: ${msg}`,
149
+ alreadyApplied: 'Caminhos já aplicados — sem rollback automático:',
150
+ restoreRecoveryHint: (dir) => `Recupere com: pantheon-opencode restore (backup em ${dir})`,
151
+ restoreNoBackup:
152
+ 'Nenhum backup foi criado (a falha ocorreu antes da primeira escrita); o alvo está intacto.',
153
+ dryRunNothingWritten: 'Somente prévia — nenhum arquivo foi escrito.',
98
154
  // summary (printSummary)
99
155
  summaryInstalled: (target) => `OpenCode instalado em ${target}`,
100
156
  summaryWithErrors: (target) => `Instalação concluída COM ERROS em ${target}`,
@@ -10,10 +10,13 @@
10
10
  */
11
11
 
12
12
  import { spawnSync } from 'node:child_process'
13
- import { existsSync, rmSync } from 'node:fs'
13
+ import { existsSync } from 'node:fs'
14
14
  import { dirname, join } from 'node:path'
15
15
  import { fileURLToPath } from 'node:url'
16
16
 
17
+ import { configure, info, step, success, warning } from './cli-ui.mjs'
18
+ import { ACTIONS, recordChange, recordRemovalTree, removeReviewedTree } from './plan.mjs'
19
+
17
20
  const __dirname = dirname(fileURLToPath(import.meta.url))
18
21
  const ROOT = join(__dirname, '..', '..')
19
22
 
@@ -40,37 +43,61 @@ export function venvPythonPath(target) {
40
43
  * Set up a Python virtual environment and install MCP dependencies.
41
44
  *
42
45
  * @param {string} target - Target installation directory (e.g. ~/.config/opencode)
43
- * @param {{ dryRun?: boolean, skipInstall?: boolean, force?: boolean }} [options]
46
+ * @param {{ dryRun?: boolean, skipInstall?: boolean, force?: boolean, recorder?: (change: object) => void, reviewedRemovals?: Set<string>|null, reviewedSnapshots?: Map<string, object>|null }} [options]
44
47
  * @returns {{ venvPath: string, python: string }}
45
48
  */
46
- export function setupVenv(target, { dryRun = false, skipInstall = false, force = false } = {}) {
49
+ export function setupVenv(
50
+ target,
51
+ {
52
+ dryRun = false,
53
+ skipInstall = false,
54
+ force = false,
55
+ recorder = null,
56
+ reviewedRemovals = null,
57
+ reviewedSnapshots = null,
58
+ } = {},
59
+ ) {
47
60
  const venvPath = join(target, '.venv')
48
61
  const pythonBin = venvPythonPath(target)
49
62
 
50
63
  // Step 1: Force recreate venv if --force
51
64
  if (force && existsSync(venvPath)) {
52
- if (!dryRun) {
53
- console.log(' Removing existing .venv (--force)...')
54
- rmSync(venvPath, { recursive: true })
65
+ if (dryRun) {
66
+ recordRemovalTree(venvPath, recorder)
67
+ info('.venv would be removed (--force)')
68
+ } else {
69
+ const removeStep = step('Removing existing .venv (--force)')
70
+ removeReviewedTree(venvPath, reviewedRemovals, reviewedSnapshots)
71
+ removeStep(true)
72
+ success('.venv removed')
55
73
  }
56
- console.log(' ✅ .venv removed')
57
74
  }
58
75
 
59
76
  // Step 1b: Create venv if not exists
60
- if (!existsSync(pythonBin)) {
61
- if (!dryRun) {
62
- console.log(' Creating .venv...')
77
+ const venvExists = existsSync(pythonBin)
78
+ if (!venvExists) {
79
+ if (dryRun) {
80
+ // Never claim a directory was created by a run that writes nothing.
81
+ info('.venv would be created')
82
+ } else {
83
+ const createStep = step('Creating .venv')
63
84
  const result = spawnSync('python3', ['-m', 'venv', venvPath], {
64
85
  stdio: 'inherit',
65
86
  timeout: 30_000,
66
87
  })
67
88
  if (result.status !== 0) {
89
+ createStep(false)
68
90
  throw new Error('Failed to create virtual environment')
69
91
  }
92
+ createStep(true)
93
+ success('.venv created')
70
94
  }
71
- console.log(' ✅ .venv created')
95
+ // A single synthetic entry for the venv directory — never enumerate its
96
+ // thousands of files. Unscored: the install summary does not count it.
97
+ recordChange({ path: venvPath, action: ACTIONS.CREATE, bytes: 0, scored: false }, recorder)
72
98
  } else {
73
- console.log(' ⏭️ .venv already exists')
99
+ info('.venv already exists')
100
+ recordChange({ path: venvPath, action: ACTIONS.UNCHANGED, bytes: 0, scored: false }, recorder)
74
101
  }
75
102
 
76
103
  // Step 2: Install MCP dependencies
@@ -82,49 +109,64 @@ export function setupVenv(target, { dryRun = false, skipInstall = false, force =
82
109
  throw new Error(`Requirements file not found: ${reqFile}`)
83
110
  }
84
111
 
85
- console.log(' Installing MCP dependencies...')
86
-
87
112
  if (!dryRun) {
88
- // Upgrade pip first (avoids resolver warnings)
89
- // Ensure PIP_USER=0 to install into venv, not user site-packages
90
- const pipEnv = { ...process.env, PIP_USER: '0' }
91
-
92
- spawnSync(pip, ['install', '--upgrade', 'pip'], {
93
- stdio: 'ignore',
94
- timeout: 30_000,
95
- env: pipEnv,
96
- })
97
-
98
- // Install requirements — attempt 1: normal
99
- const r = spawnSync(pip, ['install', '-r', reqFile], {
100
- stdio: 'inherit',
101
- timeout: 120_000,
102
- env: pipEnv,
103
- })
113
+ const depsStep = step('Installing MCP dependencies')
114
+ try {
115
+ // Upgrade pip first (avoids resolver warnings)
116
+ // Ensure PIP_USER=0 to install into venv, not user site-packages
117
+ const pipEnv = { ...process.env, PIP_USER: '0' }
118
+
119
+ // stdio is 'ignore' (pip is noisy here), so the step marker is the ONLY
120
+ // evidence this ran — report both start and outcome instead of a silent
121
+ // 30s pause.
122
+ const pipUpgradeStep = step('Upgrading pip')
123
+ const pipUpgrade = spawnSync(pip, ['install', '--upgrade', 'pip'], {
124
+ stdio: 'ignore',
125
+ timeout: 30_000,
126
+ env: pipEnv,
127
+ })
128
+ const upgraded = pipUpgrade.status === 0
129
+ pipUpgradeStep(upgraded)
130
+ if (!upgraded) warning('pip upgrade failed — continuing with the bundled version')
104
131
 
105
- if (r.status !== 0) {
106
- // Attempt 2: --break-system-packages (PEP 668 / externally-managed)
107
- console.log(' ⚠️ First attempt failed, retrying with --break-system-packages...')
108
- const r2 = spawnSync(pip, ['install', '-r', reqFile, '--break-system-packages'], {
132
+ // Install requirements — attempt 1: normal
133
+ const r = spawnSync(pip, ['install', '-r', reqFile], {
109
134
  stdio: 'inherit',
110
135
  timeout: 120_000,
111
136
  env: pipEnv,
112
137
  })
113
- if (r2.status !== 0) {
114
- throw new Error(
115
- 'Failed to install MCP dependencies. ' +
116
- 'Try: PIP_USER=0 ' +
117
- pip +
118
- ' install -r ' +
119
- reqFile +
120
- ' --break-system-packages',
121
- )
138
+
139
+ if (r.status !== 0) {
140
+ // Attempt 2: --break-system-packages (PEP 668 / externally-managed)
141
+ warning('First attempt failed, retrying with --break-system-packages...')
142
+ const r2 = spawnSync(pip, ['install', '-r', reqFile, '--break-system-packages'], {
143
+ stdio: 'inherit',
144
+ timeout: 120_000,
145
+ env: pipEnv,
146
+ })
147
+ if (r2.status !== 0) {
148
+ throw new Error(
149
+ 'Failed to install MCP dependencies. ' +
150
+ 'Try: PIP_USER=0 ' +
151
+ pip +
152
+ ' install -r ' +
153
+ reqFile +
154
+ ' --break-system-packages',
155
+ )
156
+ }
122
157
  }
158
+ depsStep(true)
159
+ success('MCP dependencies installed')
160
+ } catch (err) {
161
+ depsStep(false)
162
+ throw err
123
163
  }
164
+ } else {
165
+ // A dry run installs nothing: say so rather than reporting success.
166
+ info('MCP dependencies would be installed')
124
167
  }
125
- console.log(' ✅ MCP dependencies installed')
126
168
  } else {
127
- console.log(' ⏭️ Dependency install skipped (--skip-install)')
169
+ info('Dependency install skipped (--skip-install)')
128
170
  }
129
171
 
130
172
  return { venvPath, python: pythonBin }
@@ -140,12 +182,13 @@ function main() {
140
182
  const dryRun = args.includes('--dry-run')
141
183
  const skipInstall = args.includes('--skip-install')
142
184
  const force = args.includes('--force')
185
+ configure({ dryRun })
143
186
 
144
187
  try {
145
188
  const result = setupVenv(target, { dryRun, skipInstall, force })
146
- console.log(` 📍 Python: ${result.python}`)
189
+ info(`Python: ${result.python}`)
147
190
  } catch (err) {
148
- console.error(`\n ❌ ${err.message}`)
191
+ console.error(`\n [ERROR] ${err.message}`)
149
192
  process.exit(1)
150
193
  }
151
194
  }
@@ -0,0 +1,128 @@
1
+ import {
2
+ closeSync,
3
+ fsyncSync,
4
+ lstatSync,
5
+ openSync,
6
+ readFileSync,
7
+ renameSync,
8
+ unlinkSync,
9
+ writeFileSync,
10
+ } from 'node:fs'
11
+ import { isAbsolute, parse, relative, resolve, sep } from 'node:path'
12
+
13
+ /** Reject symlinked path components before a managed filesystem operation. */
14
+ export function assertNoSymlinkAncestors(filePath, { includeLeaf = true } = {}) {
15
+ const absolute = resolve(filePath)
16
+ const root = parse(absolute).root
17
+ const parts = absolute.slice(root.length).split(sep).filter(Boolean)
18
+ const checked = parts.slice(0, includeLeaf ? parts.length : Math.max(0, parts.length - 1))
19
+ let current = root
20
+ for (const [index, part] of checked.entries()) {
21
+ current = current ? `${current}${current.endsWith(sep) ? '' : sep}${part}` : part
22
+ let info
23
+ try {
24
+ info = lstatSync(current)
25
+ } catch (error) {
26
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return true
27
+ throw error
28
+ }
29
+ if (info.isSymbolicLink()) throw new Error(`Path contains a symlink: ${current}`)
30
+ if (index < checked.length - 1 && !info.isDirectory()) {
31
+ throw new Error(`Path ancestor is not a directory: ${current}`)
32
+ }
33
+ }
34
+ return true
35
+ }
36
+
37
+ /** Require a destination to remain lexically inside its selected target. */
38
+ export function assertPathWithin(rootPath, destinationPath) {
39
+ const root = resolve(rootPath)
40
+ const destination = resolve(destinationPath)
41
+ const fromRoot = relative(root, destination)
42
+ if (fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
43
+ throw new Error(`Path escapes selected target: ${destinationPath}`)
44
+ }
45
+ return true
46
+ }
47
+
48
+ /** Validate lexical containment and reject links before deleting a path. */
49
+ export function assertSafeRemoval(rootPath, destinationPath) {
50
+ assertPathWithin(rootPath, destinationPath)
51
+ assertNoSymlinkAncestors(destinationPath)
52
+ return true
53
+ }
54
+
55
+ /** Read back a regular-file write without ever including file contents in errors. */
56
+ export function verifyRegularFile(filePath, expected) {
57
+ const info = lstatSync(filePath)
58
+ if (!info.isFile() || info.isSymbolicLink()) {
59
+ throw new Error(`Managed-file write did not produce a regular file: ${filePath}`)
60
+ }
61
+ const actual = readFileSync(filePath)
62
+ const expectedBuffer = Buffer.isBuffer(expected) ? expected : Buffer.from(expected)
63
+ if (!actual.equals(expectedBuffer)) {
64
+ throw new Error(`Managed-file read-back verification failed: ${filePath}`)
65
+ }
66
+ return true
67
+ }
68
+
69
+ /**
70
+ * Atomically write a managed file using a private, exclusively-created temp.
71
+ * Existing destinations are replaced only after path checks and a temp read-back.
72
+ */
73
+ export function writeFileAtomically(filePath, content) {
74
+ const temporary = `${filePath}.tmp-${process.pid}`
75
+ assertNoSymlinkAncestors(filePath)
76
+ assertRegularFileOrMissing(filePath)
77
+ assertNoSymlinkAncestors(temporary)
78
+
79
+ let fd
80
+ let createdTemporary = false
81
+ try {
82
+ fd = openSync(temporary, 'wx', 0o600)
83
+ createdTemporary = true
84
+ writeFileSync(fd, content)
85
+ fsyncSync(fd)
86
+ closeSync(fd)
87
+ fd = undefined
88
+
89
+ verifyRegularFile(temporary, content)
90
+ assertNoSymlinkAncestors(filePath)
91
+ assertRegularFileOrMissing(filePath)
92
+ renameSync(temporary, filePath)
93
+ createdTemporary = false
94
+ verifyRegularFile(filePath, content)
95
+ } finally {
96
+ if (fd !== undefined) closeSync(fd)
97
+ if (createdTemporary) {
98
+ try {
99
+ assertNoSymlinkAncestors(temporary)
100
+ unlinkSync(temporary)
101
+ } catch {
102
+ // Preserve the write error; do not follow or remove an unsafe path.
103
+ }
104
+ }
105
+ }
106
+ }
107
+
108
+ function assertRegularFileOrMissing(filePath) {
109
+ try {
110
+ const info = lstatSync(filePath)
111
+ if (!info.isFile() || info.isSymbolicLink()) {
112
+ throw new Error(`Refusing to replace non-regular file: ${filePath}`)
113
+ }
114
+ } catch (error) {
115
+ if (error?.code !== 'ENOENT') throw error
116
+ }
117
+ }
118
+
119
+ /** Verify a managed path was removed, without following symlinks. */
120
+ export function verifyPathRemoved(filePath) {
121
+ try {
122
+ lstatSync(filePath)
123
+ } catch (error) {
124
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return true
125
+ throw error
126
+ }
127
+ throw new Error(`Managed-path removal verification failed: ${filePath}`)
128
+ }