pantheon-opencode 1.6.0-beta.9 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +144 -365
  4. package/README.md +124 -607
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +504 -141
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +22 -13
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +850 -45
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +99 -383
  29. package/scripts/install/interrupt.mjs +78 -0
  30. package/scripts/install/migrate.mjs +49 -25
  31. package/scripts/install/model-picker.mjs +218 -250
  32. package/scripts/install/opencode-state.mjs +91 -0
  33. package/scripts/install/opencode-version.mjs +83 -21
  34. package/scripts/install/opencode.mjs +1675 -187
  35. package/scripts/install/plan-artifact.mjs +517 -0
  36. package/scripts/install/plan.mjs +475 -0
  37. package/scripts/install/plugin.mjs +214 -27
  38. package/scripts/install/prompt-result.mjs +2 -0
  39. package/scripts/install/run-record.mjs +115 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +93 -8
  43. package/scripts/install/v2-capabilities.mjs +205 -0
  44. package/scripts/install/venv.mjs +90 -47
  45. package/scripts/install/verify.mjs +128 -0
  46. package/scripts/install/vision-prompt.mjs +173 -0
  47. package/scripts/install-mcp.mjs +2 -2
  48. package/scripts/manifest-inventory.mjs +49 -3
  49. package/scripts/mcp_persistence.py +1535 -1050
  50. package/scripts/memory_mcp.py +12 -843
  51. package/scripts/node-engine-policy.mjs +85 -0
  52. package/scripts/package-evidence.mjs +10 -2
  53. package/scripts/postinstall.mjs +26 -26
  54. package/scripts/probe-pantheon-cost.mjs +118 -19
  55. package/scripts/prune.mjs +9 -3
  56. package/scripts/reconcile.mjs +325 -0
  57. package/scripts/release-gates.mjs +687 -0
  58. package/scripts/restore.mjs +222 -0
  59. package/scripts/run-node-tests.mjs +24 -8
  60. package/scripts/sync-artifacts.mjs +19 -7
  61. package/scripts/sync-tui.mjs +5 -1
  62. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  63. package/scripts/uninstall.mjs +369 -34
  64. package/scripts/update.mjs +164 -0
  65. package/scripts/validate-node-engine-policy.mjs +13 -0
  66. package/scripts/version-check.mjs +34 -1
  67. package/scripts/versioning.mjs +23 -3
  68. package/scripts/vision-status.mjs +682 -0
  69. package/skills-lock.json +8 -8
  70. package/src/agents/aphrodite.md +13 -10
  71. package/src/agents/apollo.md +4 -5
  72. package/src/agents/athena.md +74 -46
  73. package/src/agents/demeter.md +10 -7
  74. package/src/agents/gaia.md +0 -1
  75. package/src/agents/hephaestus.md +4 -3
  76. package/src/agents/hermes.md +10 -9
  77. package/src/agents/iris.md +6 -1
  78. package/src/agents/mnemosyne.md +10 -4
  79. package/src/agents/nyx.md +4 -4
  80. package/src/agents/prometheus.md +12 -11
  81. package/src/agents/talos.md +6 -0
  82. package/src/agents/zeus.md +84 -56
  83. package/src/instructions/agent-return-format.instructions.md +12 -41
  84. package/src/instructions/memory-protocol.instructions.md +5 -11
  85. package/src/instructions/test-economy.instructions.md +12 -0
  86. package/src/instructions/yagni.instructions.md +6 -15
  87. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  88. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  89. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  90. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  91. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  92. package/src/mcp/_pantheon_paths.py +24 -0
  93. package/src/mcp/mcp_codemap_module.py +86 -18
  94. package/src/mcp/mcp_persistence.py +1535 -1050
  95. package/src/mcp/memory_mcp.py +444 -94
  96. package/src/mcp/pantheon_vision.py +285 -41
  97. package/src/mcp/requirements-mcp.txt +6 -1
  98. package/src/mcp/requirements-vision.txt +1 -1
  99. package/src/pantheon/context-pruner.ts +541 -0
  100. package/src/pantheon/cost-command.ts +901 -60
  101. package/src/pantheon/delegation-enforce.ts +160 -23
  102. package/src/pantheon/goal-loop.ts +11 -8
  103. package/src/pantheon/guard-path.ts +162 -0
  104. package/src/pantheon/memory-context.ts +1017 -0
  105. package/src/pantheon/model-agents.ts +19 -0
  106. package/src/pantheon/model-command.ts +218 -56
  107. package/src/pantheon/model-pricing.ts +536 -0
  108. package/src/pantheon/presets.mjs +2 -0
  109. package/src/pantheon/task-result-guard.ts +50 -14
  110. package/src/pantheon/v2-bounded-read.ts +654 -0
  111. package/src/pantheon/v2-bridge.ts +27 -0
  112. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  113. package/src/pantheon/v2-execute-after.ts +135 -24
  114. package/src/pantheon/v2-model-overrides.ts +275 -0
  115. package/src/pantheon/v2-shell-hooks.ts +260 -0
  116. package/src/pantheon/v2-tools.ts +89 -35
  117. package/src/pantheon/v2-unsupported.mjs +34 -7
  118. package/src/pantheon/v2-vision.ts +622 -0
  119. package/src/pantheon/vision-local.ts +531 -0
  120. package/src/pantheon/vision.ts +1166 -116
  121. package/src/plugin-v2.ts +1039 -171
  122. package/src/plugin.ts +37 -13
  123. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  124. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  125. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  126. package/src/plugins/tui/dist/tui.js +1 -1
  127. package/src/plugins/tui/package-lock.json +15 -15
  128. package/src/plugins/tui/package.json +7 -5
  129. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  130. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  131. package/src/routing.yml +50 -5
  132. package/src/skills/agent-coordination/SKILL.md +7 -2
  133. package/src/skills/artifact-management/SKILL.md +5 -1
  134. package/src/skills/auto-continue/SKILL.md +14 -6
  135. package/src/skills/codemap/SKILL.md +1 -1
  136. package/src/skills/memory-bank/SKILL.md +21 -13
  137. package/src/skills/session-goal/SKILL.md +12 -22
  138. package/src/skills/spec-driven-development/SKILL.md +3 -1
  139. package/src/skills/worktrees/SKILL.md +30 -11
  140. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -0,0 +1,475 @@
