pantheon-opencode 1.6.2-beta.4 โ†’ 1.6.2-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +174 -3
  3. package/bin/pantheon-init.mjs +6 -1
  4. package/package.json +1 -1
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +3 -3
  8. package/scripts/decision-router-v2-budget.mjs +218 -0
  9. package/scripts/decision-router-v2-egress.mjs +272 -0
  10. package/scripts/decision-router.mjs +268 -46
  11. package/scripts/docs-check-changelog.mjs +5 -3
  12. package/scripts/install/decision-layer-preview.mjs +376 -0
  13. package/scripts/install/decision-router-config.mjs +158 -11
  14. package/scripts/mcp_resources.py +11 -9
  15. package/scripts/release-notes.mjs +30 -7
  16. package/scripts/versioning.mjs +41 -5
  17. package/src/mcp/eval_store.py +11 -4
  18. package/src/mcp/mcp_resources.py +11 -9
  19. package/src/mcp/memory_mcp.py +293 -150
  20. package/src/pantheon/local-decision-prompt.ts +181 -36
  21. package/src/pantheon/local-decision-skills.ts +115 -5
  22. package/src/pantheon/local-decision-tool.ts +35 -1
  23. package/src/pantheon/v2-decision-budget.ts +456 -0
  24. package/src/pantheon/v2-decision-contracts.ts +300 -0
  25. package/src/pantheon/v2-decision-egress.ts +203 -0
  26. package/src/pantheon/v2-decision-events.ts +180 -0
  27. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  28. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  29. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  30. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  31. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  32. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  33. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  34. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  35. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  36. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  37. package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
  38. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  39. package/src/pantheon/v2-decision-points.ts +242 -0
  40. package/src/pantheon/v2-decision-policy.ts +166 -0
  41. package/src/pantheon/v2-decision-premises.ts +146 -0
  42. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  43. package/src/pantheon/v2-decision-rank.ts +91 -0
  44. package/src/pantheon/v2-decision-registry.ts +391 -0
  45. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  46. package/src/pantheon/v2-decision-shadow.ts +123 -0
  47. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  48. package/src/pantheon/v2-decision-verify.ts +51 -0
  49. package/src/pantheon/v2-tools.ts +21 -2
  50. package/src/plugin-v2.ts +305 -3
  51. package/src/plugins/tui/dist/tui-v2.js +3 -3
  52. package/src/plugins/tui/dist/tui.js +1 -1
  53. package/src/plugins/tui/package-lock.json +2 -2
  54. package/src/plugins/tui/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -10,6 +10,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
10
10
  <!-- Add new changes here. Running `node scripts/versioning.mjs apply` will
11
11
  move this section to a versioned entry and reset the template below. -->
12
12
 
