pantheon-opencode 1.6.2-beta.4 → 1.6.2-beta.5

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 (54) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +174 -3
  3. package/bin/pantheon-init.mjs +6 -1
  4. package/package.json +1 -1
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +3 -3
  8. package/scripts/decision-router-v2-budget.mjs +218 -0
  9. package/scripts/decision-router-v2-egress.mjs +272 -0
  10. package/scripts/decision-router.mjs +268 -46
  11. package/scripts/docs-check-changelog.mjs +5 -3
  12. package/scripts/install/decision-layer-preview.mjs +376 -0
  13. package/scripts/install/decision-router-config.mjs +158 -11
  14. package/scripts/mcp_resources.py +11 -9
  15. package/scripts/release-notes.mjs +30 -7
  16. package/scripts/versioning.mjs +41 -5
  17. package/src/mcp/eval_store.py +11 -4
  18. package/src/mcp/mcp_resources.py +11 -9
  19. package/src/mcp/memory_mcp.py +293 -150
  20. package/src/pantheon/local-decision-prompt.ts +181 -36
  21. package/src/pantheon/local-decision-skills.ts +115 -5
  22. package/src/pantheon/local-decision-tool.ts +35 -1
  23. package/src/pantheon/v2-decision-budget.ts +456 -0
  24. package/src/pantheon/v2-decision-contracts.ts +300 -0
  25. package/src/pantheon/v2-decision-egress.ts +203 -0
  26. package/src/pantheon/v2-decision-events.ts +180 -0
  27. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  28. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  29. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  30. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  31. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  32. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  33. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  34. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  35. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  36. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  37. package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
  38. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  39. package/src/pantheon/v2-decision-points.ts +242 -0
  40. package/src/pantheon/v2-decision-policy.ts +166 -0
  41. package/src/pantheon/v2-decision-premises.ts +146 -0
  42. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  43. package/src/pantheon/v2-decision-rank.ts +91 -0
  44. package/src/pantheon/v2-decision-registry.ts +391 -0
  45. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  46. package/src/pantheon/v2-decision-shadow.ts +123 -0
  47. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  48. package/src/pantheon/v2-decision-verify.ts +51 -0
  49. package/src/pantheon/v2-tools.ts +21 -2
  50. package/src/plugin-v2.ts +305 -3
  51. package/src/plugins/tui/dist/tui-v2.js +3 -3
  52. package/src/plugins/tui/dist/tui.js +1 -1
  53. package/src/plugins/tui/package-lock.json +2 -2
  54. package/src/plugins/tui/package.json +1 -1
@@ -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
+ }
@@ -7,8 +7,10 @@ import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
7
7
  export const DECISION_ROUTER_CONFIG_SCHEMA_VERSION = 1
8
8
 
9
9
  /**
10
- * Legacy installer-state providers. This file is target metadata only: the
11
- * runtime reads the user-level configuration below, never install-state.
10
+ * Legacy installer-state providers, in prompt order. This file is target
11
+ * metadata only: the runtime reads the user-level configuration below, never
12
+ * install-state. The order is positional (the interactive prompt indexes it), so
13
+ * ids are appended only through {@link ACCEPTED_INSTALL_STATE_PROVIDERS}.
12
14
  */
13
15
  export const DECISION_ROUTER_PROVIDERS = Object.freeze(['local', 'openai-decisions', 'jev', 'auto'])
14
16
 
@@ -70,7 +72,14 @@ const LEGACY_USER_CONFIG_KEYS = [
70
72
  'selection',
71
73
  ]
72
74
 
73
- const providerSet = new Set(DECISION_ROUTER_PROVIDERS)
75
+ /**
76
+ * Accepted install-state provider ids. `typesafe-jev` is the canonical form of
77
+ * the legacy `jev` alias and is written by `projectDecisionRouterInstallState`;
78
+ * accepting it is what lets a projected record survive a read/write round trip
79
+ * instead of resetting to Local (D7). The prompt list above is unchanged, so no
80
+ * new install-time option appears.
81
+ */
82
+ const ACCEPTED_INSTALL_STATE_PROVIDERS = new Set([...DECISION_ROUTER_PROVIDERS, 'typesafe-jev'])
74
83
  const externalProviderSet = new Set(['openai-decisions', 'jev', 'typesafe-jev'])
75
84
 
76
85
  /** Canonicalize the legacy `jev` spelling once, at every user-config boundary. */