1
+ /**
2
+ * plan.mjs — Per-file change planning for the Pantheon installer.
3
+ *
4
+ * Beta 11, Setup phase 1: `pantheon-opencode init ... --dry-run` must print the
5
+ * REAL per-file change set (create / update / remove / unchanged) that the SAME
6
+ * code path would produce, and write nothing.
7
+ *
8
+ * The plan is built by a change recorder threaded through the writer helpers as
9
+ * an OPTIONAL argument whose default is a module-level no-op singleton, so any
10
+ * caller (or writer) that is not instrumented keeps byte-identical behavior.
11
+ *
12
+ * NET-OUTCOME semantics: several writers can touch the same path in one pass
13
+ * (the TUI `unregister`→`register` toggle; the code-mode `syncDir` payload and
14
+ * its generated `manifest.json`). The LAST writer decides the net disk result,
15
+ * so a later no-write (skipped/unchanged) leaves the path UNCHANGED even when an
16
+ * earlier writer computed a would-be update. A no-write never promotes a path to
17
+ * a scored change.
18
+ *
19
+ * "Scored" vs "unscored": writers that increment the install summary
20
+ * (`stats.created`) alongside a genuine change are SCORED. Artifacts that are
21
+ * not part of that summary (the synthetic `.venv` entry, the state-only
22
+ * `.pantheon/install-state.json` write, the backup-set manifest, and the TUI
23
+ * stale-ref cleanup) are recorded UNSCORED so they still appear in the printed
24
+ * plan but never affect the consistency guard.
25
+ *
26
+ * Security: the recorder, the summary and the formatter deal in paths, actions
27
+ * and byte sizes ONLY. File contents and hashes stay internal — hashes are kept
28
+ * so a later phase can detect drift between a preview and an apply, and are
29
+ * never printed.
30
+ */
31
+
32
+ import { createHash } from 'node:crypto'
33
+ import { lstatSync, readdirSync, readFileSync, rmdirSync, unlinkSync } from 'node:fs'
34
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
35
+ import {
36
+ assertNoSymlinkAncestors,
37
+ assertPathWithin,
38
+ assertSafeRemoval,
39
+ verifyPathRemoved,
40
+ } from './verify.mjs'
41
+
42
+ /** The action vocabulary shared by the recorder, the summary and the formatter. */
43
+ export const ACTIONS = Object.freeze({
44
+ CREATE: 'create',
45
+ UPDATE: 'update',
46
+ REMOVE: 'remove',
47
+ UNCHANGED: 'unchanged',
48
+ CONFLICT: 'conflict',
49
+ })
50
+
51
+ const ACTION_VALUES = new Set(Object.values(ACTIONS))
52
+
53
+ /** Whether an action represents a real change to the target (not a no-write). */
54
+ function isChange(action) {
55
+ return action === ACTIONS.CREATE || action === ACTIONS.UPDATE || action === ACTIONS.REMOVE
56
+ }
57
+
58
+ // Display order for the formatted plan.
59
+ const DISPLAY_ORDER = Object.freeze([
60
+ ACTIONS.CREATE,
61
+ ACTIONS.UPDATE,
62
+ ACTIONS.REMOVE,
63
+ ACTIONS.CONFLICT,
64
+ ACTIONS.UNCHANGED,
65
+ ])
66
+
67
+ /**
68
+ * The module-level no-op recorder. Instrumented writers whose caller did not
69
+ * pass a recorder fall back to this, so their behavior is byte-identical to an
70
+ * uninstrumented run (no allocation, no side effects).
71
+ */
72
+ export function noopRecorder() {}
73
+
74
+ /** The default recorder instance — the no-op singleton. */
75
+ export const NOOP_RECORDER = noopRecorder
76
+
77
+ /**
78
+ * Whether a recorder will actually collect anything. Writers in hot loops use
79
+ * this to skip `Buffer.byteLength(content)` on the common (uninstrumented) path.
80
+ *
81
+ * @param {unknown} recorder
82
+ * @returns {boolean}
83
+ */
84
+ export function isRecording(recorder) {
85
+ return typeof recorder === 'function' && recorder !== NOOP_RECORDER
86
+ }
87
+
88
+ /** Normalize an arbitrary change into the `{ path, action, bytes, scored }` shape. */
89
+ function normalizeChange(change) {
90
+ const action = change && ACTION_VALUES.has(change.action) ? change.action : ACTIONS.UNCHANGED
91
+ return {
92
+ path: String(change?.path ?? ''),
93
+ action,
94
+ bytes: Number.isFinite(change?.bytes) ? change.bytes : 0,
95
+ outputFingerprint:
96
+ typeof change?.outputFingerprint === 'string' ? change.outputFingerprint : null,
97
+ // Scored by default: most writers feed the install summary. Synthetic and
98
+ // state-only entries opt out explicitly with `scored: false`.
99
+ scored: !(change && change.scored === false),
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Create a recorder that collects changes in memory. `recorder` is the function
105
+ * to thread into the writer helpers; `entries` holds the raw recorded changes.
106
+ *
107
+ * @returns {{ recorder: (change: object) => void, entries: object[] }}
108
+ */
109
+ export function createRecorder() {
110
+ const entries = []
111
+ const recorder = (change) => {
112
+ entries.push(normalizeChange(change))
113
+ }
114
+ return { recorder, entries }
115
+ }
116
+
117
+ /**
118
+ * Record a single change. Writers call this instead of touching fs bookkeeping.
119
+ * With no explicit recorder the module-level no-op singleton is used.
120
+ *
121
+ * @param {{ path: string, action: string, bytes?: number, scored?: boolean }} change
122
+ * @param {(change: object) => void} [recorder]
123
+ */
124
+ export function recordChange(change, recorder = NOOP_RECORDER) {
125
+ if (!isRecording(recorder)) return
126
+ recorder(normalizeChange(change))
127
+ }
128
+
129
+ /** Return the non-displayed SHA-256 fingerprint used by reviewed plan artifacts. */
130
+ export function fingerprintOutput(content) {
131
+ return createHash('sha256').update(content).digest('hex')
132
+ }
133
+
134
+ /** Sort helper: display order first, then path for determinism. */
135
+ function compareFiles(a, b) {
136
+ const order = DISPLAY_ORDER.indexOf(a.action) - DISPLAY_ORDER.indexOf(b.action)
137
+ if (order !== 0) return order
138
+ return a.path.localeCompare(b.path)
139
+ }
140
+
141
+ function zeroTotals() {
142
+ return { create: 0, update: 0, remove: 0, unchanged: 0, conflict: 0 }
143
+ }
144
+
145
+ /** Tally a change into one of the five action buckets. */
146
+ function tally(totals, action) {
147
+ if (Object.hasOwn(totals, action)) totals[action] += 1
148
+ }
149
+
150
+ /**
151
+ * Collapse recorded changes into the final change set: one entry per path,
152
+ * reflecting the NET disk outcome, plus totals.
153
+ *
154
+ * The last record for a path decides the action, so a later no-write wins over
155
+ * an earlier would-be write. A path is scored only if at least one of its
156
+ * CHANGE records was scored AND the net action is still a change — a no-write
157
+ * can never turn a path into a scored change.
158
+ *
159
+ * @param {object[]} entries
160
+ * @returns {{
161
+ * files: object[],
162
+ * totals: { create: number, update: number, remove: number, unchanged: number, conflict: number },
163
+ * scored: { create: number, update: number, remove: number, unchanged: number, conflict: number },
164
+ * }}
165
+ */
166
+ export function summarizeChanges(entries = []) {
167
+ const byPath = new Map()
168
+ for (const entry of entries ?? []) {
169
+ const change = normalizeChange(entry)
170
+ let record = byPath.get(change.path)
171
+ if (!record) {
172
+ record = {
173
+ path: change.path,
174
+ action: change.action,
175
+ bytes: change.bytes,
176
+ outputFingerprint: change.outputFingerprint,
177
+ scored: false,
178
+ }
179
+ byPath.set(change.path, record)
180
+ }
181
+ // The LAST writer decides the net on-disk outcome. A later no-write
182
+ // (skipped/unchanged) leaves the path unchanged even if an earlier writer
183
+ // computed a would-be update (e.g. unregister→register toggling).
184
+ record.action = change.action
185
+ record.bytes = change.bytes
186
+ record.outputFingerprint = change.outputFingerprint
187
+ // Only a genuine change can score a path; a no-write never does.
188
+ if (isChange(change.action) && change.scored) record.scored = true
189
+ }
190
+
191
+ const files = [...byPath.values()].sort(compareFiles)
192
+ for (const file of files) {
193
+ if (!isChange(file.action)) file.scored = false
194
+ }
195
+
196
+ const totals = zeroTotals()
197
+ const scored = zeroTotals()
198
+ for (const file of files) {
199
+ tally(totals, file.action)
200
+ if (file.scored) tally(scored, file.action)
201
+ }
202
+ return { files, totals, scored }
203
+ }
204
+
205
+ /** Human-readable byte size. The caller never sees raw bytes or hashes. */
206
+ function formatBytes(bytes) {
207
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
208
+ if (bytes < 1024) return `${bytes} B`
209
+ const kb = bytes / 1024
210
+ if (kb < 1024) return `${kb.toFixed(1)} KB`
211
+ return `${(kb / 1024).toFixed(1)} MB`
212
+ }
213
+
214
+ /** Path shown in the plan: relative to the target when it lives inside it. */
215
+ export function displayPath(target, filePath) {
216
+ if (!target) return filePath
217
+ const rel = relative(target, filePath)
218
+ if (rel === '') return '.'
219
+ return rel.startsWith('..') || isAbsolute(rel) ? filePath : rel
220
+ }
221
+
222
+ /**
223
+ * Render the secret-safe plan: paths + action + byte size ONLY. No contents,
224
+ * no hashes.
225
+ *
226
+ * Two non-file facts are printed when the caller supplies them, because a
227
+ * per-file plan alone does not answer "what will be configured?":
228
+ * * `mcpServers` — the MCP servers this pass seeds into opencode.json, in
229
+ * write order, with their count. Derived from the write path, never a
230
+ * separate hand-maintained list.
231
+ * * `versionAssumed` — the host generation could not be probed, so the plan
232
+ * assumes V1 and may diverge from an apply on a 2.x host.
233
+ *
234
+ * @param {string} target - install target (used to relativize paths)
235
+ * @param {{ files: object[], totals: object, mcpServers?: string[], versionAssumed?: boolean }} plan
236
+ * @param {{ perFile?: boolean }} [options] - `perFile: false` renders the
237
+ * summary (totals + MCP servers + "No files were written.") without the
238
+ * per-file list. That is the DEFAULT dry-run surface; the per-file list is
239
+ * opt-in via --verbose/--json.
240
+ * @returns {string}
241
+ */
242
+ export function formatChangePlan(target, plan, { perFile = true } = {}) {
243
+ const { files, totals } = plan
244
+ const lines = []
245
+ lines.push(`Change plan — ${target}`)
246
+ if (perFile) {
247
+ for (const file of files) {
248
+ const isWrite = file.action === ACTIONS.CREATE || file.action === ACTIONS.UPDATE
249
+ const size = isWrite ? ` (${formatBytes(file.bytes)})` : ''
250
+ lines.push(` ${file.action.padEnd(9)} ${displayPath(target, file.path)}${size}`)
251
+ }
252
+ lines.push(` ${'─'.repeat(28)}`)
253
+ }
254
+ lines.push(
255
+ ` ${totals.create} create · ${totals.update} update · ${totals.remove} remove · ` +
256
+ `${totals.conflict} conflict`,
257
+ )
258
+ if (Array.isArray(plan.mcpServers)) {
259
+ const names = plan.mcpServers
260
+ const servers =
261
+ names.length === 0 ? 'none (already configured or runtime skipped)' : names.join(', ')
262
+ lines.push(` MCP servers (${names.length}): ${servers}`)
263
+ }
264
+ if (plan.versionAssumed) {
265
+ lines.push(
266
+ ' OpenCode host generation unknown — this plan assumes V1 and may diverge from the ' +
267
+ 'apply. Pass --opencode-version v1|v2 to pin it.',
268
+ )
269
+ }
270
+ lines.push(' No files were written.')
271
+ return lines.join('\n')
272
+ }
273
+
274
+ /**
275
+ * Snapshot a path for later drift comparison. Hashes stay internal.
276
+ *
277
+ * @param {string} filePath
278
+ * @returns {{ exists: boolean, sha256: string|null, size: number, mode: number|null }}
279
+ */
280
+ export function snapshot(filePath) {
281
+ let stat
282
+ try {
283
+ stat = lstatSync(filePath)
284
+ } catch {
285
+ return { exists: false, sha256: null, size: 0, mode: null }
286
+ }
287
+ if (stat.isDirectory()) {
288
+ // Directory snapshots include the direct child inventory. Descendant
289
+ // directories/files are snapshotted separately by collectRemovalTree().
290
+ const entries = readdirSync(filePath, { withFileTypes: true })
291
+ .map((entry) => [
292
+ entry.name,
293
+ entry.isDirectory()
294
+ ? 'directory'
295
+ : entry.isFile()
296
+ ? 'file'
297
+ : entry.isSymbolicLink()
298
+ ? 'symlink'
299
+ : 'other',
300
+ ])
301
+ .sort(([left], [right]) => left.localeCompare(right))
302
+ return {
303
+ exists: true,
304
+ sha256: createHash('sha256').update(JSON.stringify(entries)).digest('hex'),
305
+ size: stat.size,
306
+ mode: stat.mode,
307
+ }
308
+ }
309
+ if (!stat.isFile()) {
310
+ return { exists: true, sha256: null, size: stat.size, mode: stat.mode }
311
+ }
312
+ let buffer
313
+ try {
314
+ buffer = readFileSync(filePath)
315
+ } catch {
316
+ return { exists: true, sha256: null, size: stat.size, mode: stat.mode }
317
+ }
318
+ return {
319
+ exists: true,
320
+ sha256: createHash('sha256').update(buffer).digest('hex'),
321
+ size: buffer.length,
322
+ mode: stat.mode,
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Enumerate a path and its complete subtree as removal operations with
328
+ * pre-apply snapshots. Symlinks are treated as leaf entries and never followed.
329
+ *
330
+ * @param {string} rootPath
331
+ * @returns {{path: string, snapshot: object}[]}
332
+ */
333
+ export function collectRemovalTree(rootPath) {
334
+ const entries = []
335
+ const visit = (filePath, allowMissing = false) => {
336
+ let stat
337
+ try {
338
+ stat = lstatSync(filePath)
339
+ } catch (error) {
340
+ if (allowMissing && error?.code === 'ENOENT') return
341
+ throw error
342
+ }
343
+ entries.push({ path: filePath, snapshot: snapshot(filePath) })
344
+ if (stat.isDirectory()) {
345
+ for (const name of readdirSync(filePath).sort()) visit(`${filePath}${sep}${name}`)
346
+ }
347
+ }
348
+ visit(rootPath, true)
349
+ return entries
350
+ }
351
+
352
+ /** Record every path that a recursive removal will delete. */
353
+ export function recordRemovalTree(rootPath, recorder, { scored = false } = {}) {
354
+ const entries = collectRemovalTree(rootPath)
355
+ for (const entry of entries) {
356
+ recordChange({ path: entry.path, action: ACTIONS.REMOVE, bytes: 0, scored }, recorder)
357
+ }
358
+ return entries
359
+ }
360
+
361
+ /**
362
+ * Fail closed unless the exact reviewed subtree and its snapshots still match.
363
+ *
364
+ * @param {string} rootPath
365
+ * @param {Set<string>|null} reviewedRemovals
366
+ * @param {Map<string, object>|null} reviewedSnapshots
367
+ */
368
+ export function validateRemovalTree(rootPath, reviewedRemovals, reviewedSnapshots) {
369
+ if (!reviewedRemovals || !reviewedSnapshots) {
370
+ throw new Error(`Refusing destructive removal without a reviewed snapshot: ${rootPath}`)
371
+ }
372
+ const root = resolve(rootPath)
373
+ const isWithinRoot = (filePath) => {
374
+ const rel = relative(root, resolve(filePath))
375
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
376
+ }
377
+ const expected = new Set(
378
+ [...reviewedRemovals].filter(isWithinRoot).map((filePath) => resolve(filePath)),
379
+ )
380
+ const current = collectRemovalTree(rootPath)
381
+ const actual = new Set(current.map((entry) => resolve(entry.path)))
382
+ if (actual.size !== expected.size || [...actual].some((filePath) => !expected.has(filePath))) {
383
+ throw new Error(`Removal set changed after review: ${rootPath}`)
384
+ }
385
+ for (const entry of current) {
386
+ const filePath = resolve(entry.path)
387
+ const before = reviewedSnapshots.get(filePath)
388
+ const now = entry.snapshot
389
+ if (
390
+ !before ||
391
+ before.exists !== now.exists ||
392
+ before.sha256 !== now.sha256 ||
393
+ before.size !== now.size ||
394
+ before.mode !== now.mode
395
+ ) {
396
+ throw new Error(`Removal target drifted after review: ${entry.path}`)
397
+ }
398
+ }
399
+ return true
400
+ }
401
+
402
+ /**
403
+ * Remove only the reviewed entries, without recursive deletion that could
404
+ * consume a path added after preflight. Directory removal uses rmdir, which
405
+ * fails closed if any unreviewed entry appears during cleanup.
406
+ */
407
+ export function removeReviewedTree(rootPath, reviewedRemovals, reviewedSnapshots) {
408
+ validateRemovalTree(rootPath, reviewedRemovals, reviewedSnapshots)
409
+ const entries = collectRemovalTree(rootPath)
410
+ for (const entry of entries.reverse()) {
411
+ const info = lstatSync(entry.path)
412
+ if (info.isDirectory()) {
413
+ assertSafeRemoval(rootPath, entry.path)
414
+ try {
415
+ rmdirSync(entry.path)
416
+ } catch (error) {
417
+ if (error?.code === 'ENOTEMPTY' || error?.code === 'EEXIST') {
418
+ throw new Error(`Removal set changed after review: ${entry.path}`, { cause: error })
419
+ }
420
+ throw error
421
+ }
422
+ } else {
423
+ // Unlinking a reviewed symlink leaf is safe and preserves historical
424
+ // cleanup behavior; reject linked ancestors so the parent is never
425
+ // redirected outside the reviewed root.
426
+ assertPathWithin(rootPath, entry.path)
427
+ assertNoSymlinkAncestors(entry.path, { includeLeaf: false })
428
+ const before = reviewedSnapshots?.get(resolve(entry.path))
429
+ const now = snapshot(entry.path)
430
+ if (
431
+ !before ||
432
+ before.exists !== now.exists ||
433
+ before.sha256 !== now.sha256 ||
434
+ before.size !== now.size ||
435
+ before.mode !== now.mode
436
+ ) {
437
+ throw new Error(`Removal target drifted after review: ${entry.path}`)
438
+ }
439
+ unlinkSync(entry.path)
440
+ }
441
+ verifyPathRemoved(entry.path)
442
+ }
443
+ return true
444
+ }
445
+
446
+ /**
447
+ * Compare the preview's SCORED change count against this call's install
448
+ * summary delta. Returns a descriptor on mismatch, or `null` when they agree.
449
+ *
450
+ * Only the CHANGED count is gated (`create + update + remove` vs
451
+ * `stats.created`). `stats.skipped` deliberately mixes genuine file-unchanged
452
+ * outcomes with logical no-op skips that never touch a file (e.g. the V2 TUI
453
+ * registration skip), so it cannot be reconciled against `plan.scored.unchanged`
454
+ * without making the guard cry wolf. The meaningful invariant is: every change
455
+ * the summary counted must have been recorded — a preview that silently missed
456
+ * a writer is exactly a `stats.created` with no recorded change.
457
+ *
458
+ * Both sides must be scoped to a SINGLE `installOpenCode` call.
459
+ *
460
+ * @param {{ scored: object }} plan
461
+ * @param {{ created: number, skipped: number }} stats - per-call delta
462
+ * @returns {{ changed: number, unchanged: number, recordedChanged: number, recordedUnchanged: number }|null}
463
+ */
464
+ export function planStatsMismatch(plan, stats) {
465
+ const changed = plan.scored.create + plan.scored.update + plan.scored.remove
466
+ if (changed !== stats.created) {
467
+ return {
468
+ changed,
469
+ unchanged: plan.scored.unchanged,
470
+ recordedChanged: stats.created,
471
+ recordedUnchanged: stats.skipped,
472
+ }
473
+ }
474
+ return null
475
+ }