pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.11

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 (145) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-gates.mjs +6 -82
  42. package/scripts/release-notes.mjs +30 -7
  43. package/scripts/restore.mjs +22 -10
  44. package/scripts/sync-tui.mjs +3 -3
  45. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  46. package/scripts/versioning.mjs +41 -5
  47. package/src/agents/aphrodite.md +6 -1
  48. package/src/agents/apollo.md +1 -0
  49. package/src/agents/athena.md +1 -0
  50. package/src/agents/demeter.md +1 -1
  51. package/src/agents/gaia.md +1 -0
  52. package/src/agents/hephaestus.md +1 -1
  53. package/src/agents/hermes.md +8 -10
  54. package/src/agents/iris.md +1 -1
  55. package/src/agents/mnemosyne.md +1 -0
  56. package/src/agents/nyx.md +1 -1
  57. package/src/agents/prometheus.md +1 -1
  58. package/src/agents/talos.md +6 -1
  59. package/src/agents/themis.md +1 -1
  60. package/src/agents/zeus.md +52 -62
  61. package/src/mcp/eval_store.py +11 -4
  62. package/src/mcp/mcp_resources.py +11 -9
  63. package/src/mcp/memory_mcp.py +293 -150
  64. package/src/pantheon/cost-command.ts +30 -133
  65. package/src/pantheon/jev-decision-tool.ts +359 -0
  66. package/src/pantheon/jev-decisions.ts +625 -0
  67. package/src/pantheon/local-decision-agents.ts +170 -0
  68. package/src/pantheon/local-decision-budget.ts +1046 -0
  69. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  70. package/src/pantheon/local-decision-prompt.ts +256 -0
  71. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  72. package/src/pantheon/local-decision-router.ts +225 -0
  73. package/src/pantheon/local-decision-skills.ts +281 -0
  74. package/src/pantheon/local-decision-tool.ts +160 -0
  75. package/src/pantheon/local-decision-turn.ts +101 -0
  76. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  77. package/src/pantheon/local-orchestration.ts +322 -0
  78. package/src/pantheon/model-pricing.ts +1 -536
  79. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  80. package/src/pantheon/v2-decision-budget.ts +456 -0
  81. package/src/pantheon/v2-decision-contracts.ts +300 -0
  82. package/src/pantheon/v2-decision-egress.ts +203 -0
  83. package/src/pantheon/v2-decision-events.ts +180 -0
  84. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  85. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  86. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  87. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  88. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  89. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  90. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  91. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  92. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  93. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  94. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  95. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  96. package/src/pantheon/v2-decision-points.ts +242 -0
  97. package/src/pantheon/v2-decision-policy.ts +166 -0
  98. package/src/pantheon/v2-decision-premises.ts +146 -0
  99. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  100. package/src/pantheon/v2-decision-rank.ts +91 -0
  101. package/src/pantheon/v2-decision-registry.ts +391 -0
  102. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  103. package/src/pantheon/v2-decision-shadow.ts +123 -0
  104. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  105. package/src/pantheon/v2-decision-verify.ts +51 -0
  106. package/src/pantheon/v2-hook-engine.ts +307 -0
  107. package/src/pantheon/v2-native-decisions.ts +365 -0
  108. package/src/pantheon/v2-shell-hooks.ts +66 -2
  109. package/src/pantheon/v2-tools.ts +38 -15
  110. package/src/plugin-v2.ts +419 -26
  111. package/src/plugin.ts +4 -0
  112. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  113. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  114. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  115. package/src/plugins/tui/dist/server-v2.js +19 -666
  116. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  117. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  119. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  121. package/src/plugins/tui/dist/tui.js +1 -1
  122. package/src/plugins/tui/package-lock.json +17 -2
  123. package/src/plugins/tui/package.json +4 -2
  124. package/src/plugins/tui/src/cost-data.ts +607 -0
  125. package/src/plugins/tui/src/index-v2.tsx +213 -54
  126. package/src/plugins/tui/src/model-pricing.ts +536 -0
  127. package/src/plugins/tui/src/server-v2.ts +18 -838
  128. package/src/plugins/tui/tsdown.config.ts +28 -6
  129. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  130. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  131. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  132. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  133. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  134. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  135. package/src/plugins/tui/dist/quota-cli.js +0 -184
  136. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  138. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  139. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  140. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  141. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  142. package/src/plugins/tui/src/quota-cli.ts +0 -237
  143. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  144. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  145. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -10,7 +10,7 @@
