pantheon-opencode 1.6.3-beta.2 → 1.6.3-beta.21

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 (69) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +143 -0
  4. package/README.md +21 -3
  5. package/README.pt-BR.md +1 -1
  6. package/bin/pantheon-init.mjs +46 -28
  7. package/package.json +1 -1
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/decision-router-budget.mjs +103 -3
  11. package/scripts/decision-router-v2-budget.mjs +2 -2
  12. package/scripts/decision-router.mjs +88 -6
  13. package/scripts/install/cli-ui.mjs +2 -1
  14. package/scripts/install/decision-router-config.mjs +53 -0
  15. package/scripts/install/interactive.mjs +103 -9
  16. package/scripts/install/opencode.mjs +101 -30
  17. package/scripts/install/plugin.mjs +17 -0
  18. package/scripts/jev-live-probe.mjs +212 -0
  19. package/scripts/skill-search.mjs +273 -0
  20. package/scripts/sync-tui.mjs +11 -0
  21. package/skills-lock.json +1 -0
  22. package/src/agents/aphrodite.md +34 -1
  23. package/src/agents/apollo.md +227 -0
  24. package/src/agents/athena.md +26 -0
  25. package/src/agents/demeter.md +33 -0
  26. package/src/agents/gaia.md +24 -0
  27. package/src/agents/hephaestus.md +24 -0
  28. package/src/agents/hermes.md +33 -0
  29. package/src/agents/iris.md +24 -0
  30. package/src/agents/mnemosyne.md +25 -3
  31. package/src/agents/nyx.md +50 -22
  32. package/src/agents/prometheus.md +242 -1
  33. package/src/agents/talos.md +24 -0
  34. package/src/agents/themis.md +24 -0
  35. package/src/agents/zeus.md +67 -6
  36. package/src/pantheon/j-telemetry-file.ts +96 -0
  37. package/src/pantheon/j1-approvals.ts +123 -0
  38. package/src/pantheon/jev-decision-tool.ts +268 -34
  39. package/src/pantheon/jev-decisions.ts +92 -8
  40. package/src/pantheon/jev-escalation.ts +1 -1
  41. package/src/pantheon/jev-quality-score.ts +7 -2
  42. package/src/pantheon/jev-rank-verify.ts +661 -0
  43. package/src/pantheon/jev-risk-gate.ts +75 -8
  44. package/src/pantheon/local-decision-budget.ts +170 -3
  45. package/src/pantheon/local-decision-router.ts +16 -0
  46. package/src/pantheon/local-decision-turn.ts +39 -4
  47. package/src/pantheon/local-decision-usage-evidence.internal.ts +2 -2
  48. package/src/pantheon/pantheon-decision-catalog.ts +9 -2
  49. package/src/pantheon/v2-decision-budget.ts +4 -2
  50. package/src/plugin-v2.ts +94 -7
  51. package/src/plugins/tui/dist/server-v2.d.ts +14 -6
  52. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  53. package/src/plugins/tui/dist/server-v2.js +16 -9
  54. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  55. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  56. package/src/plugins/tui/dist/tui-v2.js +560 -4
  57. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  58. package/src/plugins/tui/dist/tui.js +1 -1
  59. package/src/plugins/tui/package-lock.json +2 -2
  60. package/src/plugins/tui/package.json +1 -1
  61. package/src/plugins/tui/src/index-v2.tsx +6 -0
  62. package/src/plugins/tui/src/server-v2.ts +14 -7
  63. package/src/plugins/tui/src/whats-new-highlights.ts +317 -0
  64. package/src/plugins/tui/src/whats-new-open.ts +120 -0
  65. package/src/plugins/tui/src/whats-new-state.ts +128 -0
  66. package/src/plugins/tui/src/whats-new.tsx +172 -0
  67. package/src/routing.yml +1 -0
  68. package/src/skills/README.md +1 -1
  69. package/src/skills/prompt-refinery/SKILL.md +41 -0