13
+ ## [v1.6.2-beta.5] - 2026-11-01
14
+
15
+ ## ๐Ÿ†• What's New
16
+ - **routing** โ€” wire decision points to their declared host surfaces in shadow (#304)
17
+ - **routing** โ€” add V2 decision layer with measured-shape adapters (#303)
18
+
19
+ ## ๐Ÿž Fixed
20
+ - **mcp** โ€” harden memory and resource MCP reliability (#306)
13
21
  ## [v1.6.2-beta.4] - 2026-10-31
14
22
 
15
23
  ### Added
package/README.md CHANGED
@@ -261,12 +261,167 @@ runtime routing. `npx pantheon-opencode decision-router ...` manages user-level
261
261
  enablement, selection, candidates, consent, caps, and period confirmation. The
262
262
  separate SQLite ledger has no default caps. Caps limit local admission but are not
263
263
  invoice guarantees. Installation does not contact a model provider or inspect
264
- credentials. The published CLI imports a committed ESM ledger bundle:
265
- `npm run build:decision-router` regenerates it and `npm run check:decision-router`
266
- (the `prepack`/`prepublishOnly` drift gate) fails when it is stale. The
264
+ credentials. The published CLI imports committed ESM bundles:
265
+ `npm run build:decision-router` regenerates them and `npm run check:decision-router`
266
+ (the `prepack`/`prepublishOnly` drift gate) fails when any is stale. The
267
267
  `pantheon-opencode/local-decision-router` subpath itself is TypeScript source, so
268
268
  it loads only in the host runtime or under a transpiler such as `tsx`.
269
269
 
270
+ Decision-layer commands are separated by effect. `decision-router help`,
271
+ `status`, `preview` and `holds` are read-only: they never create, migrate, or
272
+ write the config or the SQLite ledger, and neither does `setup` without
273
+ `--apply`. `select` records a preference and can never enable anything โ€” moving
274
+ the target also revokes consent recorded for the previous one. `setup` prints a
275
+ **computed diff of the target artifacts** (snapshot + SHA-256 per file, compared
276
+ against the exact bytes the writer would produce); `setup --apply` is the form
277
+ that writes, and a second run reports `0 create ยท 0 update`. It is deliberately
278
+ not the installer's "Change plan", which announced 112 creates for an apply that
279
+ created nothing. `setup --target <dir>` also reconciles the
280
+ `.pantheon/install-state.json` provider/consent record with the user-level config;
281
+ that record is derived from the config and never asserts consent the config lacks.
282
+ Neither path creates a backup: installer backup sets accumulate once per
283
+ application and contain credential-bearing material (API keys/tokens), so no
284
+ extra copy is made. Installer file-ownership tracking is partial and asymmetric โ€”
285
+ `file_inventory` indexes 53 PROJECT artifacts and no GLOBAL ones (F-15); the
286
+ 106-project / 107-global denominators are derived from the 213-artifact total and
287
+ are not separately indexed โ€” so this preview compares the decision-layer
288
+ artifacts it owns, not "everything the installer touched".
289
+
290
+ Provider egress remains opt-in with the default `off`; no command in this layer
291
+ can switch it on without enablement, recorded consent, one cap- and
292
+ period-eligible candidate and a non-denying host gate. The fixed OpenAI/TypeSafe
293
+ endpoints are retained inert and are documented as **unwired**; this statement is
294
+ about wiring, not about removing any transport. Each endpoint carries its own
295
+ explicit wire status, and a test fails when a declared endpoint is neither
296
+ asserted `unwired` nor exercised by a real path. Verification covers **only the
297
+ paths a probe exercised โ€” none** โ€” so nothing here is evidence about network
298
+ absence on an unexercised path; `permission.evaluate.egress` is likewise
299
+ unreachable in the probed host (a tool declaring it is never advertised to the
300
+ provider). Measured surface coverage is
301
+ reported honestly rather than implied: P7 runs behind `PANTHEON_V2_P7_LOOP` with
302
+ an **advisory** execution cap (never described as enforcement), P2 is
303
+ **advisory-only** (an empirical no-op on the default path), P9 was measured on
304
+ top-level **and child** sessions with `reason:"overflow"` still unmeasured, and
305
+ P8 is **advisory: not activatable by measurement** โ€” its declared rules match no
306
+ delivered permission payload, so it narrows nothing (PROBE-F).
307
+
308
+ ### The V2 decision layer is declared in full and wired in part
309
+
310
+ The V2 decision layer declares eleven integration points (P1โ€“P11) over three
311
+ decision primitives โ€” `ask`, `rank`, and `verify` โ€” and a deterministic policy
312
+ that decides which point may run. **Seven of the eleven have a production call
313
+ site: two behind flags that are off by default, five in shadow.**
314
+
315
+ - **P7 (loop)** is wired to `session.execution.succeeded` behind
316
+ `PANTHEON_V2_P7_LOOP`, which is off. It writes each observation to an
317
+ in-memory, bounded telemetry collector that the plugin never reads back and
318
+ exposes only to tests, so "records" here does not mean an operator-visible log.
319
+ - **P8 (guardrail)** is wired to `permission.evaluate` behind
320
+ `PANTHEON_V2_P8_GUARDRAIL`, which is off. C8 is closed **by measurement**, and
321
+ the measurement is negative: PROBE-F delivered 24 real `permission.evaluate`
322
+ events and every declared rule matched none of them (a valid `action` token and
323
+ a top-level `sessionID` are always present), the host resolves an unrecognised
324
+ effect as `ask` and proceeds, and `permission.evaluate.egress` is unreachable
325
+ (a tool declaring it is never advertised to the provider). As declared, P8 does
326
+ not narrow. The flag stays off.
327
+ - **P1 and P2** are registered on `session.hook('prompt')` in **shadow**. They
328
+ observe the same admission payload through a projection that carries only
329
+ `prompt.agents` and `prompt.skills`: no text, no file bytes, no metadata, no
330
+ mutation, no throw. Every record says `effect: none` and goes to an in-memory,
331
+ bounded collector the plugin never reads back (test-visible only).
332
+ - **P3** is wired at its declared `tool.invoke` in **shadow**: the
333
+ `pantheon_local_decision` tool hands the adapter its own input, whose schema
334
+ requires `complexity` and `gateStatus`. It records a classification when the
335
+ tool is invoked โ€” never a permanent `complexity.invalid` refusal from a payload
336
+ that cannot carry the vector โ€” and applies nothing.
337
+ - **P9** is wired at its declared `session.hook('compaction')` in **shadow**, on
338
+ the carrier that was actually measured: the top-level `sessionID` and the
339
+ `system` part array. It records the decision key and the payload shape and
340
+ pushes nothing โ€” the injected compaction context is unchanged โ€” and a payload
341
+ whose only session id is a nested `session.id` (a field the 2.2.5 host never
342
+ sends) produces no decision at all. The same shape was measured in a **child**
343
+ session (PROBE-G: hook fires 3/3, child `sessionID` at top level, `system` an
344
+ array of 4), so no child-specific branch exists. `reason:"overflow"` was not
345
+ inducible and is not designed for. No measured surface carries the memory
346
+ candidate list it would retain or discard, so its record states that absence
347
+ rather than a retention or a priority.
348
+ - **P11** is wired inside `ctx.tool.transform` in **shadow**: it reads the draft
349
+ the host hands that callback and calls none of its mutators. Shadow has no
350
+ responder, so it records the validated `choice` question over the draft ids โ€”
351
+ never a selection.
352
+
353
+ **The other four โ€” P4, P5, P6 and P10 โ€” are library code with no production call
354
+ site.** Nothing constructs or registers them outside the per-point test suites โ€”
355
+ the offline harness imports no adapter module. P6 and P10 declared the prompt
356
+ hook, but that payload never carries council candidates or counsellor claims, so
357
+ they stay unwired instead of recording a refusal from a surface that cannot feed
358
+ them. P4 ranks a memory candidate array and the measured `context` payload
359
+ carries `system` text parts, not candidates; P5 verifies a declared
360
+ `{ requirements, responses }` pair and the `execute.after` event carries
361
+ neither. On a host they do not read the turn, record no telemetry and have no
362
+ switch to turn off, because nothing registers them.
363
+
364
+ "Shadow" therefore means no behavioural change, not a claim of effect: the five
365
+ shadow points read a narrow slice of their surface and decide nothing from it,
366
+ and the two flag-gated points are off. No activation flag is set in a default
367
+ install.
368
+
369
+ The CLI separates effects: `npx pantheon-opencode decision-router help`, `status`,
370
+ `preview` and `holds` never write, `setup` writes only under `--apply`, `preview`
371
+ is an alias of `setup`, and `select` records a preference without enabling
372
+ anything. Egress stays opt-in and off, and only the explicit `enable`, `consent`,
373
+ `caps` and `period` actions can change that; no read-only command can.
374
+
375
+ What the layer does **not** do today, stated as measured rather than implied:
376
+
377
+ - **P2 (skills) is advisory-only and does not filter.** It is an empirical no-op
378
+ on the default path, because the host sends `prompt.skills` absent. Effective
379
+ project-skill filtering was cancelled by measurement, not emulated, and no
380
+ token reduction is claimed.
381
+ - **P7 (loop) is behind `PANTHEON_V2_P7_LOOP`, off by default, and does not
382
+ enforce loop limits.** It counts executions and writes an `effect: none`
383
+ observation to an in-memory collector that nothing reads back. Its
384
+ 12-execution cap is **advisory**: no measured host surface signals a new user
385
+ turn, so nothing is claimed to reset the streak.
386
+ - **P9 (compaction) is measured in top-level and child sessions.** PROBE-G fired
387
+ the hook in a real child 3/3 with the child's `sessionID` at top level and the
388
+ same payload shape. `reason: "overflow"` was **not inducible** in 6 error
389
+ shapes โ€” the host retried and completed, and the one failure-recovery
390
+ compaction was persisted as `reason:"auto"` โ€” so that path stays unmeasured;
391
+ the checkpoint reinjection inside a child was not exercised, and the `messages`
392
+ channel remains UNKNOWN. The memory candidate list is not available on any
393
+ measured surface, so the wired P9 record names that absence and claims no
394
+ retention or priority.
395
+ - **P8 (guardrail) is not activatable by measurement.** PROBE-F delivered 24 real
396
+ `permission.evaluate` events: the payload is
397
+ `["sessionID","agent","action","resources","metadata","source","effect"]` with
398
+ `effect` an own writable data property pre-populated by the host, and a written
399
+ `deny` **is** honoured. But neither declared rule can match a delivered payload
400
+ (valid `action` token, `sessionID` always present), the host lets an
401
+ unrecognised effect resolve as `ask` and execute, and
402
+ `permission.evaluate.egress` is unreachable โ€” so the current rule set matches
403
+ nothing and does not narrow. The point is recorded as **advisory**, not as
404
+ awaiting review, and the inertness is the measured verdict rather than a design
405
+ claim. `execute.before` remains the only hard barrier.
406
+ - **The embeddings-versus-BM25 comparison has not been run.** The environment is
407
+ offline with no embedding model available, so BM25 remains the baseline and no
408
+ gain or loss in retrieval or tokens is claimed in either direction.
409
+
410
+ Calibration that was run: the offline harness
411
+ (`npx tsx tests/pantheon/v2-decision-harness.test.ts`) executed 264 synthetic
412
+ cases โ€” 132 normal, 66 refusal, 66 adversarial โ€” across the eleven points, with
413
+ 24 cases per point and the suite asserting at least 20 cases, 5 refusals and 5
414
+ adversarial cases per point. All 264 cases passed on 2026-10-31. This harness is
415
+ the only place all eleven points are exercised in one run, but it imports no
416
+ adapter module: it iterates the registry and exercises the shared primitives,
417
+ while the adapters are covered by their per-point suites
418
+ (`v2-decision-p1.test.ts` โ€ฆ `v2-decision-p11.test.ts`). Passing it says nothing
419
+ about whether a point is registered in a host.
420
+ The harness measures contracts (admission, refusal, shadow no-op, telemetry
421
+ redaction, offline discipline, registry integrity), **not** token use, quality,
422
+ latency or any effect inside a host turn. Numbers and unmeasured surfaces are
423
+ recorded in the [router reference](docs/reference/local-decision-router.md).
424
+
270
425
  ## Documentation
271
426
 
272
427
  | Start here | Go deeper |
@@ -280,12 +435,28 @@ it loads only in the host runtime or under a transpiler such as `tsx`.
280
435
  | [Model Routing](docs/reference/model-routing.md) | [Local Decision Router](docs/reference/local-decision-router.md) ยท [Offline Evaluation Protocol](docs/reference/offline-evaluation.md) ยท [Env Vars](docs/reference/env-vars.md) ยท [Code Mode](docs/reference/code-mode.md) |
281
436
  | [Contributing](CONTRIBUTING.md) | [Roadmap](ROADMAP.md) ยท [Changelog](CHANGELOG.md) |
282
437
 
438
+ Memory writes through `pantheon-memory` are serialized, and failed writes are
439
+ reported as failures rather than as stored entries. Eval resources wait for
440
+ SQLite locks and close their connections; project-specific resources resolve
441
+ the current project root per request while preserving the trusted
442
+ `PANTHEON_HOME` fallback. See [Memory](docs/MEMORY.md) for store separation and
443
+ [MCP tools](docs/mcp-tools.md) for details.
444
+
283
445
  The release install gate's tool canary loads the installed tarball's V2 plugin
284
446
  entry under OpenCode 2.0.30 and verifies `hashline_edit` registration, Code Mode
285
447
  visibility, and a bounded edit in an isolated project. It does not prove npm
286
448
  publication or compatibility with untested host versions; details are in the
287
449
  [release process](docs/RELEASING.md).
288
450
 
451
+ Generate beta release notes from commits since the latest prior beta tag with
452
+ `node scripts/versioning.mjs apply --beta --notes`. See the [release
453
+ procedure](docs/RELEASING.md) for details.
454
+ After the version bump, verify and rebuild the TUI workspace from the repository
455
+ root with `npm run typecheck --workspace=src/plugins/tui` and
456
+ `npm run build --workspace=src/plugins/tui`.
457
+ The maintainer-only `release` scope is excluded from public notes and their
458
+ Closed Issues references; see the [release-notes policy](docs/RELEASING.md#release-notes).
459
+
289
460
  ## Status
290
461
 
291
462
  The manifests in this checkout express the version being prepared, not a
@@ -84,7 +84,12 @@ function printUsage() {
84
84
  ' npx pantheon-opencode init --merge-dev-config <path> # Merge a dev config (off by default)',
85
85
  )
86
86
  console.log(' npx pantheon-opencode set-tier <name> # Set active model preset (global)')
87
- console.log(' npx pantheon-opencode decision-router status|select|enable|consent|caps|period')
87
+ console.log(
88
+ ' npx pantheon-opencode decision-router help|status|setup|preview|holds # read-only',
89
+ )
90
+ console.log(
91
+ ' npx pantheon-opencode decision-router select|enable|consent|caps|period # explicit actions',
92
+ )
88
93
  console.log(
89
94
  ' npx pantheon-opencode update [--stable] # Update package + re-run init (default: beta channel)',
90
95
  )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pantheon-opencode",
3
- "version": "1.6.2-beta.4",
3
+ "version": "1.6.2-beta.5",
4
4
  "description": "Multi-agent orchestration for OpenCode โ€” 14 specialized agents, TDD, Themis review gates.",
5
5
  "type": "module",
6
6
  "workspaces": [
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pantheon",
3
3
  "publisher": "ils15",
4
- "version": "1.6.2-beta.4",
4
+ "version": "1.6.2-beta.5",
5
5
  "displayName": "Pantheon",
6
6
  "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 20 skills, and OpenCode support.",
7
7
  "agents": "./src/agents",
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend"
4
4
 
5
5
  [project]
6
6
  name = "pantheon"
7
- version = "1.6.2-beta.4"
7
+ version = "1.6.2-beta.5"
8
8
  description = "Multi-agent orchestration framework"
9
9
  requires-python = ">=3.11"
10
10
  # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those
@@ -1,6 +1,6 @@
1
- // Generated by scripts/build-decision-router.mjs from src/pantheon/local-decision-budget.ts.
2
- // The published CLI cannot import TypeScript from node_modules, so it imports
3
- // this prebuilt ESM bundle instead. Do not edit: run `npm run build:decision-router`.
1
+ // Generated by scripts/build-decision-router.mjs. The published CLI cannot
2
+ // import TypeScript from node_modules, so it imports this prebuilt ESM bundle
3
+ // instead. Do not edit: run `npm run build:decision-router`.
4
4
 
5
5
  // src/pantheon/local-decision-budget.ts
6
6
  import { randomUUID } from "node:crypto";
@@ -0,0 +1,218 @@
1
+ // Generated by scripts/build-decision-router.mjs. The published CLI cannot
2
+ // import TypeScript from node_modules, so it imports this prebuilt ESM bundle
3
+ // instead. Do not edit: run `npm run build:decision-router`.
4
+
5
+ // src/pantheon/v2-decision-budget.ts
6
+ import { lstatSync } from "node:fs";
7
+ import { DatabaseSync } from "node:sqlite";
8
+ function isPositiveCaps(value) {
9
+ return value !== void 0 && Number.isSafeInteger(value.monthlyCapMicros) && Number.isSafeInteger(value.perDecisionCapMicros) && value.monthlyCapMicros > 0 && value.perDecisionCapMicros > 0;
10
+ }
11
+ function evaluateCapGate(input) {
12
+ const { user, provider, model } = input;
13
+ for (const caps of [user, provider, model]) {
14
+ if (caps === void 0) continue;
15
+ if (!Number.isSafeInteger(caps.monthlyCapMicros) || !Number.isSafeInteger(caps.perDecisionCapMicros) || caps.monthlyCapMicros < 0 || caps.perDecisionCapMicros < 0) {
16
+ return { concern: "cap", ok: false, reason: "invalid-caps" };
17
+ }
18
+ }
19
+ if (!isPositiveCaps(user) || !isPositiveCaps(provider) || !isPositiveCaps(model)) {
20
+ return { concern: "cap", ok: false, reason: "no-cap" };
21
+ }
22
+ const reservedMicros = model.perDecisionCapMicros;
23
+ if (reservedMicros > user.perDecisionCapMicros || reservedMicros > provider.perDecisionCapMicros) {
24
+ return { concern: "cap", ok: false, reason: "per-decision-cap" };
25
+ }
26
+ return { concern: "cap", ok: true, reservedMicros };
27
+ }
28
+ var PERIOD_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/;
29
+ function utcPeriodOf(instantMs) {
30
+ if (!Number.isSafeInteger(instantMs) || instantMs < 0) return null;
31
+ const period = new Date(instantMs).toISOString().slice(0, 7);
32
+ return PERIOD_PATTERN.test(period) ? period : null;
33
+ }
34
+ function evaluatePeriodGate(input) {
35
+ if (input.wallPeriod === null || !PERIOD_PATTERN.test(input.wallPeriod)) {
36
+ return { concern: "period", ok: false, reason: "invalid-period" };
37
+ }
38
+ if (input.activePeriod === null) {
39
+ return { concern: "period", ok: false, reason: "period-unconfirmed" };
40
+ }
41
+ if (!PERIOD_PATTERN.test(input.activePeriod)) {
42
+ return { concern: "period", ok: false, reason: "invalid-period" };
43
+ }
44
+ if (input.activePeriod !== input.wallPeriod) {
45
+ return { concern: "period", ok: false, reason: "period-mismatch" };
46
+ }
47
+ return { concern: "period", ok: true, period: input.activePeriod };
48
+ }
49
+ function evaluateLedgerGate(input) {
50
+ if (!input.present) return { concern: "ledger", ok: false, reason: "ledger-missing" };
51
+ if (input.frozen) return { concern: "ledger", ok: false, reason: "frozen" };
52
+ const additional = input.reservedMicros;
53
+ const exceeds = (committed, cap) => committed > cap || additional > cap - committed;
54
+ if (exceeds(input.userCommittedMicros, input.userMonthlyCapMicros) || exceeds(input.providerCommittedMicros, input.providerMonthlyCapMicros) || exceeds(input.modelCommittedMicros, input.modelMonthlyCapMicros)) {
55
+ return { concern: "ledger", ok: false, reason: "monthly-cap" };
56
+ }
57
+ return { concern: "ledger", ok: true };
58
+ }
59
+ function evaluateDecisionBudgetAdmission(input) {
60
+ const cap = evaluateCapGate(input.caps);
61
+ if (!cap.ok) return { admitted: false, concern: cap.concern, reason: cap.reason };
62
+ const period = evaluatePeriodGate(input.period);
63
+ if (!period.ok) return { admitted: false, concern: period.concern, reason: period.reason };
64
+ const ledger = evaluateLedgerGate({
65
+ ...input.ledger,
66
+ present: true,
67
+ reservedMicros: cap.reservedMicros
68
+ });
69
+ if (!ledger.ok) return { admitted: false, concern: ledger.concern, reason: ledger.reason };
70
+ return { admitted: true, period: period.period, reservedMicros: cap.reservedMicros };
71
+ }
72
+ var EXPECTED_APPLICATION_ID = 1346522161;
73
+ function classifyDbPath(dbPath) {
74
+ try {
75
+ const stat = lstatSync(dbPath);
76
+ return stat.isFile() && !stat.isSymbolicLink() ? "regular" : "unsafe";
77
+ } catch {
78
+ return "missing";
79
+ }
80
+ }
81
+ function readCapsRow(db, sql) {
82
+ const row = db.prepare(sql).get();
83
+ if (!row) return null;
84
+ return {
85
+ monthly: Number(row.monthly_cap_micros),
86
+ perDecision: Number(row.per_decision_cap_micros)
87
+ };
88
+ }
89
+ function readDecisionBudgetLedgerFacts(dbPath) {
90
+ const kind = classifyDbPath(dbPath);
91
+ if (kind === "missing") return { present: false };
92
+ if (kind === "unsafe") {
93
+ return { present: true, readable: false, reason: "not-a-regular-file" };
94
+ }
95
+ let db;
96
+ try {
97
+ db = new DatabaseSync(dbPath, { readOnly: true });
98
+ } catch {
99
+ return { present: true, readable: false, reason: "unsupported-schema" };
100
+ }
101
+ try {
102
+ const version = db.prepare("PRAGMA user_version").get().user_version;
103
+ const applicationId = db.prepare("PRAGMA application_id").get().application_id;
104
+ if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) {
105
+ return { present: true, readable: false, reason: "unsupported-schema" };
106
+ }
107
+ const activeRow = db.prepare("SELECT active_period_utc FROM ledger_state WHERE id = 1").get();
108
+ const counts = db.prepare(
109
+ `SELECT
110
+ COUNT(*) AS reservations,
111
+ COALESCE(SUM(CASE WHEN state IN ('pending', 'uncertain') THEN 1 ELSE 0 END), 0) AS holds
112
+ FROM reservations`
113
+ ).get();
114
+ const freezes = db.prepare("SELECT COUNT(*) AS total FROM budget_freezes").get();
115
+ return {
116
+ present: true,
117
+ readable: true,
118
+ schemaVersion: version,
119
+ applicationId,
120
+ activePeriod: activeRow?.active_period_utc ?? null,
121
+ reservations: Number(counts.reservations),
122
+ holds: Number(counts.holds),
123
+ freezes: Number(freezes.total)
124
+ };
125
+ } catch {
126
+ return { present: true, readable: false, reason: "unsupported-schema" };
127
+ } finally {
128
+ db.close();
129
+ }
130
+ }
131
+ function readDecisionCapFacts(dbPath) {
132
+ if (classifyDbPath(dbPath) !== "regular") return null;
133
+ let db;
134
+ try {
135
+ db = new DatabaseSync(dbPath, { readOnly: true });
136
+ } catch {
137
+ return null;
138
+ }
139
+ try {
140
+ const user = readCapsRow(
141
+ db,
142
+ "SELECT monthly_cap_micros, per_decision_cap_micros FROM user_caps WHERE id = 1"
143
+ );
144
+ const providers = {};
145
+ for (const row of db.prepare("SELECT provider, monthly_cap_micros, per_decision_cap_micros FROM provider_caps").all()) {
146
+ providers[row.provider] = {
147
+ monthlyCapMicros: Number(row.monthly_cap_micros),
148
+ perDecisionCapMicros: Number(row.per_decision_cap_micros)
149
+ };
150
+ }
151
+ const models = {};
152
+ for (const row of db.prepare(
153
+ "SELECT provider, model, monthly_cap_micros, per_decision_cap_micros FROM model_caps"
154
+ ).all()) {
155
+ models[`${row.provider}/${row.model}`] = {
156
+ monthlyCapMicros: Number(row.monthly_cap_micros),
157
+ perDecisionCapMicros: Number(row.per_decision_cap_micros)
158
+ };
159
+ }
160
+ return {
161
+ user: user === null ? null : { monthlyCapMicros: user.monthly, perDecisionCapMicros: user.perDecision },
162
+ providers,
163
+ models
164
+ };
165
+ } catch {
166
+ return null;
167
+ } finally {
168
+ db.close();
169
+ }
170
+ }
171
+ function inspectDecisionBudget(dbPath) {
172
+ const ledger = readDecisionBudgetLedgerFacts(dbPath);
173
+ const caps = readDecisionCapFacts(dbPath);
174
+ const activePeriod = ledger.present && ledger.readable ? ledger.activePeriod : null;
175
+ return { ledger, caps, period: { activePeriod } };
176
+ }
177
+ function listDecisionHoldsReadOnly(dbPath) {
178
+ if (classifyDbPath(dbPath) !== "regular") return null;
179
+ let db;
180
+ try {
181
+ db = new DatabaseSync(dbPath, { readOnly: true });
182
+ } catch {
183
+ return null;
184
+ }
185
+ try {
186
+ const applicationId = db.prepare("PRAGMA application_id").get().application_id;
187
+ const version = db.prepare("PRAGMA user_version").get().user_version;
188
+ if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) return null;
189
+ const rows = db.prepare(
190
+ `SELECT id, provider, model, period_utc, reserved_micros, state
191
+ FROM reservations WHERE state IN ('pending', 'uncertain')
192
+ ORDER BY created_at_ms, id`
193
+ ).all();
194
+ return rows.map((row) => ({
195
+ reservationId: row.id,
196
+ provider: row.provider,
197
+ model: row.model,
198
+ period: row.period_utc,
199
+ reservedMicros: Number(row.reserved_micros),
200
+ state: row.state
201
+ }));
202
+ } catch {
203
+ return null;
204
+ } finally {
205
+ db.close();
206
+ }
207
+ }
208
+ export {
209
+ evaluateCapGate,
210
+ evaluateDecisionBudgetAdmission,
211
+ evaluateLedgerGate,
212
+ evaluatePeriodGate,
213
+ inspectDecisionBudget,
214
+ listDecisionHoldsReadOnly,
215
+ readDecisionBudgetLedgerFacts,
216
+ readDecisionCapFacts,
217
+ utcPeriodOf
218
+ };