@@ -92,7 +101,7 @@ export function migrateDecisionRouterConfig(value) {
92
101
  typeof value !== 'object' ||
93
102
  Array.isArray(value) ||
94
103
  value.schema_version !== DECISION_ROUTER_CONFIG_SCHEMA_VERSION ||
95
- !providerSet.has(value.provider) ||
104
+ !ACCEPTED_INSTALL_STATE_PROVIDERS.has(value.provider) ||
96
105
  typeof value.egress_consent !== 'boolean'
97
106
  ) {
98
107
  return { ...DEFAULT_DECISION_ROUTER_CONFIG }
@@ -231,6 +240,18 @@ export function updateUserDecisionRouterConfig(config, update) {
231
240
  throw new TypeError('Invalid enabled provider/model candidates')
232
241
  }
233
242
  const next = { ...current, ...update }
243
+ // Selecting a different provider/model target is not consent for it (D9):
244
+ // `select` records a preference and can only ever leave egress OFF. A
245
+ // previously recorded consent is revoked when the target moves, unless the
246
+ // caller passes `egress_consent` in the same explicit update (an admin
247
+ // surface that names both fields at once).
248
+ if (
249
+ Object.hasOwn(update, 'selection') &&
250
+ !Object.hasOwn(update, 'egress_consent') &&
251
+ !sameSelection(normalizeSelection(update.selection), current.selection)
252
+ ) {
253
+ next.egress_consent = false
254
+ }
234
255
  const normalized = migrateUserDecisionRouterConfig(next)
235
256
  if (normalized.selection.mode === 'local' && update.egress_consent === true) {
236
257
  throw new TypeError('Local selection cannot enable egress consent')
@@ -243,23 +264,71 @@ export function isUserDecisionRouterEnabled(config) {
243
264
  return migrateUserDecisionRouterConfig(config).enabled
244
265
  }
245
266
 
246
- /** Auto resolves only one enabled, cap-valid direct provider/model tuple. */
247
- export function resolveUserDecisionRouterCandidate(config, capValidCandidates = []) {
248
- const preference = migrateUserDecisionRouterConfig(config)
249
- if (!preference.enabled || !preference.egress_consent) return null
267
+ function eligibleAutoCandidates(preference, capValidCandidates) {
250
268
  const validKeys = new Set(
251
269
  capValidCandidates
252
270
  .filter(isKnownCandidate)
253
271
  .map(({ provider, model }) => candidateKey(normalizeDecisionProviderId(provider), model)),
254
272
  )
255
- const enabled = preference.enabled_candidates.filter(
273
+ return preference.enabled_candidates.filter(
256
274
  (candidate) =>
257
275
  remotelyEligibleProviders.has(candidate.provider) &&
258
276
  validKeys.has(candidateKey(candidate.provider, candidate.model)),
259
277
  )
278
+ }
279
+
280
+ /**
281
+ * Explain an Auto selection with an explicit cardinality branch (D5).
282
+ *
283
+ * The defect this closes: 0 and 2+ eligible candidates both collapsed into a
284
+ * single `null`, so a caller could not tell "nothing is enabled" from "several
285
+ * are enabled and I refuse to guess". The three outcomes below are distinct
286
+ * values with distinct reason codes, and every refusal names the state that
287
+ * caused it.
288
+ *
289
+ * @param {unknown} config
290
+ * @param {ReadonlyArray<{ provider: string, model: string }>} [capValidCandidates]
291
+ * @returns {{ outcome: 'ineligible', reason: 'DISABLED'|'CONSENT_MISSING'|'NOT_AUTO' }
292
+ * | { outcome: 'none', reason: 'NO_ELIGIBLE_CANDIDATE', count: 0 }
293
+ * | { outcome: 'single', reason: 'SINGLE_ELIGIBLE_CANDIDATE', count: 1,
294
+ * candidate: { provider: string, model: string } }
295
+ * | { outcome: 'ambiguous', reason: 'MULTIPLE_ELIGIBLE_CANDIDATES', count: number }}
296
+ */
297
+ export function explainUserDecisionRouterAutoSelection(config, capValidCandidates = []) {
298
+ const preference = migrateUserDecisionRouterConfig(config)
299
+ // Preconditions are reported as ineligible, never as a cardinality outcome:
300
+ // a disabled router with two candidates is disabled, not ambiguous.
301
+ if (!preference.enabled) return { outcome: 'ineligible', reason: 'DISABLED' }
302
+ if (!preference.egress_consent) return { outcome: 'ineligible', reason: 'CONSENT_MISSING' }
303
+ if (preference.selection.mode !== 'auto') return { outcome: 'ineligible', reason: 'NOT_AUTO' }
304
+
305
+ const eligible = eligibleAutoCandidates(preference, capValidCandidates)
306
+ if (eligible.length === 0) {
307
+ return { outcome: 'none', reason: 'NO_ELIGIBLE_CANDIDATE', count: 0 }
308
+ }
309
+ if (eligible.length > 1) {
310
+ return {
311
+ outcome: 'ambiguous',
312
+ reason: 'MULTIPLE_ELIGIBLE_CANDIDATES',
313
+ count: eligible.length,
314
+ }
315
+ }
316
+ return {
317
+ outcome: 'single',
318
+ reason: 'SINGLE_ELIGIBLE_CANDIDATE',
319
+ count: 1,
320
+ candidate: eligible[0],
321
+ }
322
+ }
323
+
324
+ /** Auto resolves only one enabled, cap-valid direct provider/model tuple. */
325
+ export function resolveUserDecisionRouterCandidate(config, capValidCandidates = []) {
326
+ const preference = migrateUserDecisionRouterConfig(config)
327
+ if (!preference.enabled || !preference.egress_consent) return null
260
328
  if (preference.selection.mode === 'local') return null
261
329
  if (preference.selection.mode === 'explicit') {
262
330
  const selected = preference.selection
331
+ const enabled = eligibleAutoCandidates(preference, capValidCandidates)
263
332
  return (
264
333
  enabled.find(
265
334
  (candidate) =>
@@ -268,7 +337,8 @@ export function resolveUserDecisionRouterCandidate(config, capValidCandidates =
268
337
  ) ?? null
269
338
  )
270
339
  }
271
- return enabled.length === 1 ? enabled[0] : null
340
+ const explained = explainUserDecisionRouterAutoSelection(preference, capValidCandidates)
341
+ return explained.outcome === 'single' ? explained.candidate : null
272
342
  }
273
343
 
274
344
  /** Read only a private user-level JSON file. Invalid contents fail closed. */
@@ -306,11 +376,88 @@ export function writeUserDecisionRouterConfig(config, { env = process.env } = {}
306
376
  } catch (error) {
307
377
  if (error?.code !== 'ENOENT') throw error
308
378
  }
309
- writeFileAtomically(filePath, `${JSON.stringify(normalized, null, 2)}\n`)
379
+ writeFileAtomically(filePath, serializeUserDecisionRouterConfig(normalized))
310
380
  chmodSync(filePath, 0o600)
311
381
  return filePath
312
382
  }
313
383
 
384
+ /**
385
+ * The only serializer for the user-level config.
386
+ *
387
+ * A preview is honest only when the bytes it compares are the bytes the writer
388
+ * would produce, so the preview and the writer share this function. It is
389
+ * deliberately free of clock and environment reads.
390
+ *
391
+ * @param {unknown} config
392
+ * @returns {string}
393
+ */
394
+ export function serializeUserDecisionRouterConfig(config) {
395
+ return `${JSON.stringify(migrateUserDecisionRouterConfig(config), null, 2)}\n`
396
+ }
397
+
398
+ /**
399
+ * Project the user-level configuration onto the only install-state record that
400
+ * may exist (D7).
401
+ *
402
+ * Install-state records a target preference; the runtime reads the user-level
403
+ * file. Deriving the record from that file is what keeps the two surfaces from
404
+ * disagreeing: there is no second place where a provider or a consent decision
405
+ * can be typed in. The projection carries the user's own consent boolean, so it
406
+ * can never assert consent the runtime configuration does not have.
407
+ *
408
+ * @param {unknown} userConfig
409
+ * @returns {{ schema_version: 1, provider: string, egress_consent: boolean }}
410
+ */
411
+ export function projectDecisionRouterInstallState(userConfig) {
412
+ const preference = migrateUserDecisionRouterConfig(userConfig)
413
+ const provider =
414
+ preference.selection.mode === 'explicit'
415
+ ? normalizeDecisionProviderId(preference.selection.provider)
416
+ : preference.selection.mode
417
+ return migrateDecisionRouterConfig({
418
+ schema_version: DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
419
+ provider,
420
+ egress_consent: preference.egress_consent,
421
+ })
422
+ }
423
+
424
+ /**
425
+ * Field-level divergence between install-state and the user-level config (D7).
426
+ * Returns field NAMES and both states, never free-form content; callers print a
427
+ * reconciliation instruction instead of rewriting the record silently.
428
+ *
429
+ * @param {unknown} userConfig
430
+ * @param {unknown} installStateRecord
431
+ * @returns {{ expected: object, actual: object, differences: Array<{ field: string, installState: unknown, userConfig: unknown }> }}
432
+ */
433
+ export function diffDecisionRouterSurfaces(userConfig, installStateRecord) {
434
+ const expected = projectDecisionRouterInstallState(userConfig)
435
+ const actual = migrateDecisionRouterConfig(installStateRecord)
436
+ const differences = []
437
+ if (actual.provider !== expected.provider) {
438
+ differences.push({
439
+ field: 'provider',
440
+ installState: actual.provider,
441
+ userConfig: expected.provider,
442
+ })
443
+ }
444
+ if (actual.egress_consent !== expected.egress_consent) {
445
+ differences.push({
446
+ field: 'egress_consent',
447
+ installState: actual.egress_consent,
448
+ userConfig: expected.egress_consent,
449
+ })
450
+ }
451
+ return { expected, actual, differences }
452
+ }
453
+
454
+ function sameSelection(left, right) {
455
+ if (left === null || right === null) return left === right
456
+ if (left.mode !== right.mode) return false
457
+ if (left.mode !== 'explicit') return true
458
+ return left.provider === right.provider && left.model === right.model
459
+ }
460
+
314
461
  function normalizeSelection(value) {
315
462
  if (!isPlainObject(value) || typeof value.mode !== 'string') return null
316
463
  if (value.mode === 'local' || value.mode === 'auto') {
@@ -23,7 +23,6 @@ from fastmcp import FastMCP
23
23
 
24
24
  # ── Path Resolution ──────────────────────────────────────────────────────────
25
25
  _PANTHEON_HOME: Path = pantheon_home()
26
- _PANTHEON_PROJECT: Path | None = pantheon_project()
27
26
 
28
27
 
29
28
  def _within(path: Path, parent: Path) -> bool:
@@ -68,12 +67,13 @@ def _resource_root(name: str) -> Path | None:
68
67
  preserves the global fallback while preventing symlink escapes.
69
68
  """
70
69
  candidates: list[tuple[Path, Path]] = []
71
- if _PANTHEON_PROJECT is not None:
70
+ project = pantheon_project()
71
+ if project is not None:
72
72
  if name in {"agents", "skills"}:
73
- local = _PANTHEON_PROJECT / ".opencode"
73
+ local = project / ".opencode"
74
74
  candidates.append((local / name, local))
75
75
  elif name in {"deepwork", "memory-bank"}:
76
- local = _PANTHEON_PROJECT / ".pantheon"
76
+ local = project / ".pantheon"
77
77
  candidates.append((local / name, local))
78
78
  candidates.append((_PANTHEON_HOME / name, _PANTHEON_HOME))
79
79
  for root, parent in candidates:
@@ -86,9 +86,10 @@ def _resource_root(name: str) -> Path | None:
86
86
  def _resource_roots(name: str) -> list[Path]:
87
87
  """Return safe resource roots in local-first precedence order."""
88
88
  roots: list[Path] = []
89
- if _PANTHEON_PROJECT is not None:
89
+ project = pantheon_project()
90
+ if project is not None:
90
91
  base_name = ".opencode" if name in {"agents", "skills"} else ".pantheon"
91
- base = _PANTHEON_PROJECT / base_name
92
+ base = project / base_name
92
93
  local = _safe_root(base / name, base)
93
94
  if local is not None:
94
95
  roots.append(local)
@@ -208,9 +209,10 @@ async def list_skills() -> str:
208
209
  async def get_routing() -> str:
209
210
  """Return the full content of routing.yml."""
210
211
  routing_file = _safe_child(_PANTHEON_HOME, "routing.yml")
211
- if routing_file is None and _PANTHEON_PROJECT:
212
- routing_file = _safe_child(_PANTHEON_PROJECT / "src", "routing.yml")
213
- if routing_file is None or not routing_file.exists():
212
+ project = pantheon_project()
213
+ if (routing_file is None or not routing_file.is_file()) and project:
214
+ routing_file = _safe_child(project / "src", "routing.yml")
215
+ if routing_file is None or not routing_file.is_file():
214
216
  return "routing.yml not found."
215
217
  return routing_file.read_text(encoding="utf-8")
216
218