pantheon-opencode 1.6.1 → 1.6.2-beta.10

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 (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
@@ -0,0 +1,560 @@
1
+ import { chmodSync, lstatSync, mkdirSync, readFileSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
4
+ import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
5
+
6
+ /** Versioned, non-secret installer preference for the advisory decision router. */
7
+ export const DECISION_ROUTER_CONFIG_SCHEMA_VERSION = 1
8
+
9
+ /**
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}.
14
+ */
15
+ export const DECISION_ROUTER_PROVIDERS = Object.freeze(['local', 'openai-decisions', 'jev', 'auto'])
16
+
17
+ export const DEFAULT_DECISION_ROUTER_CONFIG = Object.freeze({
18
+ schema_version: DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
19
+ provider: 'local',
20
+ egress_consent: false,
21
+ })
22
+
23
+ /**
24
+ * Canonical user-level provider/model matrix. The provider identifiers are the
25
+ * same ones used by the runtime selector and by the private provider adapter;
26
+ * `decision-provider-budget.ts` maps them onto the ledger's accounting names.
27
+ */
28
+ export const DECISION_ROUTER_MODELS = Object.freeze({
29
+ 'openai-decisions': Object.freeze(['gpt-6-luna']),
30
+ 'typesafe-jev': Object.freeze(['jev-1.14.0']),
31
+ 'opencode-console-jev': Object.freeze(['jev-1.13']),
32
+ 'opencode-console-jev-free': Object.freeze(['jev-1.13-free']),
33
+ })
34
+
35
+ /** Single mapping from a user-level provider ID to the local budget provider. */
36
+ export const DECISION_PROVIDER_BUDGET_MAPPING = Object.freeze({
37
+ 'openai-decisions': 'openai-decisions',
38
+ 'typesafe-jev': 'typesafe-jev',
39
+ 'opencode-console-jev': 'opencode-console',
40
+ 'opencode-console-jev-free': 'jev-free',
41
+ })
42
+
43
+ /** Providers whose usage and price are documented well enough to reconcile. */
44
+ export const REMOTELY_ELIGIBLE_DECISION_PROVIDERS = Object.freeze([
45
+ 'openai-decisions',
46
+ 'typesafe-jev',
47
+ ])
48
+
49
+ export const USER_DECISION_ROUTER_CONFIG_SCHEMA_VERSION = 2
50
+ export const DEFAULT_USER_DECISION_ROUTER_CONFIG = Object.freeze({
51
+ schema_version: USER_DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
52
+ enabled: false,
53
+ selection: Object.freeze({ mode: 'local' }),
54
+ egress_consent: false,
55
+ enabled_candidates: Object.freeze([]),
56
+ })
57
+
58
+ const LEGACY_PROVIDER_ALIASES = Object.freeze({ jev: 'typesafe-jev' })
59
+ const userCandidateProviders = new Set(Object.keys(DECISION_ROUTER_MODELS))
60
+ const remotelyEligibleProviders = new Set(REMOTELY_ELIGIBLE_DECISION_PROVIDERS)
61
+ const USER_CONFIG_KEYS = [
62
+ 'egress_consent',
63
+ 'enabled',
64
+ 'enabled_candidates',
65
+ 'schema_version',
66
+ 'selection',
67
+ ]
68
+ const LEGACY_USER_CONFIG_KEYS = [
69
+ 'egress_consent',
70
+ 'enabled_candidates',
71
+ 'schema_version',
72
+ 'selection',
73
+ ]
74
+
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'])
83
+
84
+ /** Canonicalize the legacy `jev` spelling once, at every user-config boundary. */
85
+ export function normalizeDecisionProviderId(provider) {
86
+ if (typeof provider !== 'string') return provider
87
+ return LEGACY_PROVIDER_ALIASES[provider] ?? provider
88
+ }
89
+
90
+ /**
91
+ * Migrate/validate persisted preference data. Missing or invalid legacy data is
92
+ * fail-closed: Local, no egress consent. Credentials are neither accepted nor
93
+ * inspected here.
94
+ * @param {unknown} value
95
+ * @returns {{ schema_version: 1, provider: string, egress_consent: boolean }}
96
+ */
97
+ export function migrateDecisionRouterConfig(value) {
98
+ if (
99
+ !value ||
100
+ typeof value !== 'object' ||
101
+ Array.isArray(value) ||
102
+ value.schema_version !== DECISION_ROUTER_CONFIG_SCHEMA_VERSION ||
103
+ !ACCEPTED_INSTALL_STATE_PROVIDERS.has(value.provider) ||
104
+ typeof value.egress_consent !== 'boolean'
105
+ ) {
106
+ return { ...DEFAULT_DECISION_ROUTER_CONFIG }
107
+ }
108
+
109
+ return {
110
+ schema_version: DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
111
+ provider: value.provider,
112
+ egress_consent: value.provider === 'local' ? false : value.egress_consent,
113
+ }
114
+ }
115
+
116
+ /** Build the only preference shape the installer persists. */
117
+ export function createDecisionRouterConfig(provider, egressConsent = false) {
118
+ return migrateDecisionRouterConfig({
119
+ schema_version: DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
120
+ provider,
121
+ egress_consent: provider === 'local' ? false : egressConsent === true,
122
+ })
123
+ }
124
+
125
+ /**
126
+ * Resolve a preference without probing the environment or credentials.
127
+ * (The legacy `resolveDecisionRouterProvider` auto resolver was removed with
128
+ * the direct-fetch provider path; runtime selection uses
129
+ * `resolveUserDecisionRouterCandidate` / `explainUserDecisionRouterAutoSelection`
130
+ * and the native route resolver.)
131
+ */
132
+
133
+ /**
134
+ * Resolve Pantheon's private non-secret user configuration path.
135
+ * @param {Readonly<Record<string, string | undefined>>} [env]
136
+ */
137
+ export function resolveUserDecisionRouterConfigPath(env = process.env) {
138
+ const xdg = env.XDG_CONFIG_HOME
139
+ const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir()
140
+ const root = xdg && isAbsolute(xdg) ? xdg : join(home, '.config')
141
+ return resolve(root, 'pantheon', 'decision-router.json')
142
+ }
143
+
144
+ /** Migrate invalid or missing user data to a local-only, no-consent config. */
145
+ export function migrateUserDecisionRouterConfig(value) {
146
+ if (!isPlainObject(value)) return cloneDefaultUserConfig()
147
+ if (value.schema_version === 1) return migrateLegacyUserConfig(value)
148
+ if (value.schema_version !== USER_DECISION_ROUTER_CONFIG_SCHEMA_VERSION) {
149
+ return cloneDefaultUserConfig()
150
+ }
151
+ if (
152
+ !hasExactKeys(value, USER_CONFIG_KEYS) ||
153
+ typeof value.egress_consent !== 'boolean' ||
154
+ typeof value.enabled !== 'boolean' ||
155
+ !Array.isArray(value.enabled_candidates)
156
+ ) {
157
+ return cloneDefaultUserConfig()
158
+ }
159
+ const selection = normalizeSelection(value.selection)
160
+ const candidates = normalizeEnabledCandidates(value.enabled_candidates)
161
+ if (selection === null || candidates === null) return cloneDefaultUserConfig()
162
+ return {
163
+ schema_version: USER_DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
164
+ enabled: value.enabled,
165
+ selection,
166
+ egress_consent: selection.mode === 'local' ? false : value.egress_consent,
167
+ enabled_candidates: candidates,
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Schema v1 predated the explicit `enabled` switch. Preserve intent only when
173
+ * the user had selected a provider, consented, and enabled at least one
174
+ * candidate; every other legacy shape migrates to disabled.
175
+ */
176
+ function migrateLegacyUserConfig(value) {
177
+ if (
178
+ !hasExactKeys(value, LEGACY_USER_CONFIG_KEYS) ||
179
+ typeof value.egress_consent !== 'boolean' ||
180
+ !Array.isArray(value.enabled_candidates)
181
+ ) {
182
+ return cloneDefaultUserConfig()
183
+ }
184
+ const selection = normalizeSelection(value.selection)
185
+ const candidates = normalizeEnabledCandidates(value.enabled_candidates)
186
+ if (selection === null || candidates === null) return cloneDefaultUserConfig()
187
+ const egressConsent = selection.mode === 'local' ? false : value.egress_consent
188
+ return {
189
+ schema_version: USER_DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
190
+ enabled: selection.mode !== 'local' && egressConsent && candidates.length > 0,
191
+ selection,
192
+ egress_consent: egressConsent,
193
+ enabled_candidates: candidates,
194
+ }
195
+ }
196
+
197
+ /** Return a validated immutable update, without implying consent or enablement. */
198
+ export function updateUserDecisionRouterConfig(config, update) {
199
+ const current = migrateUserDecisionRouterConfig(config)
200
+ if (!isPlainObject(update)) throw new TypeError('Invalid decision-router update')
201
+ if (
202
+ Object.keys(update).some(
203
+ (key) => !['enabled', 'selection', 'egress_consent', 'enabled_candidates'].includes(key),
204
+ )
205
+ ) {
206
+ throw new TypeError('Unsupported decision-router configuration field')
207
+ }
208
+ if (Object.hasOwn(update, 'selection') && normalizeSelection(update.selection) === null) {
209
+ throw new TypeError('Invalid decision-router selection')
210
+ }
211
+ if (Object.hasOwn(update, 'enabled') && typeof update.enabled !== 'boolean') {
212
+ throw new TypeError('Enabled must be explicitly true or false')
213
+ }
214
+ if (Object.hasOwn(update, 'egress_consent') && typeof update.egress_consent !== 'boolean') {
215
+ throw new TypeError('Egress consent must be explicitly true or false')
216
+ }
217
+ if (
218
+ Object.hasOwn(update, 'enabled_candidates') &&
219
+ normalizeEnabledCandidates(update.enabled_candidates) === null
220
+ ) {
221
+ throw new TypeError('Invalid enabled provider/model candidates')
222
+ }
223
+ const next = { ...current, ...update }
224
+ // Selecting a different provider/model target is not consent for it (D9):
225
+ // `select` records a preference and can only ever leave egress OFF. A
226
+ // previously recorded consent is revoked when the target moves, unless the
227
+ // caller passes `egress_consent` in the same explicit update (an admin
228
+ // surface that names both fields at once).
229
+ if (
230
+ Object.hasOwn(update, 'selection') &&
231
+ !Object.hasOwn(update, 'egress_consent') &&
232
+ !sameSelection(normalizeSelection(update.selection), current.selection)
233
+ ) {
234
+ next.egress_consent = false
235
+ }
236
+ const normalized = migrateUserDecisionRouterConfig(next)
237
+ if (normalized.selection.mode === 'local' && update.egress_consent === true) {
238
+ throw new TypeError('Local selection cannot enable egress consent')
239
+ }
240
+ return normalized
241
+ }
242
+
243
+ /** True only when the user explicitly enabled turn selection. */
244
+ export function isUserDecisionRouterEnabled(config) {
245
+ return migrateUserDecisionRouterConfig(config).enabled
246
+ }
247
+
248
+ function eligibleAutoCandidates(preference, capValidCandidates) {
249
+ const validKeys = new Set(
250
+ capValidCandidates
251
+ .filter(isKnownCandidate)
252
+ .map(({ provider, model }) => candidateKey(normalizeDecisionProviderId(provider), model)),
253
+ )
254
+ return preference.enabled_candidates.filter(
255
+ (candidate) =>
256
+ remotelyEligibleProviders.has(candidate.provider) &&
257
+ validKeys.has(candidateKey(candidate.provider, candidate.model)),
258
+ )
259
+ }
260
+
261
+ /**
262
+ * Explain an Auto selection with an explicit cardinality branch (D5).
263
+ *
264
+ * The defect this closes: 0 and 2+ eligible candidates both collapsed into a
265
+ * single `null`, so a caller could not tell "nothing is enabled" from "several
266
+ * are enabled and I refuse to guess". The three outcomes below are distinct
267
+ * values with distinct reason codes, and every refusal names the state that
268
+ * caused it.
269
+ *
270
+ * @param {unknown} config
271
+ * @param {ReadonlyArray<{ provider: string, model: string }>} [capValidCandidates]
272
+ * @returns {{ outcome: 'ineligible', reason: 'DISABLED'|'CONSENT_MISSING'|'NOT_AUTO' }
273
+ * | { outcome: 'none', reason: 'NO_ELIGIBLE_CANDIDATE', count: 0 }
274
+ * | { outcome: 'single', reason: 'SINGLE_ELIGIBLE_CANDIDATE', count: 1,
275
+ * candidate: { provider: string, model: string } }
276
+ * | { outcome: 'ambiguous', reason: 'MULTIPLE_ELIGIBLE_CANDIDATES', count: number }}
277
+ */
278
+ export function explainUserDecisionRouterAutoSelection(config, capValidCandidates = []) {
279
+ const preference = migrateUserDecisionRouterConfig(config)
280
+ // Preconditions are reported as ineligible, never as a cardinality outcome:
281
+ // a disabled router with two candidates is disabled, not ambiguous.
282
+ if (!preference.enabled) return { outcome: 'ineligible', reason: 'DISABLED' }
283
+ if (!preference.egress_consent) return { outcome: 'ineligible', reason: 'CONSENT_MISSING' }
284
+ if (preference.selection.mode !== 'auto') return { outcome: 'ineligible', reason: 'NOT_AUTO' }
285
+
286
+ const eligible = eligibleAutoCandidates(preference, capValidCandidates)
287
+ if (eligible.length === 0) {
288
+ return { outcome: 'none', reason: 'NO_ELIGIBLE_CANDIDATE', count: 0 }
289
+ }
290
+ if (eligible.length > 1) {
291
+ return {
292
+ outcome: 'ambiguous',
293
+ reason: 'MULTIPLE_ELIGIBLE_CANDIDATES',
294
+ count: eligible.length,
295
+ }
296
+ }
297
+ return {
298
+ outcome: 'single',
299
+ reason: 'SINGLE_ELIGIBLE_CANDIDATE',
300
+ count: 1,
301
+ candidate: eligible[0],
302
+ }
303
+ }
304
+
305
+ /** Auto resolves only one enabled, cap-valid direct provider/model tuple. */
306
+ export function resolveUserDecisionRouterCandidate(config, capValidCandidates = []) {
307
+ const preference = migrateUserDecisionRouterConfig(config)
308
+ if (!preference.enabled || !preference.egress_consent) return null
309
+ if (preference.selection.mode === 'local') return null
310
+ if (preference.selection.mode === 'explicit') {
311
+ const selected = preference.selection
312
+ const enabled = eligibleAutoCandidates(preference, capValidCandidates)
313
+ return (
314
+ enabled.find(
315
+ (candidate) =>
316
+ candidateKey(candidate.provider, candidate.model) ===
317
+ candidateKey(selected.provider, selected.model),
318
+ ) ?? null
319
+ )
320
+ }
321
+ const explained = explainUserDecisionRouterAutoSelection(preference, capValidCandidates)
322
+ return explained.outcome === 'single' ? explained.candidate : null
323
+ }
324
+
325
+ /** Read only a private user-level JSON file. Invalid contents fail closed. */
326
+ export function readUserDecisionRouterConfig({ env = process.env } = {}) {
327
+ const filePath = resolveUserDecisionRouterConfigPath(env)
328
+ try {
329
+ assertNoSymlinkAncestors(filePath)
330
+ assertTrustedDirectoryChain(dirname(filePath))
331
+ const stat = lstatSync(filePath)
332
+ assertPrivatePath(stat, true)
333
+ const parsed = JSON.parse(readFileSync(filePath, 'utf8'))
334
+ return migrateUserDecisionRouterConfig(parsed)
335
+ } catch (error) {
336
+ if (error?.code === 'ENOENT') return cloneDefaultUserConfig()
337
+ throw error
338
+ }
339
+ }
340
+
341
+ /** Persist only non-secret preference data in a user-owned 0600 file. */
342
+ export function writeUserDecisionRouterConfig(config, { env = process.env } = {}) {
343
+ const normalized = migrateUserDecisionRouterConfig(config)
344
+ if (JSON.stringify(normalized) !== JSON.stringify(config)) {
345
+ throw new TypeError('Refusing to persist invalid decision-router configuration')
346
+ }
347
+ const filePath = resolveUserDecisionRouterConfigPath(env)
348
+ const directory = dirname(filePath)
349
+ assertNoSymlinkAncestors(directory, { includeLeaf: false })
350
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
351
+ assertNoSymlinkAncestors(directory)
352
+ assertTrustedDirectoryChain(directory)
353
+ assertPrivateDirectory(directory)
354
+ try {
355
+ const existing = lstatSync(filePath)
356
+ assertPrivatePath(existing, true)
357
+ } catch (error) {
358
+ if (error?.code !== 'ENOENT') throw error
359
+ }
360
+ writeFileAtomically(filePath, serializeUserDecisionRouterConfig(normalized))
361
+ chmodSync(filePath, 0o600)
362
+ return filePath
363
+ }
364
+
365
+ /**
366
+ * The only serializer for the user-level config.
367
+ *
368
+ * A preview is honest only when the bytes it compares are the bytes the writer
369
+ * would produce, so the preview and the writer share this function. It is
370
+ * deliberately free of clock and environment reads.
371
+ *
372
+ * @param {unknown} config
373
+ * @returns {string}
374
+ */
375
+ export function serializeUserDecisionRouterConfig(config) {
376
+ return `${JSON.stringify(migrateUserDecisionRouterConfig(config), null, 2)}\n`
377
+ }
378
+
379
+ /**
380
+ * Project the user-level configuration onto the only install-state record that
381
+ * may exist (D7).
382
+ *
383
+ * Install-state records a target preference; the runtime reads the user-level
384
+ * file. Deriving the record from that file is what keeps the two surfaces from
385
+ * disagreeing: there is no second place where a provider or a consent decision
386
+ * can be typed in. The projection carries the user's own consent boolean, so it
387
+ * can never assert consent the runtime configuration does not have.
388
+ *
389
+ * @param {unknown} userConfig
390
+ * @returns {{ schema_version: 1, provider: string, egress_consent: boolean }}
391
+ */
392
+ export function projectDecisionRouterInstallState(userConfig) {
393
+ const preference = migrateUserDecisionRouterConfig(userConfig)
394
+ const provider =
395
+ preference.selection.mode === 'explicit'
396
+ ? normalizeDecisionProviderId(preference.selection.provider)
397
+ : preference.selection.mode
398
+ return migrateDecisionRouterConfig({
399
+ schema_version: DECISION_ROUTER_CONFIG_SCHEMA_VERSION,
400
+ provider,
401
+ egress_consent: preference.egress_consent,
402
+ })
403
+ }
404
+
405
+ /**
406
+ * Field-level divergence between install-state and the user-level config (D7).
407
+ * Returns field NAMES and both states, never free-form content; callers print a
408
+ * reconciliation instruction instead of rewriting the record silently.
409
+ *
410
+ * @param {unknown} userConfig
411
+ * @param {unknown} installStateRecord
412
+ * @returns {{ expected: object, actual: object, differences: Array<{ field: string, installState: unknown, userConfig: unknown }> }}
413
+ */
414
+ export function diffDecisionRouterSurfaces(userConfig, installStateRecord) {
415
+ const expected = projectDecisionRouterInstallState(userConfig)
416
+ const actual = migrateDecisionRouterConfig(installStateRecord)
417
+ const differences = []
418
+ if (actual.provider !== expected.provider) {
419
+ differences.push({
420
+ field: 'provider',
421
+ installState: actual.provider,
422
+ userConfig: expected.provider,
423
+ })
424
+ }
425
+ if (actual.egress_consent !== expected.egress_consent) {
426
+ differences.push({
427
+ field: 'egress_consent',
428
+ installState: actual.egress_consent,
429
+ userConfig: expected.egress_consent,
430
+ })
431
+ }
432
+ return { expected, actual, differences }
433
+ }
434
+
435
+ function sameSelection(left, right) {
436
+ if (left === null || right === null) return left === right
437
+ if (left.mode !== right.mode) return false
438
+ if (left.mode !== 'explicit') return true
439
+ return left.provider === right.provider && left.model === right.model
440
+ }
441
+
442
+ function normalizeSelection(value) {
443
+ if (!isPlainObject(value) || typeof value.mode !== 'string') return null
444
+ if (value.mode === 'local' || value.mode === 'auto') {
445
+ return Object.keys(value).length === 1 ? { mode: value.mode } : null
446
+ }
447
+ if (
448
+ value.mode !== 'explicit' ||
449
+ Object.keys(value).length !== 3 ||
450
+ !isKnownCandidate({ provider: value.provider, model: value.model })
451
+ ) {
452
+ return null
453
+ }
454
+ return {
455
+ mode: 'explicit',
456
+ provider: normalizeDecisionProviderId(value.provider),
457
+ model: value.model,
458
+ }
459
+ }
460
+
461
+ function normalizeEnabledCandidates(value) {
462
+ const seen = new Set()
463
+ const result = []
464
+ for (const item of value) {
465
+ if (!isKnownCandidate(item) || Object.keys(item).length !== 2) return null
466
+ const provider = normalizeDecisionProviderId(item.provider)
467
+ const key = candidateKey(provider, item.model)
468
+ if (seen.has(key)) return null
469
+ seen.add(key)
470
+ result.push({ provider, model: item.model })
471
+ }
472
+ return result
473
+ }
474
+
475
+ function isKnownCandidate(value) {
476
+ if (
477
+ !isPlainObject(value) ||
478
+ typeof value.provider !== 'string' ||
479
+ typeof value.model !== 'string'
480
+ ) {
481
+ return false
482
+ }
483
+ const provider = normalizeDecisionProviderId(value.provider)
484
+ return (
485
+ userCandidateProviders.has(provider) && DECISION_ROUTER_MODELS[provider].includes(value.model)
486
+ )
487
+ }
488
+
489
+ function candidateKey(provider, model) {
490
+ return `${provider}/${model}`
491
+ }
492
+
493
+ function isPlainObject(value) {
494
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
495
+ const prototype = Object.getPrototypeOf(value)
496
+ return prototype === Object.prototype || prototype === null
497
+ }
498
+
499
+ function hasExactKeys(value, keys) {
500
+ const actual = Object.keys(value).sort()
501
+ const expected = [...keys].sort()
502
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index])
503
+ }
504
+
505
+ function cloneDefaultUserConfig() {
506
+ return {
507
+ schema_version: DEFAULT_USER_DECISION_ROUTER_CONFIG.schema_version,
508
+ enabled: false,
509
+ selection: { mode: 'local' },
510
+ egress_consent: false,
511
+ enabled_candidates: [],
512
+ }
513
+ }
514
+
515
+ function assertPrivatePath(stat, isFile) {
516
+ if (stat.isSymbolicLink() || (isFile ? !stat.isFile() : !stat.isDirectory())) {
517
+ throw new Error('Decision-router configuration path is not a regular private path')
518
+ }
519
+ if (typeof process.getuid !== 'function' || stat.uid !== process.getuid()) {
520
+ throw new Error('Decision-router configuration must be owned by the current user')
521
+ }
522
+ if ((stat.mode & 0o077) !== 0)
523
+ throw new Error('Decision-router configuration permissions must be private')
524
+ }
525
+
526
+ function assertPrivateDirectory(directory) {
527
+ const stat = lstatSync(directory)
528
+ assertPrivatePath(stat, false)
529
+ }
530
+
531
+ function assertTrustedDirectoryChain(directory) {
532
+ const absolute = resolve(directory)
533
+ const root = parse(absolute).root
534
+ const parts = absolute.slice(root.length).split(sep).filter(Boolean)
535
+ let current = root
536
+ const uid = process.getuid?.()
537
+ if (uid === undefined)
538
+ throw new Error('Decision-router configuration requires user ownership checks')
539
+ for (const part of parts) {
540
+ current = join(current, part)
541
+ let stat
542
+ try {
543
+ stat = lstatSync(current)
544
+ } catch (error) {
545
+ if (error?.code === 'ENOENT') return
546
+ throw error
547
+ }
548
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
549
+ throw new Error('Decision-router configuration path contains a non-directory component')
550
+ }
551
+ if (stat.uid !== uid && stat.uid !== 0) {
552
+ throw new Error('Decision-router configuration path has an untrusted owner')
553
+ }
554
+ const mode = stat.mode & 0o7777
555
+ const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
556
+ if ((mode & 0o022) !== 0 && !rootStickyDirectory) {
557
+ throw new Error('Decision-router configuration path is writable by other users')
558
+ }
559
+ }
560
+ }
@@ -198,27 +198,36 @@ export function healthCheck(target, { dryRun = false, pythonTarget = target } =
198
198
  // repointed: check 5 already asserts the capability that matters, and a
199
199
  // second sqlite3 import probe would tell us nothing new.
200
200
 
201
- // Check 5: SQLite FTS5 available
201
+ // Check 5: prove FTS5 can actually create a virtual table. Compile flags alone
202
+ // are not a capability test, and the memory MCP has no supported fallback.
202
203
  if (python) {
203
204
  const fts5Cmd = [
204
205
  '-c',
205
- 'import sqlite3; ' +
206
- "row = sqlite3.connect(':memory:').execute('PRAGMA compile_options').fetchall(); " +
207
- "fts5 = any('ENABLE_FTS5' in str(r[0]) for r in row); " +
208
- "print(f'SQLite {sqlite3.sqlite_version} FTS5={fts5}')",
206
+ 'import sqlite3, sys\n' +
207
+ "db = sqlite3.connect(':memory:')\n" +
208
+ 'version = sqlite3.sqlite_version\n' +
209
+ 'try:\n' +
210
+ ' db.execute("CREATE VIRTUAL TABLE fts5_probe USING fts5(content)")\n' +
211
+ 'except sqlite3.Error as exc:\n' +
212
+ ' print(f"SQLite {version} FTS5=False: {exc}")\n' +
213
+ ' sys.exit(1)\n' +
214
+ 'print(f"SQLite {version} FTS5=True")',
209
215
  ]
210
216
  const result = spawnSync(python, fts5Cmd, { stdio: 'pipe' })
211
- if (result.status === 0) {
212
- results.passed.push({
213
- check: 'sqlite-fts5',
214
- detail: result.stdout.toString().trim(),
215
- })
217
+ const detail = result.stdout.toString().trim() || result.stderr.toString().trim()
218
+ if (result.status === 0 && /\bFTS5=True\b/.test(detail)) {
219
+ results.passed.push({ check: 'sqlite-fts5', detail })
216
220
  } else {
217
221
  results.failed.push({
218
222
  check: 'sqlite-fts5',
219
- detail: result.stderr.toString().trim().split('\n').slice(-1)[0],
223
+ detail: detail || 'Python could not verify SQLite FTS5 support',
220
224
  })
221
225
  }
226
+ } else {
227
+ results.failed.push({
228
+ check: 'sqlite-fts5',
229
+ detail: 'Python is unavailable for the FTS5 probe',
230
+ })
222
231
  }
223
232
 
224
233
  return results