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

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 (67) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +137 -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 +210 -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/jev-decision-tool.ts +262 -34
  38. package/src/pantheon/jev-decisions.ts +92 -8
  39. package/src/pantheon/jev-quality-score.ts +7 -2
  40. package/src/pantheon/jev-rank-verify.ts +637 -0
  41. package/src/pantheon/jev-risk-gate.ts +70 -6
  42. package/src/pantheon/local-decision-budget.ts +170 -3
  43. package/src/pantheon/local-decision-router.ts +16 -0
  44. package/src/pantheon/local-decision-turn.ts +39 -4
  45. package/src/pantheon/local-decision-usage-evidence.internal.ts +2 -2
  46. package/src/pantheon/pantheon-decision-catalog.ts +9 -2
  47. package/src/pantheon/v2-decision-budget.ts +4 -2
  48. package/src/plugin-v2.ts +44 -7
  49. package/src/plugins/tui/dist/server-v2.d.ts +14 -6
  50. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  51. package/src/plugins/tui/dist/server-v2.js +16 -9
  52. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  53. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  54. package/src/plugins/tui/dist/tui-v2.js +560 -4
  55. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  56. package/src/plugins/tui/dist/tui.js +1 -1
  57. package/src/plugins/tui/package-lock.json +2 -2
  58. package/src/plugins/tui/package.json +1 -1
  59. package/src/plugins/tui/src/index-v2.tsx +6 -0
  60. package/src/plugins/tui/src/server-v2.ts +14 -7
  61. package/src/plugins/tui/src/whats-new-highlights.ts +317 -0
  62. package/src/plugins/tui/src/whats-new-open.ts +120 -0
  63. package/src/plugins/tui/src/whats-new-state.ts +128 -0
  64. package/src/plugins/tui/src/whats-new.tsx +172 -0
  65. package/src/routing.yml +1 -0
  66. package/src/skills/README.md +1 -1
  67. package/src/skills/prompt-refinery/SKILL.md +41 -0
@@ -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
  /**
@@ -349,6 +387,7 @@ const SKIP_REASON_BY_GATE_FAILURE: Readonly<Record<GatedNativeJevFailure, string
349
387
  PRESET_INVALID: 'skip-request-invalid',
350
388
  RESERVATION_DENIED: 'skip-reservation-denied',
351
389
  DECISION_CALL_FAILED: 'skip-decision-call-failed',
390
+ USAGE_EVIDENCE_UNAVAILABLE: 'skip-usage-evidence-unavailable',
352
391
  USAGE_UNRECONCILED: 'skip-usage-unreconciled',
353
392
  })
354
393
 
@@ -407,12 +446,25 @@ function abortDeadline(signal: AbortSignal): Promise<'timeout'> {
407
446
  * settles its own ledger reservation in the background (settlement of an
408
447
  * already-fired call — not a retry, and it writes no record).
409
448
  */