@@ -89,7 +89,7 @@ export const J1_RISK_GATE_STATE_MAX_LENGTH = 512
89
89
  /** Predicate probability at or above which the intent counts as consistent. */
90
90
  export const RISK_GATE_INTENT_THRESHOLD = 0.5
91
91
 
92
- const FLAG_ON = new Set(['1', 'on', 'true'])
92
+ const FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])
93
93
  const TOOL_NAME_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
94
94
  const SHA256_HEX = /^[0-9a-f]{64}$/
95
95
  const SCOPES: ReadonlySet<string> = new Set(['write', 'execute', 'read'])
@@ -120,12 +120,50 @@ const WRITE_TOOLS: ReadonlySet<string> = new Set([
120
120
  'hashline_edit',
121
121
  ])
122
122
 
123
- /** Whether the operator explicitly enabled the flag. Absence means off. */
123
+ /**
124
+ * The escalation ladder (field beta.14: the operator wants iterative
125
+ * escalation, not a binary flag). `on`/`1`/`true` map to `shadow` for
126
+ * back-compatibility with the shipped setup.
127
+ * off — nothing fires (hard zero)
128
+ * shadow — observe + record; invisible in the session (today's behavior)
129
+ * warn — RESERVED (needs a V2 client channel; currently behaves as shadow)
130
+ * enforce — an affirmative high-risk score DENIES the tool call (the host
131
+ * surfaces the block message in the session); gate unavailability
132
+ * never blocks (fail-open, documented)
133
+ */
134
+ export type J1RiskGateMode = 'off' | 'shadow' | 'warn' | 'enforce'
135
+
136
+ export const J1_ENFORCE_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'
137
+ export const J1_ENFORCE_THRESHOLD_DEFAULT = 0.8
138
+
139
+ export function j1ModeFromEnv(
140
+ env: Record<string, string | undefined> = process.env,
141
+ ): J1RiskGateMode {
142
+ const raw = (env[J1_RISK_GATE_FLAG_ENV] ?? '').trim().toLowerCase()
143
+ if (raw === 'enforce') return 'enforce'
144
+ if (raw === 'warn') return 'warn'
145
+ return FLAG_ON.has(raw) ? 'shadow' : 'off'
146
+ }
147
+
148
+ /** Back-compatible: any non-off mode counts as enabled. */
124
149
  export function j1RiskGateEnabledFromEnv(
125
150
  env: Record<string, string | undefined> = process.env,
126
151
  ): boolean {
127
- const raw = (env[J1_RISK_GATE_FLAG_ENV] ?? '').trim().toLowerCase()
128
- return FLAG_ON.has(raw)
152
+ return j1ModeFromEnv(env) !== 'off'
153
+ }
154
+
155
+ /**
156
+ * The enforce-mode deny threshold (0..1). Invalid or out-of-range values fall
157
+ * back to the documented default — an operator typo must not disable the gate.
158
+ */
159
+ export function j1EnforceThresholdFromEnv(
160
+ env: Record<string, string | undefined> = process.env,
161
+ ): number {
162
+ const text = (env[J1_ENFORCE_THRESHOLD_ENV] ?? '').trim()
163
+ if (text === '') return J1_ENFORCE_THRESHOLD_DEFAULT
164
+ const raw = Number(text)
165
+ if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_ENFORCE_THRESHOLD_DEFAULT
166
+ return raw
129
167
  }
130
168
 
131
169
  /**
@@ -154,7 +192,10 @@ export function isRiskGateTarget(tool: unknown): tool is string {
154
192
 
155
193
  /**
156
194
  * sha256 hex of the serialized tool input — an opaque correlation value, the
157
- * only content-derived field that ever leaves this process. Unserializable
195
+ * only content-derived field that ever leaves this process. The hash is a
196
+ * DETERMINISTIC pseudonymization (unsalted SHA-256 — same input, same hash by
197
+ * design, so approvals can be pinned to the exact call), NOT anonymization:
198
+ * someone holding the dictionary can reconstruct the input. Unserializable
158
199
  * inputs hash a stable marker; this never throws.
159
200
  */