10
10
  * - a bullet over 200 characters (including continuation lines) in those
11
11
  * sections;
12
12
  * - an empty subsection under [Unreleased];
13
- * - any `## 🆕|🐞|⚠️|✅` H2 anywhere;
13
+ * - any emoji H2 except the generated `🆕 What's New` and `🐞 Fixed` headings;
14
14
  * - a missing Deprecated or Removed block in the newest stable version.
15
15
  *
16
16
  * Historical sections are archived records: only their version-heading shape
@@ -26,7 +26,9 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
26
26
  const CHANGELOG = process.argv[2] ? process.argv[2] : join(ROOT, 'CHANGELOG.md')
27
27
  const MAX_BULLET = 200
28
28
  const ALLOWED_H3 = new Set(['Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security'])
29
- const EMOJI_H2 = /^##\s+(?:🆕|🐞|⚠️|✅)/
29
+ const EMOJI_H2 =
30
+ /^##\s+(?:\p{Extended_Pictographic}|\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3)/u
31
+ const ALLOWED_GENERATED_H2 = /^##\s+(?:🆕 What's New|🐞 Fixed)\s*$/
30
32
  const STABLE_VERSION_HEADING = /^## \[v?(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}$/
31
33
  // Historical headings may carry a pre-release suffix, a month-only date, or a
32
34
  // "(candidate)" marker.
