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

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 (35) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +38 -1
  3. package/bin/pantheon-init.mjs +17 -0
  4. package/package.json +9 -3
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +781 -0
  8. package/scripts/decision-router.mjs +297 -0
  9. package/scripts/install/decision-router-config.mjs +432 -0
  10. package/scripts/install/interactive.mjs +76 -5
  11. package/scripts/install/opencode.mjs +12 -0
  12. package/scripts/install/state.mjs +5 -0
  13. package/scripts/install/strings.mjs +4 -0
  14. package/src/agents/zeus.md +12 -0
  15. package/src/pantheon/local-decision-agents.ts +170 -0
  16. package/src/pantheon/local-decision-budget.ts +1043 -0
  17. package/src/pantheon/local-decision-egress-gate.ts +264 -0
  18. package/src/pantheon/local-decision-prompt.ts +123 -0
  19. package/src/pantheon/local-decision-provider-matrix.ts +92 -0
  20. package/src/pantheon/local-decision-provider-protocol.ts +335 -0
  21. package/src/pantheon/local-decision-provider.internal.ts +260 -0
  22. package/src/pantheon/local-decision-router.ts +225 -0
  23. package/src/pantheon/local-decision-skills.ts +171 -0
  24. package/src/pantheon/local-decision-tool.ts +126 -0
  25. package/src/pantheon/local-decision-turn.ts +338 -0
  26. package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
  27. package/src/pantheon/local-orchestration.ts +322 -0
  28. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  29. package/src/pantheon/v2-tools.ts +15 -14
  30. package/src/plugin-v2.ts +52 -19
  31. package/src/plugin.ts +4 -0
  32. package/src/plugins/tui/dist/tui-v2.js +3 -3
  33. package/src/plugins/tui/dist/tui.js +1 -1
  34. package/src/plugins/tui/package-lock.json +2 -2
  35. package/src/plugins/tui/package.json +1 -1