160
201
  export function hashToolInput(input: unknown): string {
@@ -349,6 +390,7 @@ const SKIP_REASON_BY_GATE_FAILURE: Readonly<Record<GatedNativeJevFailure, string
349
390
  PRESET_INVALID: 'skip-request-invalid',
350
391
  RESERVATION_DENIED: 'skip-reservation-denied',
351
392
  DECISION_CALL_FAILED: 'skip-decision-call-failed',
393
+ USAGE_EVIDENCE_UNAVAILABLE: 'skip-usage-evidence-unavailable',
352
394
  USAGE_UNRECONCILED: 'skip-usage-unreconciled',
353
395
  })
354
396
 
@@ -407,12 +449,25 @@ function abortDeadline(signal: AbortSignal): Promise<'timeout'> {
407
449
  * settles its own ledger reservation in the background (settlement of an
408
450
  * already-fired call — not a retry, and it writes no record).
409
451
  */
452
+ export interface J1Verdict {
453
+ /** 'block' only in enforce mode with an affirmative high-risk score. */
454
+ block: boolean
455
+ riskScore: number | null
456
+ reason: string
457
+ }
458
+
410
459
  export function createJ1RiskGateObserver(
411
- options: J1RiskGateObserverOptions,
412
- ): (event: unknown) => Promise<void> {
460
+ options: J1RiskGateObserverOptions & {
461
+ /** enforce: the caller awaits and denies on { block: true }. */
462
+ mode?: J1RiskGateMode
463
+ threshold?: number
464
+ },
465
+ ): (event: unknown) => Promise<void | J1Verdict> {
413
466
  const timeoutMs = options.timeoutMs ?? J1_RISK_GATE_TIMEOUT_MS
414
467
  const sink = options.sink
415
- return async (event: unknown): Promise<void> => {
468
+ const enforce = options.mode === 'enforce'
469
+ const threshold = options.threshold ?? J1_ENFORCE_THRESHOLD_DEFAULT
470
+ return async (event: unknown): Promise<void | J1Verdict> => {
416
471
  try {
417
472
  const payload = (event ?? {}) as J1ExecuteBeforeEvent
418
473
  if (!isRiskGateTarget(payload.tool)) return
@@ -466,6 +521,18 @@ export function createJ1RiskGateObserver(
466
521
  }),
467
522
  sink,
468
523
  )
524
+ if (enforce) {
525
+ const risk = evaluation.riskScore
526
+ const block = risk !== null && risk >= threshold
527
+ return {
528
+ block,
529
+ riskScore: risk,
530
+ reason: block
531
+ ? `J1 enforce: risco ${risk.toFixed(2)} >= threshold ${threshold}`
532
+ : 'allow',
533
+ }
534
+ }
535
+ return
469
536
  } finally {
470
537
  clearTimeout(timer)
471
538
  }
@@ -82,6 +82,20 @@ export interface UncertainReservation {
82
82
  updatedAtMs: number
83
83
  }
84
84
 
85
+ export interface ReleasedHold {
86
+ reservationId: string
87
+ provider: string
88
+ model: string
89
+ period: string
90
+ reservedMicros: number
91
+ stateAtRelease: 'pending' | 'uncertain'
92
+ reason: string
93
+ createdAtMs: number
94
+ releasedAtMs: number
95
+ }
96
+
97
+ export type ReleaseHoldsResult = { released: number; freedMicros: number }
98
+
85
99
  export interface LocalDecisionBudgetLedger {
86
100
  /** Admin/configuration API: writes policy to the local user-level DB. */
87
101
  configureUserCaps(caps: BudgetCaps): void
@@ -107,6 +121,16 @@ export interface LocalDecisionBudgetLedger {
107
121
  listUncertainReservations(): UncertainReservation[]
108
122
  /** Recovery only moves pending rows to uncertain; it never releases budget. */
109
123
  recoverPendingReservations(): number
124
+ /**
125
+ * Release every unresolved hold of one provider, archiving each row into
126
+ * `released_holds` with the mandatory reason. Deliberately narrow: this is
127
+ * the administrative correction for holds of routes that no longer exist
128
+ * (they can never reconcile, so they would freeze budget forever). Live
129
+ * providers roll their holds off with the period instead.
130
+ */
131
+ releaseHoldsForProvider(provider: string, reason: string): ReleaseHoldsResult
132
+ /** Recent archived releases, newest first — the audit view of the above. */
133
+ listReleasedHolds(limit?: number): ReleasedHold[]
110
134
  /** Prune resolved reservations from past UTC periods with no unresolved holds. */
111
135
  pruneCompletedPeriods(): number
112
136
  close(): void
@@ -123,9 +147,11 @@ export interface OpenLocalDecisionBudgetOptions {
123
147
  busyTimeoutMs?: number
124
148
  }
125
149
 
126
- const SCHEMA_VERSION = 3
150
+ const SCHEMA_VERSION = 4
127
151
  const VERSION_TWO = 2
128
152
  const APPLICATION_ID = 0x50424c31
153
+ /** Reason strings recorded on a released hold are bounded for the audit trail. */
154
+ const RELEASE_REASON_MAX_LENGTH = 200
129
155
  const DB_FILENAME = 'decision-budget.sqlite'
130
156
  /** Accounting provider IDs accepted by the ledger. */
131
157
  export const LOCAL_DECISION_BUDGET_PROVIDERS: readonly BudgetProvider[] = Object.freeze([
@@ -137,7 +163,7 @@ export const LOCAL_DECISION_BUDGET_PROVIDERS: readonly BudgetProvider[] = Object
137
163
  'cloudflare-workers-ai',
138
164
  ])
139
165
  const ALLOWED_PROVIDERS = new Set<BudgetProvider>(LOCAL_DECISION_BUDGET_PROVIDERS)
140
- const MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
166
+ const MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/
141
167
  const RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
142
168
  const CLOCK_ROLLBACK_TOLERANCE_MS = 60_000
143
169
 
@@ -608,6 +634,101 @@ export function openLocalDecisionBudgetLedger(
608
634
  })
609
635
  }
610
636
 
637
+ function releaseHoldsForProvider(provider: string, reason: string): ReleaseHoldsResult {
638
+ if (typeof provider !== 'string' || provider.length < 1 || provider.length > 64) {
639
+ return { released: 0, freedMicros: 0 }
640
+ }
641
+ if (
642
+ typeof reason !== 'string' ||
643
+ reason.length < 1 ||
644
+ reason.length > RELEASE_REASON_MAX_LENGTH
645
+ ) {
646
+ return { released: 0, freedMicros: 0 }
647
+ }
648
+ return inImmediateTransaction(() => {
649
+ const timestamp = now()
650
+ const rows = db
651
+ .prepare(
652
+ `SELECT id, provider, model, period_utc, reserved_micros, state, created_at_ms
653
+ FROM reservations WHERE provider = ? AND state IN ('pending', 'uncertain')
654
+ ORDER BY created_at_ms, id`,
655
+ )
656
+ .all(provider) as Array<{
657
+ id: string
658
+ provider: string
659
+ model: string
660
+ period_utc: string
661
+ reserved_micros: number
662
+ state: 'pending' | 'uncertain'
663
+ created_at_ms: number
664
+ }>
665
+ if (rows.length === 0) return { released: 0, freedMicros: 0 }
666
+ const archive = db.prepare(
667
+ `INSERT INTO released_holds
668
+ (reservation_id, provider, model, period_utc, reserved_micros, state_at_release,
669
+ reason, created_at_ms, released_at_ms)
670
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
671
+ )
672
+ let freedMicros = 0
673
+ for (const row of rows) {
674
+ archive.run(
675
+ row.id,
676
+ row.provider,
677
+ row.model,
678
+ row.period_utc,
679
+ row.reserved_micros,
680
+ row.state,
681
+ reason,
682
+ row.created_at_ms,
683
+ timestamp,
684
+ )
685
+ freedMicros = safeMicrosTotal(freedMicros + row.reserved_micros)
686
+ }
687
+ const remove = db
688
+ .prepare(
689
+ `DELETE FROM reservations WHERE provider = ? AND state IN ('pending', 'uncertain')`,
690
+ )
691
+ .run(provider)
692
+ if (safeChangeCount(remove.changes) !== rows.length) {
693
+ throw new Error('Reservation rows changed during release')
694
+ }
695
+ return { released: rows.length, freedMicros }
696
+ })
697
+ }
698
+
699
+ function listReleasedHolds(limit?: number): ReleasedHold[] {
700
+ const bound =
701
+ typeof limit === 'number' && Number.isInteger(limit) && limit > 0 ? Math.min(limit, 200) : 20
702
+ const rows = db
703
+ .prepare(
704
+ `SELECT reservation_id, provider, model, period_utc, reserved_micros, state_at_release,
705
+ reason, created_at_ms, released_at_ms
706
+ FROM released_holds ORDER BY released_at_ms DESC, reservation_id LIMIT ?`,
707
+ )
708
+ .all(bound) as Array<{
709
+ reservation_id: string
710
+ provider: string
711
+ model: string
712
+ period_utc: string
713
+ reserved_micros: number
714
+ state_at_release: string
715
+ reason: string
716
+ created_at_ms: number
717
+ released_at_ms: number
718
+ }>
719
+ return rows.map((row) => ({
720
+ reservationId: row.reservation_id,
721
+ provider: row.provider,
722
+ model: row.model,
723
+ period: row.period_utc,
724
+ reservedMicros: row.reserved_micros,
725
+ stateAtRelease: row.state_at_release === 'uncertain' ? 'uncertain' : 'pending',
726
+ reason: row.reason,
727
+ createdAtMs: row.created_at_ms,
728
+ releasedAtMs: row.released_at_ms,
729
+ }))
730
+ }
731
+
611
732
  function pruneCompletedPeriods(): number {
612
733
  return inImmediateTransaction(() => {
613
734
  let currentPeriod: string
@@ -675,6 +796,8 @@ export function openLocalDecisionBudgetLedger(
675
796
  reconcileVerified,
676
797
  listUncertainReservations,
677
798
  recoverPendingReservations,
799
+ releaseHoldsForProvider,
800
+ listReleasedHolds,
678
801
  pruneCompletedPeriods,
679
802
  close: () => db.close(),
680
803
  }
@@ -699,12 +822,16 @@ function ensureSchema(db: DatabaseSync): void {
699
822
  if (applicationId !== 0 || tables.length !== 0) {
700
823
  throw new Error('Refusing to initialize an unrecognized SQLite database')
701
824
  }
702
- createSchemaV3(db)
825
+ createSchemaV4(db)
703
826
  } else if (version === 1 && applicationId === APPLICATION_ID) {
704
827
  migrateVersionOne(db)
705
828
  migrateVersionTwoToThree(db)
829
+ migrateVersionThreeToFour(db)
706
830
  } else if (version === VERSION_TWO && applicationId === APPLICATION_ID) {
707
831
  migrateVersionTwoToThree(db)
832
+ migrateVersionThreeToFour(db)
833
+ } else if (version === 3 && applicationId === APPLICATION_ID) {
834
+ migrateVersionThreeToFour(db)
708
835
  } else if (version !== SCHEMA_VERSION || applicationId !== APPLICATION_ID) {
709
836
  throw new Error('Unsupported or incompatible local decision budget database schema')
710
837
  }
@@ -802,10 +929,50 @@ function migrateVersionTwoToThree(db: DatabaseSync): void {
802
929
  INSERT INTO ledger_state (id, active_period_utc)
803
930
  SELECT id, NULL FROM ledger_state_v2;
804
931
  DROP TABLE ledger_state_v2;
932
+ PRAGMA user_version = 3;
933
+ `)
934
+ }
935
+
936
+ /**
937
+ * v4 adds the `released_holds` archive (immutable audit trail for the
938
+ * administrative release of dead-route holds). The live `reservations` table
939
+ * and its state CHECK are untouched — a release archives the row and deletes
940
+ * it, so the accounting keeps summing only live states.
941
+ */
942
+ function migrateVersionThreeToFour(db: DatabaseSync): void {
943
+ validateVersionThreeSchema(db)
944
+ db.exec(`
945
+ CREATE TABLE released_holds (
946
+ reservation_id TEXT PRIMARY KEY NOT NULL,
947
+ provider TEXT NOT NULL,
948
+ model TEXT NOT NULL,
949
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
950
+ reserved_micros INTEGER NOT NULL CHECK (reserved_micros > 0),
951
+ state_at_release TEXT NOT NULL CHECK (state_at_release IN ('pending', 'uncertain')),
952
+ reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND ${RELEASE_REASON_MAX_LENGTH}),
953
+ created_at_ms INTEGER NOT NULL,
954
+ released_at_ms INTEGER NOT NULL
955
+ ) STRICT;
956
+ CREATE INDEX released_holds_released_idx ON released_holds (released_at_ms, reservation_id);
805
957
  PRAGMA user_version = ${SCHEMA_VERSION};
806
958
  `)
807
959
  }
808
960
 
961
+ function createSchemaV4(db: DatabaseSync): void {
962
+ createSchemaV3(db)
963
+ migrateVersionThreeToFour(db)
964
+ }
965
+
966
+ function validateVersionThreeSchema(db: DatabaseSync): void {
967
+ // The v3 tables match the post-migration shape; the v4 step adds
968
+ // released_holds on top of them.
969
+ db.prepare(
970
+ `SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
971
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
972
+ )
973
+ db.prepare('SELECT id, active_period_utc FROM ledger_state LIMIT 0')
974
+ }
975
+
809
976
  function migrateVersionOne(db: DatabaseSync): void {
810
977
  validateVersionOneSchema(db)
811
978
  const providers = db
@@ -4,6 +4,12 @@ import { PANTHEON_AGENTS } from './v2-delegation-enforce.ts'
4
4
  export const LOCAL_DECISION_ROUTER_ENV = 'PANTHEON_LOCAL_DECISION_ROUTER'
5
5
  export const LOCAL_DECISION_ROUTER_POLICY_VERSION = 'local-decision-router/v1'
6
6
 
7
+ /**
8
+ * Complexity dimensions, each 0..2 where HIGHER MEANS RISKIER/LESS CONTAINED
9
+ * (field report D4, three rounds unread): `boundedness: 2` reads like "very
10
+ * bounded" but means POORLY bounded (scope escapes). The label aggregate is
11
+ * max(dimensions) — one hot dimension is enough to label the task high.
12
+ */
7
13
  export const LOCAL_DECISION_COMPLEXITY_DIMENSIONS = [
8
14
  'boundedness',
9
15
  'reversibility',
@@ -32,6 +38,7 @@ export interface LocalDecisionInput {
32
38
 
33
39
  export type LocalDecisionRouteReasonCode =
34
40
  | 'DISABLED'
41
+ | 'GATE_OPEN'
35
42
  | 'INVALID_INPUT'
36
43
  | 'NO_DOMAIN'
37
44
  | 'AMBIGUOUS_DOMAIN'
@@ -192,6 +199,15 @@ function evaluateEnabledInput(input: unknown): LocalDecisionRecommendation {
192
199
  }
193
200
  }
194
201
 
202
+ // D1 (field report beta.11→12): gateStatus must influence the output. An
203
+ // open review/approval gate abstains — the advisory never routes around a
204
+ // gate; resolving the gate is the caller's move, then this router answers.
205
+ if (gateStatus === 'review_required' || gateStatus === 'human_approval_required') {
206
+ return {
207
+ ...createAbstention('GATE_OPEN', complexity.reasonCode, gateStatus),
208
+ complexity,
209
+ }
210
+ }
195
211
  return {
196
212
  schemaVersion: 1,
197
213
  policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
@@ -55,20 +55,55 @@ function readConfig(): UserDecisionRouterConfig | undefined {
55
55
  }
56
56
  }
57
57
 
58
- function localDecision(
58
+ /**
59
+ * Delegation-relevant skills per specialist (D3 fix, field reports beta.13-16:
60
+ * a PT-Brasil delegation matched the agent lexically but starved on skills —
61
+ * the English-lexical prefilter returned [] for the same domain). When the
62
+ * prefilter matches nothing but an agent was selected, these curated subsets
63
+ * of the agent's own grants keep the delegation fed. Pinned against the
64
+ * canonical frontmatter by tests/pantheon/local-decision-turn.test.ts.
65
+ */
66
+ const AGENT_SKILL_FALLBACK: Readonly<Record<string, readonly string[]>> = Object.freeze({
67
+ athena: ['spec-driven-development', 'verification-planning'],
68
+ apollo: ['codemap'],
69
+ themis: ['code-review-checklist', 'security-hardening'],
70
+ hermes: ['incremental-implementation', 'tdd-with-agents'],
71
+ aphrodite: ['incremental-implementation', 'visual-review-pipeline'],
72
+ demeter: ['incremental-implementation', 'tdd-with-agents'],
73
+ prometheus: ['git-workflow-and-versioning'],
74
+ hephaestus: ['tdd-with-agents'],
75
+ nyx: ['auto-continue'],
76
+ gaia: ['auto-continue'],
77
+ iris: ['artifact-management', 'git-workflow-and-versioning'],
78
+ mnemosyne: ['memory-bank', 'context-compression'],
79
+ talos: ['incremental-implementation'],
80
+ })
81
+
82
+ /** Pure decision core exposed for offline tests (D3 contract).
83
+ * @internal
84
+ */
85
+ export function localDecisionForTest(
59
86
  request: string,
60
87
  policy: LocalDecisionPolicy | undefined,
61
88
  reasonCode: string,
62
89
  ): TurnDecision {
63
- const skills = selectPantheonSkills(request)
90
+ const selection = selectPantheonSkills(request)
64
91
  const agent = hasDelegationSignal(request)
65
92
  ? recommendLocalDecisionAgent(request, policy).agent
66
93
  : null
94
+ // D3: the prefilter is English-lexical; a PT state for the SAME domain
95
+ // starved. When it matches nothing but the agent is known, fall back to the
96
+ // agent's own curated grants — never an empty recommendation for a routed
97
+ // specialist.
98
+ const skillIds =
99
+ selection.skillIds.length > 0 || agent === null || !(agent in AGENT_SKILL_FALLBACK)
100
+ ? selection.skillIds
101
+ : AGENT_SKILL_FALLBACK[agent]
67
102
  return {
68
103
  schemaVersion: 1,
69
104
  active: true,
70
105
  source: 'local',
71
- skillIds: skills.skillIds,
106
+ skillIds,
72
107
  agent,
73
108
  reasonCode,
74
109
  }
@@ -97,5 +132,5 @@ export async function decideLocalForTurn(input: TurnDecisionInput): Promise<Turn
97
132
  if (config === undefined || !isUserDecisionRouterEnabled(config)) return inactive('DISABLED')
98
133
 
99
134
  const policy = await loadLocalDecisionPolicy().catch(() => undefined)
100
- return localDecision(request, policy, 'LOCAL_SELECTION')
135
+ return localDecisionForTest(request, policy, 'LOCAL_SELECTION')
101
136
  }
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  /** Providers that can appear in usage details: native Decisions routes. */
11
- export type UsageProvider = 'typesafe-jev' | 'opencode-console'
11
+ export type UsageProvider = 'typesafe-jev' | 'opencode-console' | 'openrouter'
12
12
 
13
13
  export interface ParsedUsageCounts {
14
14
  provider: UsageProvider
@@ -47,7 +47,7 @@ const evidenceDetails = new WeakMap<object, VerifiedUsageEvidenceDetails>()
47
47
  * absent: direct OpenAI has no native route, so it can never settle one.
48
48
  */
49
49
  function isNativeUsageProvider(value: string): value is UsageProvider {
50
- return value === 'typesafe-jev' || value === 'opencode-console'
50
+ return value === 'typesafe-jev' || value === 'opencode-console' || value === 'openrouter'
51
51
  }
52
52
 
53
53
  /**
@@ -51,9 +51,16 @@ export const PANTHEON_AGENT_CATALOG: readonly DecisionCatalogEntry[] = Object.fr
51
51
  { id: 'aphrodite', description: 'Frontend specialist: React, TypeScript, WCAG.' },
52
52
  { id: 'demeter', description: 'Database specialist: SQLAlchemy, migrations, queries.' },
53
53
  { id: 'themis', description: 'Quality and security review gate.' },
54
- { id: 'prometheus', description: 'Infrastructure, Docker, CI, and model providers.' },
54
+ {
55
+ id: 'prometheus',
56
+ description: 'Infrastructure, Docker, CI, model providers and cloud costs.',
57
+ },
55
58
  { id: 'hephaestus', description: 'AI pipelines: LangChain, RAG, vector stores.' },
56
- { id: 'nyx', description: 'Observability, tracing, and cost analytics.' },
59
+ {
60
+ id: 'nyx',
61
+ description:
62
+ 'Observability and cost analytics: tracing, per-agent metrics; chaos and fuzz testing.',
63
+ },
57
64
  { id: 'gaia', description: 'Remote sensing and geospatial analysis.' },
58
65
  { id: 'iris', description: 'GitHub branches, pull requests, issues, releases.' },
59
66
  { id: 'mnemosyne', description: 'Memory bank and ADR authoring on request.' },
@@ -288,7 +288,9 @@ export function readDecisionBudgetLedgerFacts(dbPath: string): DecisionBudgetLed
288
288
  .user_version
289
289
  const applicationId = (db.prepare('PRAGMA application_id').get() as { application_id: number })
290
290
  .application_id
291
- if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) {
291
+ // v4 adds the released_holds archive; the live tables this module reads
292
+ // are identical from v3 through v4.
293
+ if (applicationId !== EXPECTED_APPLICATION_ID || (version !== 3 && version !== 4)) {
292
294
  return { present: true, readable: false, reason: 'unsupported-schema' }
293
295
  }
294
296
  const activeRow = db.prepare('SELECT active_period_utc FROM ledger_state WHERE id = 1').get() as
@@ -425,7 +427,7 @@ export function listDecisionHoldsReadOnly(dbPath: string): DecisionHoldRow[] | n
425
427
  .application_id
426
428
  const version = (db.prepare('PRAGMA user_version').get() as { user_version: number })
427
429
  .user_version
428
- if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) return null
430
+ if (applicationId !== EXPECTED_APPLICATION_ID || (version !== 3 && version !== 4)) return null
429
431
  const rows = db
430
432
  .prepare(
431
433
  `SELECT id, provider, model, period_utc, reserved_micros, state