449
+ export interface J1Verdict {
450
+ /** 'block' only in enforce mode with an affirmative high-risk score. */
451
+ block: boolean
452
+ riskScore: number | null
453
+ reason: string
454
+ }
455
+
410
456
  export function createJ1RiskGateObserver(
411
- options: J1RiskGateObserverOptions,
412
- ): (event: unknown) => Promise<void> {
457
+ options: J1RiskGateObserverOptions & {
458
+ /** enforce: the caller awaits and denies on { block: true }. */
459
+ mode?: J1RiskGateMode
460
+ threshold?: number
461
+ },
462
+ ): (event: unknown) => Promise<void | J1Verdict> {
413
463
  const timeoutMs = options.timeoutMs ?? J1_RISK_GATE_TIMEOUT_MS
414
464
  const sink = options.sink
415
- return async (event: unknown): Promise<void> => {
465
+ const enforce = options.mode === 'enforce'
466
+ const threshold = options.threshold ?? J1_ENFORCE_THRESHOLD_DEFAULT
467
+ return async (event: unknown): Promise<void | J1Verdict> => {
416
468
  try {
417
469
  const payload = (event ?? {}) as J1ExecuteBeforeEvent
418
470
  if (!isRiskGateTarget(payload.tool)) return
@@ -466,6 +518,18 @@ export function createJ1RiskGateObserver(
466
518
  }),
467
519
  sink,
468
520
  )
521
+ if (enforce) {
522
+ const risk = evaluation.riskScore
523
+ const block = risk !== null && risk >= threshold
524
+ return {
525
+ block,
526
+ riskScore: risk,
527
+ reason: block
528
+ ? `J1 enforce: risco ${risk.toFixed(2)} >= threshold ${threshold}`
529
+ : 'allow',
530
+ }
531
+ }
532
+ return
469
533
  } finally {
470
534
  clearTimeout(timer)
471
535
  }
@@ -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
package/src/plugin-v2.ts CHANGED
@@ -115,6 +115,7 @@ import {
115
115
  } from './pantheon/delegation-enforce.ts'
116
116
  import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-loop.ts'
117
117
  import { createGuardPathResolver } from './pantheon/guard-path.ts'
118
+ import { createJTelemetryMirror } from './pantheon/j-telemetry-file.ts'
118
119
  import type { V2JevDecisionRuntime } from './pantheon/jev-decision-tool.ts'
119
120
  import { specialistCallerAllowlist } from './pantheon/jev-decision-tool.ts'
120
121
  import {
@@ -125,7 +126,9 @@ import {
125
126
  import {
126
127
  createJ1RiskGateObserver,
127
128
  isRiskGateTarget,
128
- j1RiskGateEnabledFromEnv,
129
+ type J1Verdict,
130
+ j1EnforceThresholdFromEnv,
131
+ j1ModeFromEnv,
129
132
  } from './pantheon/jev-risk-gate.ts'
130
133
  import { DECISION_EGRESS_ACTION } from './pantheon/local-decision-egress-gate.ts'
131
134
  import { applyDecisionRouterToPrompt } from './pantheon/local-decision-prompt.ts'
@@ -705,6 +708,7 @@ function buildV2JevRuntime(host: ReturnType<typeof hostDomains>): V2JevDecisionR
705
708
  // it; the records are advisory and never read back by the tool path.
706
709
  const j4Sink = createTelemetrySink()
707
710
  j4TelemetrySink = j4Sink
711
+ const j4Mirror = createJTelemetryMirror({ enabled: true })
708
712
  return {
709
713
  specialistCallers,
710
714
  // Every host method is invoked with its owning domain as receiver: the
@@ -718,7 +722,9 @@ function buildV2JevRuntime(host: ReturnType<typeof hostDomains>): V2JevDecisionR
718
722
  listSkills: async () => skillList?.call(skillDomain),
719
723
  ...(permissionAssert === undefined ? {} : { permissionAssert }),
720
724
  shadowSink: (record) => {
721
- j4Sink.emit({ ...record, mode: 'shadow' })
725
+ const shadowRecord = { ...record, mode: 'shadow' }
726
+ j4Sink.emit(shadowRecord)
727
+ j4Mirror?.record(shadowRecord)
722
728
  },
723
729
  }
724
730
  }
@@ -1980,14 +1986,17 @@ async function registerV2ToolHooks(
1980
1986
  // ledger reservation, permission kill-switch) and records shadow records
1981
1987
  // only — it is fired WITHOUT await inside the before-handler (fire-and-
1982
1988
  // observe), self-bounds at 2s with an AbortController, and never retries.
1983
- let j1Observer: ((event: unknown) => Promise<void>) | undefined
1984
- if (jevRuntime !== undefined && j1RiskGateEnabledFromEnv()) {
1989
+ const j1Mode = j1ModeFromEnv()
1990
+ let j1Observer: ((event: unknown) => Promise<void | J1Verdict>) | undefined
1991
+ if (jevRuntime !== undefined && j1Mode !== 'off') {
1985
1992
  const j1Sink = createTelemetrySink()
1986
1993
  j1TelemetrySink = j1Sink
1987
1994
  j1Observer = createJ1RiskGateObserver({
1988
1995
  runtime: jevRuntime,
1996
+ mode: j1Mode,
1997
+ threshold: j1EnforceThresholdFromEnv(),
1989
1998
  sink: (record) => {
1990
- j1Sink.emit({ ...record, mode: 'shadow' })
1999
+ j1Sink.emit({ ...record, mode: j1Mode === 'enforce' ? 'enforce' : 'shadow' })
1991
2000
  },
1992
2001
  })
1993
2002
  }
@@ -2009,10 +2018,13 @@ async function registerV2ToolHooks(
2009
2018
  if (jevRuntime !== undefined && j3EscalationEnabledFromEnv()) {
2010
2019
  const j3Sink = createTelemetrySink()
2011
2020
  j3TelemetrySink = j3Sink
2021
+ const j3Mirror = createJTelemetryMirror({ enabled: true })
2012
2022
  j3Observer = createJ3EscalationObserver({
2013
2023
  runtime: jevRuntime,
2014
2024
  sink: (record) => {
2015
- j3Sink.emit({ ...record, mode: 'shadow' })
2025
+ const shadowRecord = { ...record, mode: 'shadow' }
2026
+ j3Sink.emit(shadowRecord)
2027
+ j3Mirror?.record(shadowRecord)
2016
2028
  },
2017
2029
  })
2018
2030
  }
@@ -2141,7 +2153,32 @@ async function registerV2ToolHooks(
2141
2153
  // the flag is off — the only cost of the flag-on check below is the
2142
2154
  // truthiness read.
2143
2155
  if (j1Observer !== undefined && isRiskGateTarget((event as { tool?: unknown }).tool)) {
2144
- void j1Observer(event)
2156
+ // Ladder semantics: shadow/warn stay fire-and-observe (latency
2157
+ // unchanged); ENFORCE awaits (bounded 2s) and DENIES via throw —
2158
+ // the host surfaces the thrown message in the session, which is the
2159
+ // block's visible form. Unavailability never denies (fail-open by
2160
+ // design: a dead budget must not brick every shell call).
2161
+ if (j1Mode === 'enforce') {
2162
+ const verdict = (await j1Observer(event)) as J1Verdict | undefined
2163
+ if (verdict?.block === true) {
2164
+ // The block is a HANDOFF CONTRACT (field: "risco alto deveria
2165
+ // vir pra mim executar manualmente"), not an error to route
2166
+ // around: present the refused call to the human for a manual
2167
+ // decision. Never echo the tool input here — the arguments may
2168
+ // carry the very secret the risk score flagged; the agent owns
2169
+ // its own rendering.
2170
+ throw new Error(
2171
+ `[J1 enforce] risco ${verdict.riskScore?.toFixed(2)} >= threshold ` +
2172
+ '— ENTREGUE AO USUÁRIO: apresente a chamada ' +
2173
+ 'recusada (ferramenta + o que ela faria), sem executá-la nem contorná-la de outra forma, ' +
2174
+ 'e pergunte se ele executa manualmente. Alternativas dele: ajustar ' +
2175
+ 'PANTHEON_J1_ENFORCE_THRESHOLD, rebaixar o modo para shadow/warn, ou reexecutar a tarefa ' +
2176
+ 'sem o passo arriscado.',
2177
+ )
2178
+ }
2179
+ } else {
2180
+ void j1Observer(event)
2181
+ }
2145
2182
  }
2146
2183
  // J3 turn-complexity shadow classification. Same fire-and-observe
2147
2184
  // discipline as J1: the dispatch's latency is unchanged, the observer
@@ -11,12 +11,20 @@
11
11
  * channel — the initial JSX mounts but effects/refresh/events stay dead (the
12
12
  * "mudo panel" symptom; same contract as the V1 `server.ts` stub).
13
13
  *
14
- * This stub satisfies the loader contract. The native quota RPC that used to
15
- * live here was removed in 1.6.2 — provider quota/usage visibility is now the
16
- * community plugin's job (`@slkiser/opencode-quota`,
17
- * docs/tui-v2-quota-providers.md) — and pantheon-tui has no other background
18
- * server work of its own.
14
+ * This stub satisfies the loader contract. Field report (beta.13): host 2.2.5
15
+ * validates the default export as a DEFINITION OBJECT — "Plugin must export a
16
+ * default definition with an id and an effect or setup function
17
+ * (SchemaError(Expected object at ["default"]))" — the bare `server()`
18
+ * function form failed that schema on every boot (~3.4k load failures in the
19
+ * host log). The native quota RPC that used to live here was removed in 1.6.2
20
+ * — provider quota/usage visibility is now the community plugin's job
21
+ * (`@slkiser/opencode-quota`, docs/tui-v2-quota-providers.md) — and
22
+ * pantheon-tui has no other background server work of its own.
19
23
  */
20
- export default function server(): {};
24
+ declare const _default: {
25
+ id: string;
26
+ setup(): {};
27
+ };
21
28
  //#endregion
29
+ export { _default as default };
22
30
  //# sourceMappingURL=server-v2.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-v2.d.ts","names":[],"sources":["../src/server-v2.ts"],"mappings":";;;;;;;;;;;;;;;;;;;wBAkBwB"}
1
+ {"version":3,"file":"server-v2.d.ts","names":[],"sources":["../src/server-v2.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;cAAA;EAuBE;EACA"}