@@ -0,0 +1,1043 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, type Stats } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
5
+ import { performance } from 'node:perf_hooks'
6
+ import { DatabaseSync } from 'node:sqlite'
7
+ import {
8
+ getVerifiedUsageEvidenceDetails,
9
+ type VerifiedUsageEvidence,
10
+ } from './local-decision-usage-evidence.internal.ts'
11
+
12
+ export type BudgetProvider = 'openai-decisions' | 'typesafe-jev' | 'opencode-console' | 'jev-free'
13
+
14
+ /** Model and OpenCode Console variant keys must be configured before admission. */
15
+ export type BudgetModel = string
16
+
17
+ export interface BudgetCaps {
18
+ /** Non-negative integer USD micros. Zero explicitly disables admission. */
19
+ monthlyCapMicros: number
20
+ /** Non-negative integer USD micros. Zero explicitly disables admission. */
21
+ perDecisionCapMicros: number
22
+ }
23
+
24
+ export type ReservationResult =
25
+ | {
26
+ status: 'reserved'
27
+ reservationId: string
28
+ period: string
29
+ reservedMicros: number
30
+ }
31
+ | {
32
+ status: 'denied'
33
+ reason:
34
+ | 'invalid-provider'
35
+ | 'invalid-model'
36
+ | 'no-cap'
37
+ | 'per-decision-cap'
38
+ | 'monthly-cap'
39
+ | 'frozen'
40
+ | 'duplicate-reservation-id'
41
+ | 'period-unconfirmed'
42
+ | 'period-mismatch'
43
+ | 'clock-untrusted'
44
+ }
45
+
46
+ export type ReservationDenialReason = Extract<ReservationResult, { status: 'denied' }>['reason']
47
+ export type AdmissionCheckResult =
48
+ | { status: 'eligible' }
49
+ | { status: 'denied'; reason: ReservationDenialReason }
50
+
51
+ export type PeriodConfirmationResult =
52
+ | { status: 'confirmed'; activePeriod: string }
53
+ | {
54
+ status: 'denied'
55
+ reason:
56
+ | 'invalid-period'
57
+ | 'stale-current'
58
+ | 'backwards'
59
+ | 'not-next-month'
60
+ | 'wall-clock-mismatch'
61
+ | 'clock-untrusted'
62
+ }
63
+
64
+ export type ReconciliationResult =
65
+ | { status: 'reconciled'; actualCostMicros: number; frozen: boolean }
66
+ | { status: 'unknown' | 'missing' | 'already-reconciled' | 'mismatch' }
67
+
68
+ export interface UncertainReservation {
69
+ reservationId: string
70
+ provider: BudgetProvider
71
+ model: BudgetModel
72
+ period: string
73
+ reservedMicros: number
74
+ state: 'pending' | 'uncertain'
75
+ createdAtMs: number
76
+ updatedAtMs: number
77
+ }
78
+
79
+ export interface LocalDecisionBudgetLedger {
80
+ /** Admin/configuration API: writes policy to the local user-level DB. */
81
+ configureUserCaps(caps: BudgetCaps): void
82
+ /** Shared cap applies to every model/variant registered for this provider. */
83
+ configureProviderCaps(provider: BudgetProvider, caps: BudgetCaps): void
84
+ /** Each model/variant has an independent monthly and per-decision cap. */
85
+ configureModelCaps(provider: BudgetProvider, model: BudgetModel, caps: BudgetCaps): void
86
+ /** Explicitly initialize or advance the persisted UTC budget month one month only. */
87
+ confirmBudgetPeriod(
88
+ expectedCurrentPeriod: string | null,
89
+ targetPeriod: string,
90
+ ): PeriodConfirmationResult
91
+ getActiveBudgetPeriod(): string | null
92
+ /** Read-only, transactionally consistent check used to count Auto candidates. */
93
+ canReserve(provider: BudgetProvider, model: BudgetModel): AdmissionCheckResult
94
+ /**
95
+ * Atomically reserves the model's configured per-decision maximum across the
96
+ * user, provider, and model buckets. No cost or cap comes from the caller.
97
+ */
98
+ reserve(provider: BudgetProvider, model: BudgetModel): ReservationResult
99
+ /** Accepts only an opaque capability minted by the internal usage verifier. */
100
+ reconcileVerified(reservationId: string, evidence: VerifiedUsageEvidence): ReconciliationResult
101
+ listUncertainReservations(): UncertainReservation[]
102
+ /** Recovery only moves pending rows to uncertain; it never releases budget. */
103
+ recoverPendingReservations(): number
104
+ /** Prune resolved reservations from past UTC periods with no unresolved holds. */
105
+ pruneCompletedPeriods(): number
106
+ close(): void
107
+ }
108
+
109
+ export interface OpenLocalDecisionBudgetOptions {
110
+ dbPath?: string
111
+ /** Test seams; monotonic time detects regressions but never selects a budget period. */
112
+ clock?: () => number
113
+ monotonicClock?: () => number
114
+ /** Test seam; duplicate generated IDs are denied without adding a reservation. */
115
+ reservationIdFactory?: () => string
116
+ /** SQLite lock wait; production defaults to five seconds, then errors fail closed. */
117
+ busyTimeoutMs?: number
118
+ }
119
+
120
+ const SCHEMA_VERSION = 3
121
+ const VERSION_TWO = 2
122
+ const APPLICATION_ID = 0x50424c31
123
+ const DB_FILENAME = 'decision-budget.sqlite'
124
+ /** Accounting provider IDs accepted by the ledger. */
125
+ export const LOCAL_DECISION_BUDGET_PROVIDERS: readonly BudgetProvider[] = Object.freeze([
126
+ 'openai-decisions',
127
+ 'typesafe-jev',
128
+ 'opencode-console',
129
+ 'jev-free',
130
+ ])
131
+ const ALLOWED_PROVIDERS = new Set<BudgetProvider>(LOCAL_DECISION_BUDGET_PROVIDERS)
132
+ const MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
133
+ const RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
134
+ const CLOCK_ROLLBACK_TOLERANCE_MS = 60_000
135
+
136
+ /** Resolve an account-wide path, independent of project install state. */
137
+ export function resolveLocalDecisionBudgetDbPath(
138
+ env: Readonly<Record<string, string | undefined>> = process.env,
139
+ ): string {
140
+ const xdgStateHome = env.XDG_STATE_HOME
141
+ const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir()
142
+ const base =
143
+ xdgStateHome && isAbsolute(xdgStateHome) ? xdgStateHome : join(home, '.local', 'state')
144
+ return resolve(base, 'pantheon', DB_FILENAME)
145
+ }
146
+
147
+ /**
148
+ * Open Pantheon's separate user-scoped accounting DB. New DBs have no policy
149
+ * and deny reservations. Schema upgrades are forward-only and preserve holds.
150
+ */
151
+ export function openLocalDecisionBudgetLedger(
152
+ options: OpenLocalDecisionBudgetOptions = {},
153
+ ): LocalDecisionBudgetLedger {
154
+ const dbPath = resolve(options.dbPath ?? resolveLocalDecisionBudgetDbPath())
155
+ if (['opencode.db', 'install-state.json'].includes(basename(dbPath))) {
156
+ throw new Error('The budget ledger must use its own SQLite database file')
157
+ }
158
+ const busyTimeoutMs = options.busyTimeoutMs ?? 5_000
159
+ if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 30_000) {
160
+ throw new RangeError('Invalid SQLite busy timeout')
161
+ }
162
+ const wallClock = options.clock ?? Date.now
163
+ const monotonicClock = options.monotonicClock ?? performance.now.bind(performance)
164
+ const reservationIdFactory = options.reservationIdFactory ?? randomUUID
165
+
166
+ const directoryPath = dirname(dbPath)
167
+ ensureTrustedDirectoryChain(directoryPath)
168
+
169
+ try {
170
+ const file = openSync(dbPath, 'wx', 0o600)
171
+ closeSync(file)
172
+ } catch (error) {
173
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
174
+ }
175
+ const fileStat = lstatSync(dbPath)
176
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1) {
177
+ throw new Error('Budget ledger path is not a private regular file')
178
+ }
179
+ if (typeof process.getuid !== 'function' || fileStat.uid !== process.getuid()) {
180
+ throw new Error('Budget ledger file must be owned by the current user')
181
+ }
182
+ chmodSync(dbPath, 0o600)
183
+
184
+ const db = new DatabaseSync(dbPath)
185
+ try {
186
+ db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}; PRAGMA foreign_keys = ON;`)
187
+ ensureSchema(db)
188
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;')
189
+ validateSchema(db)
190
+ } catch (error) {
191
+ db.close()
192
+ throw error
193
+ }
194
+
195
+ let previousWallClock: number | undefined
196
+ let previousMonotonicClock: number | undefined
197
+ const now = (): number => {
198
+ const wall = wallClock()
199
+ const monotonic = monotonicClock()
200
+ if (!Number.isSafeInteger(wall) || wall < 0 || !Number.isFinite(new Date(wall).getTime())) {
201
+ throw new Error('Invalid ledger wall clock')
202
+ }
203
+ if (!Number.isFinite(monotonic) || monotonic < 0) {
204
+ throw new Error('Invalid ledger monotonic clock')
205
+ }
206
+ if (previousWallClock !== undefined && previousMonotonicClock !== undefined) {
207
+ const wallElapsed = wall - previousWallClock
208
+ const monotonicElapsed = monotonic - previousMonotonicClock
209
+ if (
210
+ monotonicElapsed < 0 ||
211
+ wallElapsed < -CLOCK_ROLLBACK_TOLERANCE_MS ||
212
+ wallElapsed + CLOCK_ROLLBACK_TOLERANCE_MS < monotonicElapsed
213
+ ) {
214
+ throw new Error('Untrusted wall-clock movement')
215
+ }
216
+ }
217
+ previousWallClock = wall
218
+ previousMonotonicClock = monotonic
219
+ return wall
220
+ }
221
+
222
+ function inImmediateTransaction<T>(operation: () => T): T {
223
+ db.exec('BEGIN IMMEDIATE')
224
+ try {
225
+ const result = operation()
226
+ db.exec('COMMIT')
227
+ return result
228
+ } catch (error) {
229
+ try {
230
+ db.exec('ROLLBACK')
231
+ } catch {
232
+ // Preserve the original database failure. A failed transaction cannot admit.
233
+ }
234
+ throw error
235
+ }
236
+ }
237
+
238
+ function configureUserCaps(capsInput: BudgetCaps): void {
239
+ const caps = validateConfiguredCaps(capsInput)
240
+ inImmediateTransaction(() => {
241
+ const timestamp = now()
242
+ db.prepare(
243
+ `INSERT INTO user_caps (id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
244
+ VALUES (1, ?, ?, ?)
245
+ ON CONFLICT(id) DO UPDATE SET monthly_cap_micros = excluded.monthly_cap_micros,
246
+ per_decision_cap_micros = excluded.per_decision_cap_micros,
247
+ updated_at_ms = excluded.updated_at_ms`,
248
+ ).run(caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp)
249
+ })
250
+ }
251
+
252
+ function configureProviderCaps(provider: BudgetProvider, capsInput: BudgetCaps): void {
253
+ if (!isAllowedProvider(provider)) throw new TypeError('Invalid budget provider')
254
+ const caps = validateConfiguredCaps(capsInput)
255
+ inImmediateTransaction(() => {
256
+ const timestamp = now()
257
+ db.prepare(
258
+ `INSERT INTO provider_caps (provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
259
+ VALUES (?, ?, ?, ?)
260
+ ON CONFLICT(provider) DO UPDATE SET monthly_cap_micros = excluded.monthly_cap_micros,
261
+ per_decision_cap_micros = excluded.per_decision_cap_micros,
262
+ updated_at_ms = excluded.updated_at_ms`,
263
+ ).run(provider, caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp)
264
+ })
265
+ }
266
+
267
+ function configureModelCaps(
268
+ provider: BudgetProvider,
269
+ model: BudgetModel,
270
+ capsInput: BudgetCaps,
271
+ ): void {
272
+ if (!isAllowedProvider(provider)) throw new TypeError('Invalid budget provider')
273
+ if (!isAllowedModel(model)) throw new TypeError('Invalid budget model key')
274
+ const caps = validateConfiguredCaps(capsInput)
275
+ inImmediateTransaction(() => {
276
+ const timestamp = now()
277
+ db.prepare(
278
+ `INSERT INTO model_caps
279
+ (provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
280
+ VALUES (?, ?, ?, ?, ?)
281
+ ON CONFLICT(provider, model) DO UPDATE SET
282
+ monthly_cap_micros = excluded.monthly_cap_micros,
283
+ per_decision_cap_micros = excluded.per_decision_cap_micros,
284
+ updated_at_ms = excluded.updated_at_ms`,
285
+ ).run(provider, model, caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp)
286
+ })
287
+ }
288
+
289
+ function getActiveBudgetPeriod(): string | null {
290
+ const row = db.prepare('SELECT active_period_utc FROM ledger_state WHERE id = 1').get() as
291
+ | { active_period_utc: string | null }
292
+ | undefined
293
+ if (!row || row.active_period_utc === null) return null
294
+ if (!isValidPeriod(row.active_period_utc))
295
+ throw new Error('Invalid active period in budget ledger')
296
+ return row.active_period_utc
297
+ }
298
+
299
+ function confirmBudgetPeriod(
300
+ expectedCurrentPeriod: string | null,
301
+ targetPeriod: string,
302
+ ): PeriodConfirmationResult {
303
+ if (
304
+ (expectedCurrentPeriod !== null && !isValidPeriod(expectedCurrentPeriod)) ||
305
+ !isValidPeriod(targetPeriod)
306
+ ) {
307
+ return { status: 'denied', reason: 'invalid-period' }
308
+ }
309
+ return inImmediateTransaction(() => {
310
+ let wallPeriod: string
311
+ try {
312
+ wallPeriod = periodFor(now())
313
+ } catch {
314
+ return { status: 'denied', reason: 'clock-untrusted' }
315
+ }
316
+ const activePeriod = getActiveBudgetPeriod()
317
+ if (activePeriod !== expectedCurrentPeriod) {
318
+ return { status: 'denied', reason: 'stale-current' }
319
+ }
320
+ if (activePeriod === null) {
321
+ if (targetPeriod !== wallPeriod) {
322
+ return { status: 'denied', reason: 'wall-clock-mismatch' }
323
+ }
324
+ db.prepare(
325
+ `INSERT INTO ledger_state (id, active_period_utc) VALUES (1, ?)
326
+ ON CONFLICT(id) DO UPDATE SET active_period_utc = excluded.active_period_utc`,
327
+ ).run(targetPeriod)
328
+ return { status: 'confirmed', activePeriod: targetPeriod }
329
+ }
330
+ if (targetPeriod < activePeriod) return { status: 'denied', reason: 'backwards' }
331
+ if (targetPeriod === activePeriod) return { status: 'denied', reason: 'not-next-month' }
332
+ if (nextPeriod(activePeriod) !== targetPeriod) {
333
+ return { status: 'denied', reason: 'not-next-month' }
334
+ }
335
+ if (wallPeriod !== targetPeriod) {
336
+ return { status: 'denied', reason: 'wall-clock-mismatch' }
337
+ }
338
+ db.prepare('UPDATE ledger_state SET active_period_utc = ? WHERE id = 1').run(targetPeriod)
339
+ return { status: 'confirmed', activePeriod: targetPeriod }
340
+ })
341
+ }
342
+
343
+ function reserve(provider: BudgetProvider, model: BudgetModel): ReservationResult {
344
+ if (!isAllowedProvider(provider)) return { status: 'denied', reason: 'invalid-provider' }
345
+ if (!isAllowedModel(model)) return { status: 'denied', reason: 'invalid-model' }
346
+ return inImmediateTransaction(() => {
347
+ const admission = checkAdmission(provider, model)
348
+ if (admission.status === 'denied') return admission
349
+
350
+ const reservationId = reservationIdFactory()
351
+ if (typeof reservationId !== 'string' || !RESERVATION_ID.test(reservationId)) {
352
+ throw new Error('Invalid generated reservation identifier')
353
+ }
354
+ const duplicate = db
355
+ .prepare('SELECT 1 AS found FROM reservations WHERE id = ?')
356
+ .get(reservationId)
357
+ if (duplicate) return { status: 'denied', reason: 'duplicate-reservation-id' }
358
+ db.prepare(
359
+ `INSERT INTO reservations
360
+ (id, provider, model, period_utc, reserved_micros, actual_micros, state,
361
+ created_at_ms, updated_at_ms)
362
+ VALUES (?, ?, ?, ?, ?, NULL, 'pending', ?, ?)`,
363
+ ).run(
364
+ reservationId,
365
+ provider,
366
+ model,
367
+ admission.period,
368
+ admission.reservedMicros,
369
+ admission.timestamp,
370
+ admission.timestamp,
371
+ )
372
+ return {
373
+ status: 'reserved',
374
+ reservationId,
375
+ period: admission.period,
376
+ reservedMicros: admission.reservedMicros,
377
+ }
378
+ })
379
+ }
380
+
381
+ function canReserve(provider: BudgetProvider, model: BudgetModel): AdmissionCheckResult {
382
+ if (!isAllowedProvider(provider)) return { status: 'denied', reason: 'invalid-provider' }
383
+ if (!isAllowedModel(model)) return { status: 'denied', reason: 'invalid-model' }
384
+ return inImmediateTransaction(() => {
385
+ const admission = checkAdmission(provider, model)
386
+ return admission.status === 'denied' ? admission : { status: 'eligible' }
387
+ })
388
+ }
389
+
390
+ function checkAdmission(
391
+ provider: BudgetProvider,
392
+ model: BudgetModel,
393
+ ):
394
+ | { status: 'eligible'; period: string; reservedMicros: number; timestamp: number }
395
+ | { status: 'denied'; reason: ReservationDenialReason } {
396
+ let timestamp: number
397
+ let wallPeriod: string
398
+ try {
399
+ timestamp = now()
400
+ wallPeriod = periodFor(timestamp)
401
+ } catch {
402
+ return { status: 'denied', reason: 'clock-untrusted' }
403
+ }
404
+ const userCaps = readUserCaps()
405
+ const providerCaps = readProviderCaps(provider)
406
+ const modelCaps = readModelCaps(provider, model)
407
+ if (
408
+ !hasPositiveCaps(userCaps) ||
409
+ !hasPositiveCaps(providerCaps) ||
410
+ !hasPositiveCaps(modelCaps)
411
+ ) {
412
+ return { status: 'denied', reason: 'no-cap' }
413
+ }
414
+
415
+ const period = getActiveBudgetPeriod()
416
+ if (period === null) return { status: 'denied', reason: 'period-unconfirmed' }
417
+ if (wallPeriod !== period) return { status: 'denied', reason: 'period-mismatch' }
418
+
419
+ const reservedMicros = modelCaps.per_decision_cap_micros
420
+ if (
421
+ reservedMicros > userCaps.per_decision_cap_micros ||
422
+ reservedMicros > providerCaps.per_decision_cap_micros
423
+ ) {
424
+ return { status: 'denied', reason: 'per-decision-cap' }
425
+ }
426
+ if (isFrozen(period, provider, model)) return { status: 'denied', reason: 'frozen' }
427
+
428
+ if (
429
+ wouldExceed(sumReservations(period), reservedMicros, userCaps.monthly_cap_micros) ||
430
+ wouldExceed(
431
+ sumReservations(period, provider),
432
+ reservedMicros,
433
+ providerCaps.monthly_cap_micros,
434
+ ) ||
435
+ wouldExceed(
436
+ sumReservations(period, provider, model),
437
+ reservedMicros,
438
+ modelCaps.monthly_cap_micros,
439
+ )
440
+ ) {
441
+ return { status: 'denied', reason: 'monthly-cap' }
442
+ }
443
+ return { status: 'eligible', period, reservedMicros, timestamp }
444
+ }
445
+
446
+ function reconcileVerified(
447
+ reservationId: string,
448
+ evidence: VerifiedUsageEvidence,
449
+ ): ReconciliationResult {
450
+ if (typeof reservationId !== 'string' || !RESERVATION_ID.test(reservationId)) {
451
+ return { status: 'unknown' }
452
+ }
453
+ const verified = getVerifiedUsageEvidenceDetails(evidence)
454
+ if (
455
+ !verified ||
456
+ !Number.isSafeInteger(verified.actualCostMicros) ||
457
+ verified.actualCostMicros <= 0 ||
458
+ !isAllowedProvider(verified.provider) ||
459
+ !isAllowedModel(verified.model) ||
460
+ !isValidPeriod(verified.period)
461
+ ) {
462
+ return { status: 'unknown' }
463
+ }
464
+ return inImmediateTransaction(() => {
465
+ const row = db
466
+ .prepare(
467
+ `SELECT provider, model, period_utc, reserved_micros, state
468
+ FROM reservations WHERE id = ?`,
469
+ )
470
+ .get(reservationId) as
471
+ | {
472
+ provider: BudgetProvider
473
+ model: string
474
+ period_utc: string
475
+ reserved_micros: number
476
+ state: string
477
+ }
478
+ | undefined
479
+ if (!row) return { status: 'missing' }
480
+ if (row.state === 'reconciled') return { status: 'already-reconciled' }
481
+ if (row.state !== 'pending' && row.state !== 'uncertain') {
482
+ throw new Error('Invalid reservation state')
483
+ }
484
+ if (
485
+ verified.reservationId !== reservationId ||
486
+ verified.provider !== row.provider ||
487
+ verified.model !== row.model ||
488
+ verified.period !== row.period_utc
489
+ ) {
490
+ return { status: 'mismatch' }
491
+ }
492
+ const timestamp = now()
493
+ const update = db
494
+ .prepare(
495
+ `UPDATE reservations SET actual_micros = ?, state = 'reconciled', updated_at_ms = ?
496
+ WHERE id = ? AND state IN ('pending', 'uncertain')`,
497
+ )
498
+ .run(verified.actualCostMicros, timestamp, reservationId)
499
+ if (safeChangeCount(update.changes) !== 1) {
500
+ throw new Error('Reservation state changed unexpectedly')
501
+ }
502
+ const frozen = verified.actualCostMicros > row.reserved_micros
503
+ if (frozen) freezeBuckets(row.period_utc, row.provider, row.model, timestamp)
504
+ return { status: 'reconciled', actualCostMicros: verified.actualCostMicros, frozen }
505
+ })
506
+ }
507
+
508
+ function sumReservations(period: string, provider?: BudgetProvider, model?: string): number {
509
+ // Future-dated v2 holds may have resulted from an untrusted clock jump.
510
+ const where = ['period_utc >= ?']
511
+ const params: Array<string> = [period]
512
+ if (provider !== undefined) {
513
+ where.push('provider = ?')
514
+ params.push(provider)
515
+ }
516
+ if (model !== undefined) {
517
+ where.push('model = ?')
518
+ params.push(model)
519
+ }
520
+ const row = db
521
+ .prepare(
522
+ `SELECT COALESCE(SUM(CASE WHEN state = 'reconciled' THEN actual_micros ELSE reserved_micros END), 0) AS amount
523
+ FROM reservations WHERE ${where.join(' AND ')}`,
524
+ )
525
+ .get(...params) as { amount: number | bigint }
526
+ return safeMicrosTotal(row.amount)
527
+ }
528
+
529
+ function isFrozen(period: string, provider: BudgetProvider, model: string): boolean {
530
+ return Boolean(
531
+ db
532
+ .prepare(
533
+ `SELECT 1 AS found FROM budget_freezes
534
+ WHERE period_utc >= ? AND (
535
+ (scope = 'user' AND provider IS NULL AND model IS NULL) OR
536
+ (scope = 'provider' AND provider = ? AND model IS NULL) OR
537
+ (scope = 'model' AND provider = ? AND model = ?)
538
+ ) LIMIT 1`,
539
+ )
540
+ .get(period, provider, provider, model),
541
+ )
542
+ }
543
+
544
+ function freezeBuckets(
545
+ period: string,
546
+ provider: BudgetProvider,
547
+ model: string,
548
+ timestamp: number,
549
+ ): void {
550
+ const insertIfMissing = db.prepare(
551
+ `INSERT INTO budget_freezes (scope, provider, model, period_utc, reason, created_at_ms)
552
+ VALUES (?, ?, ?, ?, 'overrun', ?)
553
+ ON CONFLICT DO NOTHING`,
554
+ )
555
+ insertIfMissing.run('user', null, null, period, timestamp)
556
+ insertIfMissing.run('provider', provider, null, period, timestamp)
557
+ insertIfMissing.run('model', provider, model, period, timestamp)
558
+ }
559
+
560
+ function listUncertainReservations(): UncertainReservation[] {
561
+ const rows = db
562
+ .prepare(
563
+ `SELECT id, provider, model, period_utc, reserved_micros, state, created_at_ms, updated_at_ms
564
+ FROM reservations WHERE state IN ('pending', 'uncertain') ORDER BY created_at_ms, id`,
565
+ )
566
+ .all() as Array<{
567
+ id: string
568
+ provider: BudgetProvider
569
+ model: string
570
+ period_utc: string
571
+ reserved_micros: number
572
+ state: 'pending' | 'uncertain'
573
+ created_at_ms: number
574
+ updated_at_ms: number
575
+ }>
576
+ return rows.map((row) => ({
577
+ reservationId: row.id,
578
+ provider: row.provider,
579
+ model: row.model,
580
+ period: row.period_utc,
581
+ reservedMicros: row.reserved_micros,
582
+ state: row.state,
583
+ createdAtMs: row.created_at_ms,
584
+ updatedAtMs: row.updated_at_ms,
585
+ }))
586
+ }
587
+
588
+ function recoverPendingReservations(): number {
589
+ return inImmediateTransaction(() => {
590
+ const timestamp = now()
591
+ const result = db
592
+ .prepare(
593
+ `UPDATE reservations SET state = 'uncertain', updated_at_ms = ? WHERE state = 'pending'`,
594
+ )
595
+ .run(timestamp)
596
+ return safeChangeCount(result.changes)
597
+ })
598
+ }
599
+
600
+ function pruneCompletedPeriods(): number {
601
+ return inImmediateTransaction(() => {
602
+ let currentPeriod: string
603
+ try {
604
+ currentPeriod = periodFor(now())
605
+ } catch {
606
+ return 0
607
+ }
608
+ const activePeriod = getActiveBudgetPeriod()
609
+ if (activePeriod === null || currentPeriod !== activePeriod) return 0
610
+ const result = db
611
+ .prepare(
612
+ `DELETE FROM reservations AS completed
613
+ WHERE completed.period_utc < ? AND completed.state = 'reconciled'
614
+ AND NOT EXISTS (
615
+ SELECT 1 FROM reservations AS unresolved
616
+ WHERE unresolved.period_utc = completed.period_utc
617
+ AND unresolved.state IN ('pending', 'uncertain')
618
+ )`,
619
+ )
620
+ .run(activePeriod)
621
+ db.prepare(
622
+ `DELETE FROM budget_freezes
623
+ WHERE period_utc < ? AND NOT EXISTS (
624
+ SELECT 1 FROM reservations AS unresolved
625
+ WHERE unresolved.period_utc = budget_freezes.period_utc
626
+ AND unresolved.state IN ('pending', 'uncertain')
627
+ )`,
628
+ ).run(activePeriod)
629
+ return safeChangeCount(result.changes)
630
+ })
631
+ }
632
+
633
+ function readUserCaps(): StoredCaps | undefined {
634
+ return db
635
+ .prepare('SELECT monthly_cap_micros, per_decision_cap_micros FROM user_caps WHERE id = 1')
636
+ .get() as StoredCaps | undefined
637
+ }
638
+
639
+ function readProviderCaps(provider: BudgetProvider): StoredCaps | undefined {
640
+ return db
641
+ .prepare(
642
+ 'SELECT monthly_cap_micros, per_decision_cap_micros FROM provider_caps WHERE provider = ?',
643
+ )
644
+ .get(provider) as StoredCaps | undefined
645
+ }
646
+
647
+ function readModelCaps(provider: BudgetProvider, model: string): StoredCaps | undefined {
648
+ return db
649
+ .prepare(
650
+ `SELECT monthly_cap_micros, per_decision_cap_micros
651
+ FROM model_caps WHERE provider = ? AND model = ?`,
652
+ )
653
+ .get(provider, model) as StoredCaps | undefined
654
+ }
655
+
656
+ return {
657
+ configureUserCaps,
658
+ configureProviderCaps,
659
+ configureModelCaps,
660
+ confirmBudgetPeriod,
661
+ getActiveBudgetPeriod,
662
+ canReserve,
663
+ reserve,
664
+ reconcileVerified,
665
+ listUncertainReservations,
666
+ recoverPendingReservations,
667
+ pruneCompletedPeriods,
668
+ close: () => db.close(),
669
+ }
670
+ }
671
+
672
+ interface StoredCaps {
673
+ monthly_cap_micros: number
674
+ per_decision_cap_micros: number
675
+ }
676
+
677
+ function ensureSchema(db: DatabaseSync): void {
678
+ db.exec('BEGIN IMMEDIATE')
679
+ try {
680
+ const version = (db.prepare('PRAGMA user_version').get() as { user_version: number })
681
+ .user_version
682
+ const applicationId = (db.prepare('PRAGMA application_id').get() as { application_id: number })
683
+ .application_id
684
+ if (version === 0) {
685
+ const tables = db
686
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
687
+ .all()
688
+ if (applicationId !== 0 || tables.length !== 0) {
689
+ throw new Error('Refusing to initialize an unrecognized SQLite database')
690
+ }
691
+ createSchemaV3(db)
692
+ } else if (version === 1 && applicationId === APPLICATION_ID) {
693
+ migrateVersionOne(db)
694
+ migrateVersionTwoToThree(db)
695
+ } else if (version === VERSION_TWO && applicationId === APPLICATION_ID) {
696
+ migrateVersionTwoToThree(db)
697
+ } else if (version !== SCHEMA_VERSION || applicationId !== APPLICATION_ID) {
698
+ throw new Error('Unsupported or incompatible local decision budget database schema')
699
+ }
700
+ db.exec('COMMIT')
701
+ } catch (error) {
702
+ try {
703
+ db.exec('ROLLBACK')
704
+ } catch {
705
+ // Preserve schema/migration error.
706
+ }
707
+ throw error
708
+ }
709
+ }
710
+
711
+ function createSchemaV3(db: DatabaseSync): void {
712
+ db.exec(`
713
+ CREATE TABLE user_caps (
714
+ id INTEGER PRIMARY KEY CHECK (id = 1),
715
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
716
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
717
+ updated_at_ms INTEGER NOT NULL
718
+ ) STRICT;
719
+ CREATE TABLE provider_caps (
720
+ provider TEXT PRIMARY KEY NOT NULL,
721
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
722
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
723
+ updated_at_ms INTEGER NOT NULL
724
+ ) STRICT;
725
+ CREATE TABLE model_caps (
726
+ provider TEXT NOT NULL,
727
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
728
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
729
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
730
+ updated_at_ms INTEGER NOT NULL,
731
+ PRIMARY KEY (provider, model)
732
+ ) STRICT;
733
+ CREATE TABLE reservations (
734
+ id TEXT PRIMARY KEY NOT NULL,
735
+ provider TEXT NOT NULL,
736
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
737
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
738
+ reserved_micros INTEGER NOT NULL CHECK (reserved_micros > 0),
739
+ actual_micros INTEGER CHECK (actual_micros IS NULL OR actual_micros >= 0),
740
+ state TEXT NOT NULL CHECK (state IN ('pending', 'uncertain', 'reconciled')),
741
+ created_at_ms INTEGER NOT NULL,
742
+ updated_at_ms INTEGER NOT NULL,
743
+ CHECK ((state = 'reconciled' AND actual_micros IS NOT NULL) OR
744
+ (state IN ('pending', 'uncertain') AND actual_micros IS NULL))
745
+ ) STRICT;
746
+ CREATE INDEX reservations_provider_period_idx ON reservations (provider, period_utc, state);
747
+ CREATE INDEX reservations_model_period_idx
748
+ ON reservations (provider, model, period_utc, state);
749
+ CREATE INDEX reservations_period_state_idx ON reservations (period_utc, state);
750
+ CREATE INDEX reservations_state_created_idx ON reservations (state, created_at_ms, id);
751
+ CREATE TABLE ledger_state (
752
+ id INTEGER PRIMARY KEY CHECK (id = 1),
753
+ active_period_utc TEXT CHECK (active_period_utc IS NULL OR length(active_period_utc) = 7)
754
+ ) STRICT;
755
+ CREATE TABLE budget_freezes (
756
+ id INTEGER PRIMARY KEY,
757
+ scope TEXT NOT NULL CHECK (scope IN ('user', 'provider', 'model')),
758
+ provider TEXT,
759
+ model TEXT,
760
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
761
+ reason TEXT NOT NULL CHECK (reason = 'overrun'),
762
+ created_at_ms INTEGER NOT NULL,
763
+ CHECK ((scope = 'user' AND provider IS NULL AND model IS NULL) OR
764
+ (scope = 'provider' AND provider IS NOT NULL AND model IS NULL) OR
765
+ (scope = 'model' AND provider IS NOT NULL AND model IS NOT NULL))
766
+ ) STRICT;
767
+ CREATE UNIQUE INDEX budget_freezes_unique_idx
768
+ ON budget_freezes (scope, ifnull(provider, ''), ifnull(model, ''), period_utc);
769
+ CREATE INDEX budget_freezes_period_scope_idx
770
+ ON budget_freezes (period_utc, scope, provider, model);
771
+ PRAGMA application_id = ${APPLICATION_ID};
772
+ PRAGMA user_version = ${SCHEMA_VERSION};
773
+ `)
774
+ }
775
+
776
+ function migrateVersionTwoToThree(db: DatabaseSync): void {
777
+ validateVersionTwoSchema(db)
778
+ db.exec(`
779
+ UPDATE reservations SET
780
+ reserved_micros = CASE
781
+ WHEN actual_micros > reserved_micros THEN actual_micros
782
+ ELSE reserved_micros
783
+ END,
784
+ state = 'uncertain', actual_micros = NULL
785
+ WHERE state = 'reconciled';
786
+ ALTER TABLE ledger_state RENAME TO ledger_state_v2;
787
+ CREATE TABLE ledger_state (
788
+ id INTEGER PRIMARY KEY CHECK (id = 1),
789
+ active_period_utc TEXT CHECK (active_period_utc IS NULL OR length(active_period_utc) = 7)
790
+ ) STRICT;
791
+ INSERT INTO ledger_state (id, active_period_utc)
792
+ SELECT id, NULL FROM ledger_state_v2;
793
+ DROP TABLE ledger_state_v2;
794
+ PRAGMA user_version = ${SCHEMA_VERSION};
795
+ `)
796
+ }
797
+
798
+ function migrateVersionOne(db: DatabaseSync): void {
799
+ validateVersionOneSchema(db)
800
+ const providers = db
801
+ .prepare('SELECT DISTINCT provider FROM reservations UNION SELECT provider FROM provider_caps')
802
+ .all() as Array<{ provider: string }>
803
+ if (providers.some(({ provider }) => provider !== 'openai-decisions' && provider !== 'jev')) {
804
+ throw new Error('Refusing to migrate an unsupported version-one provider')
805
+ }
806
+ db.exec(`
807
+ ALTER TABLE reservations
808
+ ADD COLUMN model TEXT NOT NULL DEFAULT 'legacy-unknown'
809
+ CHECK (length(model) BETWEEN 1 AND 128);
810
+ UPDATE reservations SET model = 'gpt-6-luna' WHERE provider = 'openai-decisions';
811
+ UPDATE reservations SET provider = 'typesafe-jev', model = 'jev-1.14.0' WHERE provider = 'jev';
812
+ UPDATE provider_caps SET provider = 'typesafe-jev' WHERE provider = 'jev';
813
+ CREATE TABLE user_caps (
814
+ id INTEGER PRIMARY KEY CHECK (id = 1),
815
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
816
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
817
+ updated_at_ms INTEGER NOT NULL
818
+ ) STRICT;
819
+ CREATE TABLE model_caps (
820
+ provider TEXT NOT NULL,
821
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
822
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
823
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
824
+ updated_at_ms INTEGER NOT NULL,
825
+ PRIMARY KEY (provider, model)
826
+ ) STRICT;
827
+ CREATE INDEX reservations_model_period_idx
828
+ ON reservations (provider, model, period_utc, state);
829
+ CREATE INDEX reservations_state_created_idx ON reservations (state, created_at_ms, id);
830
+ CREATE TABLE budget_freezes (
831
+ id INTEGER PRIMARY KEY,
832
+ scope TEXT NOT NULL CHECK (scope IN ('user', 'provider', 'model')),
833
+ provider TEXT,
834
+ model TEXT,
835
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
836
+ reason TEXT NOT NULL CHECK (reason = 'overrun'),
837
+ created_at_ms INTEGER NOT NULL,
838
+ CHECK ((scope = 'user' AND provider IS NULL AND model IS NULL) OR
839
+ (scope = 'provider' AND provider IS NOT NULL AND model IS NULL) OR
840
+ (scope = 'model' AND provider IS NOT NULL AND model IS NOT NULL))
841
+ ) STRICT;
842
+ CREATE UNIQUE INDEX budget_freezes_unique_idx
843
+ ON budget_freezes (scope, ifnull(provider, ''), ifnull(model, ''), period_utc);
844
+ CREATE INDEX budget_freezes_period_scope_idx
845
+ ON budget_freezes (period_utc, scope, provider, model);
846
+ PRAGMA user_version = ${VERSION_TWO};
847
+ `)
848
+ }
849
+
850
+ function validateVersionOneSchema(db: DatabaseSync): void {
851
+ db.prepare(
852
+ `SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
853
+ FROM provider_caps LIMIT 0`,
854
+ )
855
+ db.prepare(
856
+ `SELECT id, provider, period_utc, reserved_micros, actual_micros, state,
857
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
858
+ )
859
+ db.prepare('SELECT id, highest_period_utc, last_seen_ms FROM ledger_state LIMIT 0')
860
+ }
861
+
862
+ function validateVersionTwoSchema(db: DatabaseSync): void {
863
+ db.prepare(
864
+ 'SELECT id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM user_caps LIMIT 0',
865
+ )
866
+ db.prepare(
867
+ 'SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM provider_caps LIMIT 0',
868
+ )
869
+ db.prepare(
870
+ 'SELECT provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM model_caps LIMIT 0',
871
+ )
872
+ db.prepare(
873
+ `SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
874
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
875
+ )
876
+ db.prepare('SELECT id, highest_period_utc, last_seen_ms FROM ledger_state LIMIT 0')
877
+ db.prepare(
878
+ 'SELECT id, scope, provider, model, period_utc, reason, created_at_ms FROM budget_freezes LIMIT 0',
879
+ )
880
+ }
881
+
882
+ function validateSchema(db: DatabaseSync): void {
883
+ db.prepare(
884
+ `SELECT id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM user_caps LIMIT 0`,
885
+ )
886
+ db.prepare(
887
+ `SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
888
+ FROM provider_caps LIMIT 0`,
889
+ )
890
+ db.prepare(
891
+ `SELECT provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
892
+ FROM model_caps LIMIT 0`,
893
+ )
894
+ db.prepare(
895
+ `SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
896
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
897
+ )
898
+ db.prepare('SELECT id, active_period_utc FROM ledger_state LIMIT 0')
899
+ db.prepare(
900
+ `SELECT id, scope, provider, model, period_utc, reason, created_at_ms
901
+ FROM budget_freezes LIMIT 0`,
902
+ )
903
+ }
904
+
905
+ function validateConfiguredCaps(value: unknown): BudgetCaps {
906
+ if (!isPlainRecord(value)) throw new TypeError('Caps must be an object')
907
+ const keys = Object.keys(value).sort()
908
+ if (keys.join(',') !== 'monthlyCapMicros,perDecisionCapMicros') {
909
+ throw new TypeError('Caps must contain only monthly and per-decision values')
910
+ }
911
+ if (!isValidCap(value.monthlyCapMicros) || !isValidCap(value.perDecisionCapMicros)) {
912
+ throw new TypeError('Caps must be non-negative safe integer USD micros')
913
+ }
914
+ return {
915
+ monthlyCapMicros: value.monthlyCapMicros,
916
+ perDecisionCapMicros: value.perDecisionCapMicros,
917
+ }
918
+ }
919
+
920
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
921
+ try {
922
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value))
923
+ } catch {
924
+ return false
925
+ }
926
+ }
927
+
928
+ function isAllowedProvider(provider: unknown): provider is BudgetProvider {
929
+ return typeof provider === 'string' && ALLOWED_PROVIDERS.has(provider as BudgetProvider)
930
+ }
931
+
932
+ function isAllowedModel(model: unknown): model is BudgetModel {
933
+ return typeof model === 'string' && MODEL_KEY.test(model)
934
+ }
935
+
936
+ function isValidCap(value: unknown): value is number {
937
+ return Number.isSafeInteger(value) && (value as number) >= 0
938
+ }
939
+
940
+ function hasPositiveCaps(value: StoredCaps | undefined): value is StoredCaps {
941
+ return Boolean(
942
+ value &&
943
+ isValidCap(value.monthly_cap_micros) &&
944
+ value.monthly_cap_micros > 0 &&
945
+ isValidCap(value.per_decision_cap_micros) &&
946
+ value.per_decision_cap_micros > 0,
947
+ )
948
+ }
949
+
950
+ function wouldExceed(current: number, additional: number, cap: number): boolean {
951
+ return current > cap || additional > cap - current
952
+ }
953
+
954
+ function safeMicrosTotal(value: number | bigint): number {
955
+ if (typeof value === 'bigint') {
956
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < 0n) {
957
+ throw new Error('Invalid spend total in budget ledger')
958
+ }
959
+ return Number(value)
960
+ }
961
+ if (!Number.isSafeInteger(value) || value < 0) {
962
+ throw new Error('Invalid spend total in budget ledger')
963
+ }
964
+ return value
965
+ }
966
+
967
+ function periodFor(timestamp: number): string {
968
+ const period = new Date(timestamp).toISOString().slice(0, 7)
969
+ if (!isValidPeriod(period)) throw new Error('Invalid UTC accounting period')
970
+ return period
971
+ }
972
+
973
+ function isValidPeriod(value: string): boolean {
974
+ return /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
975
+ }
976
+
977
+ function nextPeriod(period: string): string | null {
978
+ if (!isValidPeriod(period)) return null
979
+ let year = Number(period.slice(0, 4))
980
+ let month = Number(period.slice(5, 7)) + 1
981
+ if (month === 13) {
982
+ year += 1
983
+ month = 1
984
+ }
985
+ if (year > 9999) return null
986
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}`
987
+ }
988
+
989
+ function safeChangeCount(value: number | bigint): number {
990
+ const count = Number(value)
991
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid SQLite change count')
992
+ return count
993
+ }
994
+
995
+ function ensureTrustedDirectoryChain(directoryPath: string): void {
996
+ if (process.platform === 'win32' || typeof process.getuid !== 'function') {
997
+ throw new Error('Secure budget-ledger path validation is unavailable on this platform')
998
+ }
999
+ const uid = process.getuid()
1000
+ const absolute = resolve(directoryPath)
1001
+ const root = parse(absolute).root
1002
+ let current = root
1003
+ validateDirectoryTrust(lstatSync(current), uid, current === absolute)
1004
+
1005
+ for (const component of absolute.slice(root.length).split(sep).filter(Boolean)) {
1006
+ current = join(current, component)
1007
+ try {
1008
+ lstatSync(current)
1009
+ } catch (error) {
1010
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
1011
+ try {
1012
+ mkdirSync(current, { mode: 0o700 })
1013
+ } catch (mkdirError) {
1014
+ if ((mkdirError as NodeJS.ErrnoException).code !== 'EEXIST') throw mkdirError
1015
+ }
1016
+ }
1017
+ const stat = lstatSync(current)
1018
+ const isFinalDirectory = current === absolute
1019
+ validateDirectoryTrust(stat, uid, isFinalDirectory)
1020
+ if (isFinalDirectory) {
1021
+ chmodSync(current, 0o700)
1022
+ validateDirectoryTrust(lstatSync(current), uid, true)
1023
+ }
1024
+ }
1025
+ }
1026
+
1027
+ function validateDirectoryTrust(stat: Stats, uid: number, isFinalDirectory: boolean): void {
1028
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
1029
+ throw new Error('Budget ledger path contains a non-directory or symlink ancestor')
1030
+ }
1031
+ if (stat.uid !== uid && stat.uid !== 0) {
1032
+ throw new Error('Budget ledger path contains an untrusted owner')
1033
+ }
1034
+ if (isFinalDirectory && stat.uid !== uid) {
1035
+ throw new Error('Budget ledger directory must be owned by the current user')
1036
+ }
1037
+ const mode = stat.mode & 0o7777
1038
+ const writableByOthers = (mode & 0o022) !== 0
1039
+ const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
1040
+ if (writableByOthers && !rootStickyDirectory) {
1041
+ throw new Error('Budget ledger path contains a group/other-writable directory')
1042
+ }
1043
+ }