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,456 @@
1
+ /**
2
+ * V2 decision budget surface — three separate concerns, never one blob (D6).
3
+ *
4
+ * The defect this closes: CAP, PERIOD and LEDGER were coupled inside
5
+ * `local-decision-budget.ts`, so a read of one concern went through the same
6
+ * open path as the others and an administrative listing could create the
7
+ * database or apply a forward-only migration. This module separates them:
8
+ *
9
+ * - **cap** — user / provider / model USD micros, and the per-decision
10
+ * hierarchy between them;
11
+ * - **period** — the explicitly confirmed UTC accounting month and the wall
12
+ * clock it must match;
13
+ * - **ledger** — committed spend, freeze state and whether the SQLite file is
14
+ * even present.
15
+ *
16
+ * Each concern has its own gate and its own reason-code set, so a caller can
17
+ * exercise one without the others, and each denial names the concern that
18
+ * produced it. The gates are **diagnostic**: they explain why admission would
19
+ * be refused. They never reserve, reconcile, prune or write; the accounting
20
+ * authority remains the transactional ledger in `local-decision-budget.ts`.
21
+ *
22
+ * Reads are strictly read-only: `node:sqlite` is opened with `readOnly: true`,
23
+ * which cannot create the file and cannot migrate it. A missing database is a
24
+ * fact (`present: false`), not an error and not a reason to create one.
25
+ */
26
+ import { lstatSync } from 'node:fs'
27
+ import { DatabaseSync } from 'node:sqlite'
28
+
29
+ /** The three decoupled concerns. */
30
+ export type DecisionBudgetConcern = 'cap' | 'period' | 'ledger'
31
+
32
+ export interface DecisionCaps {
33
+ readonly monthlyCapMicros: number
34
+ readonly perDecisionCapMicros: number
35
+ }
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // CAP concern
39
+ // ---------------------------------------------------------------------------
40
+
41
+ export type CapGateDenial = 'no-cap' | 'per-decision-cap' | 'invalid-caps'
42
+
43
+ export type CapGateResult =
44
+ | { concern: 'cap'; ok: true; reservedMicros: number }
45
+ | { concern: 'cap'; ok: false; reason: CapGateDenial }
46
+
47
+ export interface CapGateInput {
48
+ readonly user: DecisionCaps | undefined
49
+ readonly provider: DecisionCaps | undefined
50
+ readonly model: DecisionCaps | undefined
51
+ }
52
+
53
+ function isPositiveCaps(value: DecisionCaps | undefined): value is DecisionCaps {
54
+ return (
55
+ value !== undefined &&
56
+ Number.isSafeInteger(value.monthlyCapMicros) &&
57
+ Number.isSafeInteger(value.perDecisionCapMicros) &&
58
+ value.monthlyCapMicros > 0 &&
59
+ value.perDecisionCapMicros > 0
60
+ )
61
+ }
62
+
63
+ /**
64
+ * Decide only the CAP concern.
65
+ *
66
+ * The per-decision reservation is the model's configured maximum, and no wider
67
+ * scope may admit more than its own per-decision cap — the same hierarchy the
68
+ * ledger enforces. Zero and missing caps deny: there are no default caps.
69
+ */
70
+ export function evaluateCapGate(input: CapGateInput): CapGateResult {
71
+ const { user, provider, model } = input
72
+ for (const caps of [user, provider, model]) {
73
+ if (caps === undefined) continue
74
+ if (
75
+ !Number.isSafeInteger(caps.monthlyCapMicros) ||
76
+ !Number.isSafeInteger(caps.perDecisionCapMicros) ||
77
+ caps.monthlyCapMicros < 0 ||
78
+ caps.perDecisionCapMicros < 0
79
+ ) {
80
+ return { concern: 'cap', ok: false, reason: 'invalid-caps' }
81
+ }
82
+ }
83
+ if (!isPositiveCaps(user) || !isPositiveCaps(provider) || !isPositiveCaps(model)) {
84
+ return { concern: 'cap', ok: false, reason: 'no-cap' }
85
+ }
86
+ const reservedMicros = model.perDecisionCapMicros
87
+ if (
88
+ reservedMicros > user.perDecisionCapMicros ||
89
+ reservedMicros > provider.perDecisionCapMicros
90
+ ) {
91
+ return { concern: 'cap', ok: false, reason: 'per-decision-cap' }
92
+ }
93
+ return { concern: 'cap', ok: true, reservedMicros }
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // PERIOD concern
98
+ // ---------------------------------------------------------------------------
99
+
100
+ export type PeriodGateDenial = 'invalid-period' | 'period-unconfirmed' | 'period-mismatch'
101
+
102
+ export type PeriodGateResult =
103
+ | { concern: 'period'; ok: true; period: string }
104
+ | { concern: 'period'; ok: false; reason: PeriodGateDenial }
105
+
106
+ const PERIOD_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/
107
+
108
+ /** The UTC accounting month of an instant. No timezone is assumed. */
109
+ export function utcPeriodOf(instantMs: number): string | null {
110
+ if (!Number.isSafeInteger(instantMs) || instantMs < 0) return null
111
+ const period = new Date(instantMs).toISOString().slice(0, 7)
112
+ return PERIOD_PATTERN.test(period) ? period : null
113
+ }
114
+
115
+ /**
116
+ * Decide only the PERIOD concern.
117
+ *
118
+ * An unconfirmed period denies; a confirmed period must equal the current UTC
119
+ * month. Crossing a calendar month never advances it automatically — that is
120
+ * still an explicit `period confirm` action.
121
+ */
122
+ export function evaluatePeriodGate(input: {
123
+ readonly activePeriod: string | null
124
+ readonly wallPeriod: string | null
125
+ }): PeriodGateResult {
126
+ if (input.wallPeriod === null || !PERIOD_PATTERN.test(input.wallPeriod)) {
127
+ return { concern: 'period', ok: false, reason: 'invalid-period' }
128
+ }
129
+ if (input.activePeriod === null) {
130
+ return { concern: 'period', ok: false, reason: 'period-unconfirmed' }
131
+ }
132
+ if (!PERIOD_PATTERN.test(input.activePeriod)) {
133
+ return { concern: 'period', ok: false, reason: 'invalid-period' }
134
+ }
135
+ if (input.activePeriod !== input.wallPeriod) {
136
+ return { concern: 'period', ok: false, reason: 'period-mismatch' }
137
+ }
138
+ return { concern: 'period', ok: true, period: input.activePeriod }
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // LEDGER concern
143
+ // ---------------------------------------------------------------------------
144
+
145
+ export type LedgerGateDenial = 'ledger-missing' | 'frozen' | 'monthly-cap'
146
+
147
+ export type LedgerGateResult =
148
+ | { concern: 'ledger'; ok: true }
149
+ | { concern: 'ledger'; ok: false; reason: LedgerGateDenial }
150
+
151
+ /**
152
+ * Decide only the LEDGER concern: capacity against the three monthly buckets,
153
+ * plus an explicit freeze. It receives amounts, never reads the database.
154
+ */
155
+ export function evaluateLedgerGate(input: {
156
+ readonly present: boolean
157
+ readonly frozen: boolean
158
+ readonly reservedMicros: number
159
+ readonly userCommittedMicros: number
160
+ readonly userMonthlyCapMicros: number
161
+ readonly providerCommittedMicros: number
162
+ readonly providerMonthlyCapMicros: number
163
+ readonly modelCommittedMicros: number
164
+ readonly modelMonthlyCapMicros: number
165
+ }): LedgerGateResult {
166
+ if (!input.present) return { concern: 'ledger', ok: false, reason: 'ledger-missing' }
167
+ if (input.frozen) return { concern: 'ledger', ok: false, reason: 'frozen' }
168
+ const additional = input.reservedMicros
169
+ const exceeds = (committed: number, cap: number): boolean =>
170
+ committed > cap || additional > cap - committed
171
+ if (
172
+ exceeds(input.userCommittedMicros, input.userMonthlyCapMicros) ||
173
+ exceeds(input.providerCommittedMicros, input.providerMonthlyCapMicros) ||
174
+ exceeds(input.modelCommittedMicros, input.modelMonthlyCapMicros)
175
+ ) {
176
+ return { concern: 'ledger', ok: false, reason: 'monthly-cap' }
177
+ }
178
+ return { concern: 'ledger', ok: true }
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Composition
183
+ // ---------------------------------------------------------------------------
184
+
185
+ export type DecisionBudgetAdmission =
186
+ | { admitted: true; period: string; reservedMicros: number }
187
+ | {
188
+ admitted: false
189
+ concern: DecisionBudgetConcern
190
+ reason: CapGateDenial | PeriodGateDenial | LedgerGateDenial
191
+ }
192
+
193
+ /**
194
+ * Compose the three gates in a fixed order — cap, period, ledger — so the same
195
+ * input always reports the same concern. The order matters for explanation
196
+ * only: every denial is a refusal either way.
197
+ */
198
+ export function evaluateDecisionBudgetAdmission(input: {
199
+ readonly caps: CapGateInput
200
+ readonly period: { readonly activePeriod: string | null; readonly wallPeriod: string | null }
201
+ readonly ledger: Omit<Parameters<typeof evaluateLedgerGate>[0], 'present' | 'reservedMicros'>
202
+ }): DecisionBudgetAdmission {
203
+ const cap = evaluateCapGate(input.caps)
204
+ if (!cap.ok) return { admitted: false, concern: cap.concern, reason: cap.reason }
205
+ const period = evaluatePeriodGate(input.period)
206
+ if (!period.ok) return { admitted: false, concern: period.concern, reason: period.reason }
207
+ const ledger = evaluateLedgerGate({
208
+ ...input.ledger,
209
+ present: true,
210
+ reservedMicros: cap.reservedMicros,
211
+ })
212
+ if (!ledger.ok) return { admitted: false, concern: ledger.concern, reason: ledger.reason }
213
+ return { admitted: true, period: period.period, reservedMicros: cap.reservedMicros }
214
+ }
215
+
216
+ // ---------------------------------------------------------------------------
217
+ // Read-only inspection
218
+ // ---------------------------------------------------------------------------
219
+
220
+ export type DecisionBudgetLedgerFacts =
221
+ | { present: false }
222
+ | {
223
+ present: true
224
+ readable: true
225
+ schemaVersion: number
226
+ applicationId: number
227
+ activePeriod: string | null
228
+ reservations: number
229
+ holds: number
230
+ freezes: number
231
+ }
232
+ | { present: true; readable: false; reason: 'not-a-regular-file' | 'unsupported-schema' }
233
+
234
+ export interface DecisionCapFacts {
235
+ readonly user: DecisionCaps | null
236
+ readonly providers: Readonly<Record<string, DecisionCaps>>
237
+ readonly models: Readonly<Record<string, DecisionCaps>>
238
+ }
239
+
240
+ const EXPECTED_APPLICATION_ID = 0x50424c31
241
+
242
+ type DbPathKind = 'missing' | 'regular' | 'unsafe'
243
+
244
+ function classifyDbPath(dbPath: string): DbPathKind {
245
+ try {
246
+ const stat = lstatSync(dbPath)
247
+ return stat.isFile() && !stat.isSymbolicLink() ? 'regular' : 'unsafe'
248
+ } catch {
249
+ return 'missing'
250
+ }
251
+ }
252
+
253
+ function readCapsRow(
254
+ db: DatabaseSync,
255
+ sql: string,
256
+ ): { monthly: number; perDecision: number } | null {
257
+ const row = db.prepare(sql).get() as
258
+ | { monthly_cap_micros: number | bigint; per_decision_cap_micros: number | bigint }
259
+ | undefined
260
+ if (!row) return null
261
+ return {
262
+ monthly: Number(row.monthly_cap_micros),
263
+ perDecision: Number(row.per_decision_cap_micros),
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Read the LEDGER concern without creating or migrating anything.
269
+ *
270
+ * `present: false` is returned when the file is absent — the caller must not
271
+ * conclude "no spend"; only "no ledger". A schema this module does not know is
272
+ * reported as unreadable rather than opened for migration.
273
+ */
274
+ export function readDecisionBudgetLedgerFacts(dbPath: string): DecisionBudgetLedgerFacts {
275
+ const kind = classifyDbPath(dbPath)
276
+ if (kind === 'missing') return { present: false }
277
+ if (kind === 'unsafe') {
278
+ return { present: true, readable: false, reason: 'not-a-regular-file' }
279
+ }
280
+ let db: DatabaseSync
281
+ try {
282
+ db = new DatabaseSync(dbPath, { readOnly: true })
283
+ } catch {
284
+ return { present: true, readable: false, reason: 'unsupported-schema' }
285
+ }
286
+ try {
287
+ const version = (db.prepare('PRAGMA user_version').get() as { user_version: number })
288
+ .user_version
289
+ const applicationId = (db.prepare('PRAGMA application_id').get() as { application_id: number })
290
+ .application_id
291
+ if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) {
292
+ return { present: true, readable: false, reason: 'unsupported-schema' }
293
+ }
294
+ const activeRow = db.prepare('SELECT active_period_utc FROM ledger_state WHERE id = 1').get() as
295
+ | { active_period_utc: string | null }
296
+ | undefined
297
+ const counts = db
298
+ .prepare(
299
+ `SELECT
300
+ COUNT(*) AS reservations,
301
+ COALESCE(SUM(CASE WHEN state IN ('pending', 'uncertain') THEN 1 ELSE 0 END), 0) AS holds
302
+ FROM reservations`,
303
+ )
304
+ .get() as { reservations: number | bigint; holds: number | bigint }
305
+ const freezes = db.prepare('SELECT COUNT(*) AS total FROM budget_freezes').get() as {
306
+ total: number | bigint
307
+ }
308
+ return {
309
+ present: true,
310
+ readable: true,
311
+ schemaVersion: version,
312
+ applicationId,
313
+ activePeriod: activeRow?.active_period_utc ?? null,
314
+ reservations: Number(counts.reservations),
315
+ holds: Number(counts.holds),
316
+ freezes: Number(freezes.total),
317
+ }
318
+ } catch {
319
+ return { present: true, readable: false, reason: 'unsupported-schema' }
320
+ } finally {
321
+ db.close()
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Read the CAP concern only. Returns `null` when the ledger does not exist, so
327
+ * an absent database never looks like "caps configured to zero".
328
+ */
329
+ export function readDecisionCapFacts(dbPath: string): DecisionCapFacts | null {
330
+ if (classifyDbPath(dbPath) !== 'regular') return null
331
+ let db: DatabaseSync
332
+ try {
333
+ db = new DatabaseSync(dbPath, { readOnly: true })
334
+ } catch {
335
+ return null
336
+ }
337
+ try {
338
+ const user = readCapsRow(
339
+ db,
340
+ 'SELECT monthly_cap_micros, per_decision_cap_micros FROM user_caps WHERE id = 1',
341
+ )
342
+ const providers: Record<string, DecisionCaps> = {}
343
+ for (const row of db
344
+ .prepare('SELECT provider, monthly_cap_micros, per_decision_cap_micros FROM provider_caps')
345
+ .all() as Array<{
346
+ provider: string
347
+ monthly_cap_micros: number | bigint
348
+ per_decision_cap_micros: number | bigint
349
+ }>) {
350
+ providers[row.provider] = {
351
+ monthlyCapMicros: Number(row.monthly_cap_micros),
352
+ perDecisionCapMicros: Number(row.per_decision_cap_micros),
353
+ }
354
+ }
355
+ const models: Record<string, DecisionCaps> = {}
356
+ for (const row of db
357
+ .prepare(
358
+ 'SELECT provider, model, monthly_cap_micros, per_decision_cap_micros FROM model_caps',
359
+ )
360
+ .all() as Array<{
361
+ provider: string
362
+ model: string
363
+ monthly_cap_micros: number | bigint
364
+ per_decision_cap_micros: number | bigint
365
+ }>) {
366
+ models[`${row.provider}/${row.model}`] = {
367
+ monthlyCapMicros: Number(row.monthly_cap_micros),
368
+ perDecisionCapMicros: Number(row.per_decision_cap_micros),
369
+ }
370
+ }
371
+ return {
372
+ user:
373
+ user === null
374
+ ? null
375
+ : { monthlyCapMicros: user.monthly, perDecisionCapMicros: user.perDecision },
376
+ providers,
377
+ models,
378
+ }
379
+ } catch {
380
+ return null
381
+ } finally {
382
+ db.close()
383
+ }
384
+ }
385
+
386
+ /** Convenience: the three concerns read through one call, each still separate. */
387
+ export function inspectDecisionBudget(dbPath: string): {
388
+ ledger: DecisionBudgetLedgerFacts
389
+ caps: DecisionCapFacts | null
390
+ period: { activePeriod: string | null }
391
+ } {
392
+ const ledger = readDecisionBudgetLedgerFacts(dbPath)
393
+ const caps = readDecisionCapFacts(dbPath)
394
+ const activePeriod = ledger.present && ledger.readable ? ledger.activePeriod : null
395
+ return { ledger, caps, period: { activePeriod } }
396
+ }
397
+
398
+ export interface DecisionHoldRow {
399
+ readonly reservationId: string
400
+ readonly provider: string
401
+ readonly model: string
402
+ readonly period: string
403
+ readonly reservedMicros: number
404
+ readonly state: 'pending' | 'uncertain'
405
+ }
406
+
407
+ /**
408
+ * List unresolved holds read-only.
409
+ *
410
+ * The previous listing opened the ledger for write, so a read could create the
411
+ * database or apply a forward-only migration (D8). This one cannot: the
412
+ * connection is read-only, and a missing or unknown-schema ledger returns
413
+ * `null` instead of being created or migrated.
414
+ */
415
+ export function listDecisionHoldsReadOnly(dbPath: string): DecisionHoldRow[] | null {
416
+ if (classifyDbPath(dbPath) !== 'regular') return null
417
+ let db: DatabaseSync
418
+ try {
419
+ db = new DatabaseSync(dbPath, { readOnly: true })
420
+ } catch {
421
+ return null
422
+ }
423
+ try {
424
+ const applicationId = (db.prepare('PRAGMA application_id').get() as { application_id: number })
425
+ .application_id
426
+ const version = (db.prepare('PRAGMA user_version').get() as { user_version: number })
427
+ .user_version
428
+ if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) return null
429
+ const rows = db
430
+ .prepare(
431
+ `SELECT id, provider, model, period_utc, reserved_micros, state
432
+ FROM reservations WHERE state IN ('pending', 'uncertain')
433
+ ORDER BY created_at_ms, id`,
434
+ )
435
+ .all() as Array<{
436
+ id: string
437
+ provider: string
438
+ model: string
439
+ period_utc: string
440
+ reserved_micros: number | bigint
441
+ state: 'pending' | 'uncertain'
442
+ }>
443
+ return rows.map((row) => ({
444
+ reservationId: row.id,
445
+ provider: row.provider,
446
+ model: row.model,
447
+ period: row.period_utc,
448
+ reservedMicros: Number(row.reserved_micros),
449
+ state: row.state,
450
+ }))
451
+ } catch {
452
+ return null
453
+ } finally {
454
+ db.close()
455
+ }
456
+ }