@@ -104,7 +106,7 @@ function main() {
104
106
  if (line.startsWith('## ')) {
105
107
  closeSection()
106
108
 
107
- if (EMOJI_H2.test(line)) {
109
+ if (EMOJI_H2.test(line) && !ALLOWED_GENERATED_H2.test(line)) {
108
110
  findings.push(`${lineNo}: emoji H2 is not allowed (${line.trim()})`)
109
111
  continue
110
112
  }
@@ -1,5 +1,13 @@
1
1
  const DEFAULT_INSTALL_COMPONENTS = ['agents', 'skills', 'instructions', 'commands', 'plugins']
2
- const KNOWN_COMPONENTS = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime']
2
+ const KNOWN_COMPONENTS = [
3
+ 'agents',
4
+ 'skills',
5
+ 'instructions',
6
+ 'prompts',
7
+ 'commands',
8
+ 'plugins',
9
+ 'runtime',
10
+ ]
3
11
 
4
12
  /**
5
13
  * Resolve CLI component flags without widening an explicit component selection.
@@ -50,9 +58,6 @@ export function resolveComponentSelection(args, { reviewedComponents = null } =
50
58
  }
51
59
  }
52
60
 
53
- // Runtime is a default only for an unscoped install. Explicit --components
54
- // remains the user's exact scope; runtime can still be requested by name.
55
- if (explicitComponents === null && !components.includes('runtime')) components.push('runtime')
56
61
  return {
57
62
  components,
58
63
  requestedComponentsForPrompt: explicitComponents ? [...explicitComponents] : null,
@@ -0,0 +1,376 @@
1
+ /**
2
+ * decision-layer-preview.mjs — a COMPUTED diff of the decision-layer target
3
+ * artifacts (PLAN §7 Fase 7 gate, PM-13, D7).
4
+ *
5
+ * Why this module exists at all: the installer's "Change plan" is **not** a
6
+ * preview. PROBE-B measured a second idempotent apply that announced
7
+ * `112 create` and created nothing, because the announcement is derived from
8
+ * what a writer was asked to do, not from what the target bytes are. Shipping a
9
+ * second announcement of the same kind would repeat the defect with a new
10
+ * label. So this module never reads a change plan and never reprints one:
11
+ *
12
+ * - it takes a content snapshot of each target artifact exactly as PROBE-B §4.2
13
+ * did (`lstat` + SHA-256 + size + mode);
14
+ * - it builds the candidate bytes with the SAME serializer the writer uses
15
+ * (`serializeUserDecisionRouterConfig`), so the compared bytes are the bytes
16
+ * that would land on disk;
17
+ * - the action is decided by comparing hashes, nothing else:
18
+ * `missing → create`, `same hash → unchanged`, `different hash → update`.
19
+ *
20
+ * Consequence, and the property a test pins: apply-then-preview reports
21
+ * `0 create · 0 update`, while the measured installer re-announced 112 creates
22
+ * on an apply that created nothing.
23
+ *
24
+ * Writes only happen in {@link applyDecisionLayerPlan}, after re-reading the
25
+ * current hash and refusing the whole plan if any artifact moved in between.
26
+ *
27
+ * Secret safety: the plan and its rendered form contain paths, actions, byte
28
+ * sizes, field NAMES, and the values of a fixed allowlist of activation flags
29
+ * (schema version, enabled, consent, selection mode/provider/model, candidate
30
+ * count). No free-form content, no file contents, no hashes are printed.
31
+ */
32
+ import { createHash } from 'node:crypto'
33
+ import { existsSync, lstatSync, readFileSync } from 'node:fs'
34
+ import { join, resolve } from 'node:path'
35
+ import {
36
+ migrateUserDecisionRouterConfig,
37
+ projectDecisionRouterInstallState,
38
+ readUserDecisionRouterConfig,
39
+ resolveUserDecisionRouterConfigPath,
40
+ serializeUserDecisionRouterConfig,
41
+ updateUserDecisionRouterConfig,
42
+ writeUserDecisionRouterConfig,
43
+ } from './decision-router-config.mjs'
44
+ import { snapshot } from './plan.mjs'
45
+ import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
46
+
47
+ export const DECISION_LAYER_ACTIONS = Object.freeze({
48
+ CREATE: 'create',
49
+ UPDATE: 'update',
50
+ UNCHANGED: 'unchanged',
51
+ })
52
+
53
+ export const DECISION_LAYER_ROLES = Object.freeze({
54
+ USER_CONFIG: 'user-config',
55
+ INSTALL_STATE: 'install-state',
56
+ })
57
+
58
+ /**
59
+ * Backups are credential-bearing. The installer's own log says a backup set
60
+ * contains API keys/tokens, and PROBE-B measured one backup directory
61
+ * accumulated per application. The decision-layer setup path creates none and
62
+ * says so; it never adds a silent backup copy.
63
+ */
64
+ export const DECISION_LAYER_BACKUP_NOTICE =
65
+ 'Backup notice: installer backup sets accumulate once per application and contain ' +
66
+ 'credential-bearing files (API keys/tokens) by the installer log itself. This command ' +
67
+ 'creates no backup and no copy; nothing extra is written or retained.'
68
+
69
+ /** Fields whose VALUES may be printed. They are activation flags, never secrets. */
70
+ const VISIBLE_FIELDS = Object.freeze([
71
+ 'schema_version',
72
+ 'enabled',
73
+ 'egress_consent',
74
+ 'selection.mode',
75
+ 'selection.provider',
76
+ 'selection.model',
77
+ ])
78
+
79
+ function readRawJson(filePath) {
80
+ try {
81
+ assertNoSymlinkAncestors(filePath)
82
+ const stat = lstatSync(filePath)
83
+ if (!stat.isFile() || stat.isSymbolicLink()) return null
84
+ return JSON.parse(readFileSync(filePath, 'utf8'))
85
+ } catch {
86
+ return null
87
+ }
88
+ }
89
+
90
+ function visibleValue(value) {
91
+ if (value === null || value === undefined) return null
92
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
93
+ return value
94
+ }
95
+ return Array.isArray(value) ? value.length : typeof value
96
+ }
97
+
98
+ function fieldValue(record, field) {
99
+ if (record === null || typeof record !== 'object') return undefined
100
+ let current = record
101
+ for (const part of field.split('.')) {
102
+ if (current === null || typeof current !== 'object') return undefined
103
+ current = current[part]
104
+ }
105
+ return current
106
+ }
107
+
108
+ /** Field-level diff for the allowlisted activation flags only. */
109
+ function diffConfigFields(rawConfig, candidateConfig) {
110
+ const changes = []
111
+ for (const field of VISIBLE_FIELDS) {
112
+ const before = fieldValue(rawConfig, field)
113
+ const after = fieldValue(candidateConfig, field)
114
+ if (JSON.stringify(before) !== JSON.stringify(after)) {
115
+ changes.push({ field, before: visibleValue(before), after: visibleValue(after) })
116
+ }
117
+ }
118
+ if (rawConfig === null) return changes
119
+ const rawKeys = Object.keys(rawConfig).sort()
120
+ const candidateKeys = Object.keys(candidateConfig).sort()
121
+ for (const key of rawKeys) {
122
+ if (!candidateKeys.includes(key))
123
+ changes.push({ field: key, before: 'present', after: 'removed' })
124
+ }
125
+ for (const key of candidateKeys) {
126
+ if (!rawKeys.includes(key)) changes.push({ field: key, before: 'absent', after: 'present' })
127
+ }
128
+ if (
129
+ Array.isArray(rawConfig?.enabled_candidates) &&
130
+ rawConfig.enabled_candidates.length !== candidateConfig.enabled_candidates.length
131
+ ) {
132
+ changes.push({
133
+ field: 'enabled_candidates.length',
134
+ before: rawConfig.enabled_candidates.length,
135
+ after: candidateConfig.enabled_candidates.length,
136
+ })
137
+ }
138
+ return changes
139
+ }
140
+
141
+ function artifactDiff({ role, path, current, candidateBytes, changedFields }) {
142
+ const candidateSnapshot = {
143
+ sha256: snapshotBytesHash(candidateBytes),
144
+ size: Buffer.byteLength(candidateBytes),
145
+ }
146
+ let action
147
+ if (!current.exists) action = DECISION_LAYER_ACTIONS.CREATE
148
+ else if (current.sha256 === candidateSnapshot.sha256) action = DECISION_LAYER_ACTIONS.UNCHANGED
149
+ else action = DECISION_LAYER_ACTIONS.UPDATE
150
+ return {
151
+ role,
152
+ path,
153
+ action,
154
+ bytes: candidateSnapshot.size,
155
+ currentBytes: current.size,
156
+ // Internal comparison state: never rendered, never printed.
157
+ currentExists: current.exists,
158
+ currentHash: current.sha256,
159
+ candidateBytes,
160
+ expectedHash: candidateSnapshot.sha256,
161
+ changedFields: action === DECISION_LAYER_ACTIONS.UNCHANGED ? [] : changedFields,
162
+ }
163
+ }
164
+
165
+ function snapshotBytesHash(bytes) {
166
+ return createHash('sha256').update(bytes).digest('hex')
167
+ }
168
+
169
+ /** Resolve the install-state document for an explicit target, if it exists. */
170
+ export function resolveInstallStatePath(target) {
171
+ return join(resolve(target), '.pantheon', 'install-state.json')
172
+ }
173
+
174
+ /**
175
+ * Build the plan. No writes, no directory creation, no timestamp reads.
176
+ *
177
+ * @param {{ env?: Record<string, string|undefined>, target?: string,
178
+ * selection?: { mode: 'local' } | { mode: 'auto' } |
179
+ * { mode: 'explicit', provider: string, model: string },
180
+ * acceptMigration?: boolean }} [options]
181
+ */
182
+ export function buildDecisionLayerPlan(options = {}) {
183
+ const { env = process.env, target, selection, acceptMigration = false } = options
184
+ const configPath = resolveUserDecisionRouterConfigPath(env)
185
+ const currentConfig = readUserDecisionRouterConfig({ env })
186
+ const candidateConfig =
187
+ selection === undefined
188
+ ? currentConfig
189
+ : updateUserDecisionRouterConfig(currentConfig, { selection })
190
+ const candidateBytes = serializeUserDecisionRouterConfig(candidateConfig)
191
+ const rawConfig = readRawJson(configPath)
192
+
193
+ const artifacts = [
194
+ artifactDiff({
195
+ role: DECISION_LAYER_ROLES.USER_CONFIG,
196
+ path: configPath,
197
+ current: snapshot(configPath),
198
+ candidateBytes,
199
+ changedFields: diffConfigFields(rawConfig, candidateConfig),
200
+ }),
201
+ ]
202
+
203
+ const warnings = [DECISION_LAYER_BACKUP_NOTICE]
204
+ const blocked = []
205
+
206
+ // A legacy file being normalized to the canonical schema must never turn the
207
+ // turn router on as a side effect of a preview/apply. The file can be
208
+ // rewritten, but enabling requires its own explicit flag and its own review.
209
+ const migrationEnablesTurnRouter =
210
+ rawConfig !== null &&
211
+ rawConfig.schema_version !== migrateUserDecisionRouterConfig(candidateConfig).schema_version &&
212
+ rawConfig.enabled !== true &&
213
+ migrateUserDecisionRouterConfig(candidateConfig).enabled === true
214
+ if (migrationEnablesTurnRouter && !acceptMigration) {
215
+ blocked.push({
216
+ role: DECISION_LAYER_ROLES.USER_CONFIG,
217
+ path: configPath,
218
+ reason: 'MIGRATION_WOULD_ENABLE_TURN_ROUTER',
219
+ detail:
220
+ 'Writing the canonical schema would set enabled: true from a legacy file. ' +
221
+ 'Re-run with --accept-migration to accept that activation explicitly.',
222
+ })
223
+ }
224
+
225
+ if (target !== undefined) {
226
+ const statePath = resolveInstallStatePath(target)
227
+ if (existsSync(statePath)) {
228
+ const rawState = readRawJson(statePath)
229
+ if (rawState && rawState.decision_router !== undefined) {
230
+ const projection = projectDecisionRouterInstallState(candidateConfig)
231
+ const candidateState = { ...rawState, decision_router: projection }
232
+ const stateBytes = `${JSON.stringify(candidateState, null, 2)}\n`
233
+ const current = diffInstallStateRecord(rawState.decision_router, projection)
234
+ artifacts.push(
235
+ artifactDiff({
236
+ role: DECISION_LAYER_ROLES.INSTALL_STATE,
237
+ path: statePath,
238
+ current: snapshot(statePath),
239
+ candidateBytes: stateBytes,
240
+ changedFields: current,
241
+ }),
242
+ )
243
+ }
244
+ } else {
245
+ warnings.push(
246
+ `No install-state at ${statePath}: nothing to reconcile. The decision-layer setup ` +
247
+ 'never fabricates install state for an unmanaged target.',
248
+ )
249
+ }
250
+ }
251
+
252
+ const totals = {
253
+ create: artifacts.filter((a) => a.action === DECISION_LAYER_ACTIONS.CREATE).length,
254
+ update: artifacts.filter((a) => a.action === DECISION_LAYER_ACTIONS.UPDATE).length,
255
+ unchanged: artifacts.filter((a) => a.action === DECISION_LAYER_ACTIONS.UNCHANGED).length,
256
+ }
257
+ return { artifacts, totals, warnings, blocked, wrote: false }
258
+ }
259
+
260
+ function diffInstallStateRecord(installStateRecord, projection) {
261
+ const changes = []
262
+ for (const field of ['provider', 'egress_consent']) {
263
+ const before = installStateRecord?.[field]
264
+ const after = projection[field]
265
+ if (JSON.stringify(before) !== JSON.stringify(after)) {
266
+ changes.push({
267
+ field: `decision_router.${field}`,
268
+ before: visibleValue(before),
269
+ after: visibleValue(after),
270
+ })
271
+ }
272
+ }
273
+ return changes
274
+ }
275
+
276
+ /** Secret-safe rendering. Paths, actions, sizes, field names and flag values only. */
277
+ export function formatDecisionLayerPlan(plan, { scope = 'user', applyPending = false } = {}) {
278
+ const lines = [`Decision-layer preview — ${scope} (computed artifact diff, not a change plan)`]
279
+ for (const artifact of plan.artifacts) {
280
+ lines.push(` ${artifact.action.padEnd(9)} ${artifact.path} (${artifact.bytes} B)`)
281
+ for (const change of artifact.changedFields) {
282
+ const before = change.before === null ? 'absent' : String(change.before)
283
+ const after = change.after === null ? 'absent' : String(change.after)
284
+ lines.push(` ${change.field}: ${before} -> ${after}`)
285
+ }
286
+ }
287
+ lines.push(
288
+ ` ${plan.totals.create} create · ${plan.totals.update} update · ${plan.totals.unchanged} unchanged`,
289
+ )
290
+ for (const warning of plan.warnings) lines.push(` ${warning}`)
291
+ for (const entry of plan.blocked) {
292
+ lines.push(` BLOCKED ${entry.path}: ${entry.reason} — ${entry.detail}`)
293
+ }
294
+ lines.push(
295
+ applyPending
296
+ ? ' Writing the artifacts above (explicit --apply). No backup copy is created.'
297
+ : ' No files were written.',
298
+ )
299
+ return lines.join('\n')
300
+ }
301
+
302
+ /** Machine-readable form. Same facts as the text renderer, no contents. */
303
+ export function toDecisionLayerPlanJson(plan) {
304
+ return {
305
+ kind: 'decision-layer-preview',
306
+ preview: true,
307
+ wrote: false,
308
+ totals: plan.totals,
309
+ artifacts: plan.artifacts.map((artifact) => ({
310
+ role: artifact.role,
311
+ path: artifact.path,
312
+ action: artifact.action,
313
+ bytes: artifact.bytes,
314
+ changed_fields: artifact.changedFields.map((change) => ({
315
+ field: change.field,
316
+ before: change.before,
317
+ after: change.after,
318
+ })),
319
+ })),
320
+ blocked: plan.blocked.map((entry) => ({
321
+ role: entry.role,
322
+ path: entry.path,
323
+ reason: entry.reason,
324
+ })),
325
+ warnings: plan.warnings,
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Write exactly the artifacts the plan described.
331
+ *
332
+ * Every artifact is re-snapshotted first: if any hash or existence differs from
333
+ * the reviewed plan, the whole apply is refused before the first write, so a
334
+ * preview that raced an edit can never be applied. Unchanged artifacts are not
335
+ * written at all (no mtime churn, no backup copy).
336
+ *
337
+ * @returns {{ written: string[], skipped: string[] }}
338
+ */
339
+ export function applyDecisionLayerPlan(plan, { env = process.env } = {}) {
340
+ if (plan.blocked.length > 0) {
341
+ throw new Error(
342
+ `Refusing to apply a blocked plan: ${plan.blocked.map((entry) => entry.reason).join(', ')}`,
343
+ )
344
+ }
345
+ for (const artifact of plan.artifacts) {
346
+ const live = snapshot(artifact.path)
347
+ if (live.exists !== artifact.currentExists) {
348
+ throw new Error(`Artifact changed since the preview: ${artifact.path}. Re-run the preview.`)
349
+ }
350
+ if (live.sha256 !== artifact.currentHash) {
351
+ throw new Error(`Artifact changed since the preview: ${artifact.path}. Re-run the preview.`)
352
+ }
353
+ }
354
+ const written = []
355
+ const skipped = []
356
+ for (const artifact of plan.artifacts) {
357
+ if (artifact.action === DECISION_LAYER_ACTIONS.UNCHANGED) {
358
+ skipped.push(artifact.path)
359
+ continue
360
+ }
361
+ if (artifact.role === DECISION_LAYER_ROLES.USER_CONFIG) {
362
+ // Reuse the writer: path validation, ownership checks, 0700 directory and
363
+ // 0600 file mode are already centralized there, and it serializes with the
364
+ // same function this module diffed.
365
+ if (resolveUserDecisionRouterConfigPath(env) !== artifact.path) {
366
+ throw new Error('Decision-layer plan targets a different config path than the environment')
367
+ }
368
+ writeUserDecisionRouterConfig(JSON.parse(artifact.candidateBytes), { env })
369
+ } else {
370
+ assertNoSymlinkAncestors(artifact.path)
371
+ writeFileAtomically(artifact.path, artifact.candidateBytes)
372
+ }
373
+ written.push(artifact.path)
374
+ }
375
+ return { written, skipped }
376
+ }