pantheon-opencode 1.6.3-beta.6 → 1.7.0-beta.1

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 +201 -0
  4. package/README.md +16 -2
  5. package/README.pt-BR.md +1 -1
  6. package/bin/pantheon-init.mjs +46 -28
  7. package/package.json +2 -2
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/decision-router-budget.mjs +102 -2
  11. package/scripts/decision-router-v2-budget.mjs +2 -2
  12. package/scripts/decision-router.mjs +82 -25
  13. package/scripts/doctor.mjs +4 -1
  14. package/scripts/install/cli-ui.mjs +2 -1
  15. package/scripts/install/decision-router-config.mjs +12 -4
  16. package/scripts/install/interactive.mjs +45 -28
  17. package/scripts/install/opencode.mjs +151 -30
  18. package/scripts/jev-live-probe.mjs +212 -0
  19. package/scripts/skill-search.mjs +273 -0
  20. package/skills-lock.json +3 -1
  21. package/src/agents/aphrodite.md +34 -1
  22. package/src/agents/apollo.md +227 -0
  23. package/src/agents/athena.md +26 -0
  24. package/src/agents/demeter.md +33 -0
  25. package/src/agents/gaia.md +24 -0
  26. package/src/agents/hephaestus.md +24 -0
  27. package/src/agents/hermes.md +33 -0
  28. package/src/agents/iris.md +24 -0
  29. package/src/agents/mnemosyne.md +25 -3
  30. package/src/agents/nyx.md +50 -22
  31. package/src/agents/prometheus.md +242 -1
  32. package/src/agents/talos.md +24 -0
  33. package/src/agents/themis.md +24 -0
  34. package/src/agents/zeus.md +81 -6
  35. package/src/pantheon/j1-approvals.ts +123 -0
  36. package/src/pantheon/jev-decision-tool.ts +293 -35
  37. package/src/pantheon/jev-decisions.ts +95 -12
  38. package/src/pantheon/jev-escalation.ts +1 -1
  39. package/src/pantheon/jev-quality-score.ts +45 -10
  40. package/src/pantheon/jev-rank-verify.ts +665 -0
  41. package/src/pantheon/jev-risk-gate.ts +82 -12
  42. package/src/pantheon/local-decision-budget.ts +169 -2
  43. package/src/pantheon/local-decision-prompt.ts +2 -0
  44. package/src/pantheon/local-decision-router.ts +16 -0
  45. package/src/pantheon/local-decision-turn.ts +110 -4
  46. package/src/pantheon/local-decision-usage-evidence.internal.ts +2 -2
  47. package/src/pantheon/pantheon-decision-catalog.ts +9 -2
  48. package/src/pantheon/v2-decision-budget.ts +4 -2
  49. package/src/pantheon/v2-tools.ts +42 -0
  50. package/src/plugin-v2.ts +85 -5
  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.js +128 -25
  56. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  57. package/src/plugins/tui/dist/tui.js +1 -1
  58. package/src/plugins/tui/package-lock.json +2 -2
  59. package/src/plugins/tui/package.json +1 -1
  60. package/src/plugins/tui/src/server-v2.ts +14 -7
  61. package/src/plugins/tui/src/whats-new-highlights.ts +59 -5
  62. package/src/plugins/tui/src/whats-new-open.ts +41 -1
  63. package/src/plugins/tui/src/whats-new.tsx +61 -8
  64. package/src/routing.yml +2 -0
  65. package/src/skills/README.md +1 -1
  66. package/src/skills/agent-forge/SKILL.md +76 -0
  67. package/src/skills/auto-continue/SKILL.md +12 -163
  68. package/src/skills/auto-continue/references/auto-continue-details.md +175 -0
  69. package/src/skills/prompt-refinery/SKILL.md +60 -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,7 +390,10 @@ 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',
395
+ ORDER_INPUT_INVALID: 'skip-request-invalid',
396
+ ORDER_CANDIDATE_INVALID: 'skip-request-invalid',
353
397
  })
354
398
 
355
399
  /** Map a gate failure to its telemetry reason token; unknown → fail-open. */
@@ -407,15 +451,28 @@ function abortDeadline(signal: AbortSignal): Promise<'timeout'> {
407
451
  * settles its own ledger reservation in the background (settlement of an
408
452
  * already-fired call — not a retry, and it writes no record).
409
453
  */
454
+ export interface J1Verdict {
455
+ /** 'block' only in enforce mode with an affirmative high-risk score. */
456
+ block: boolean
457
+ riskScore: number | null
458
+ reason: string
459
+ }
460
+
410
461
  export function createJ1RiskGateObserver(
411
- options: J1RiskGateObserverOptions,
412
- ): (event: unknown) => Promise<void> {
462
+ options: J1RiskGateObserverOptions & {
463
+ /** enforce: the caller awaits and denies on { block: true }. */
464
+ mode?: J1RiskGateMode
465
+ threshold?: number
466
+ },
467
+ ): (event: unknown) => Promise<J1Verdict | undefined> {
413
468
  const timeoutMs = options.timeoutMs ?? J1_RISK_GATE_TIMEOUT_MS
414
469
  const sink = options.sink
415
- return async (event: unknown): Promise<void> => {
470
+ const enforce = options.mode === 'enforce'
471
+ const threshold = options.threshold ?? J1_ENFORCE_THRESHOLD_DEFAULT
472
+ return async (event: unknown): Promise<J1Verdict | undefined> => {
416
473
  try {
417
474
  const payload = (event ?? {}) as J1ExecuteBeforeEvent
418
- if (!isRiskGateTarget(payload.tool)) return
475
+ if (!isRiskGateTarget(payload.tool)) return undefined
419
476
  const tool = payload.tool
420
477
  const scope = classifyRiskGateScope(tool)
421
478
  const built = buildRiskGateRequest({
@@ -425,7 +482,7 @@ export function createJ1RiskGateObserver(
425
482
  })
426
483
  if (!built.ok) {
427
484
  recordSkip(sink, 'skip-input-invalid')
428
- return
485
+ return undefined
429
486
  }
430
487
  const controller = new AbortController()
431
488
  const timer = setTimeout(() => controller.abort(), timeoutMs)
@@ -450,11 +507,11 @@ export function createJ1RiskGateObserver(
450
507
  ])
451
508
  if (outcome === 'timeout') {
452
509
  recordSkip(sink, 'skip-timeout')
453
- return
510
+ return undefined
454
511
  }
455
512
  if (!outcome.ok) {
456
513
  recordSkip(sink, mapGateFailureToSkipReason(outcome.reasonCode))
457
- return
514
+ return undefined
458
515
  }
459
516
  const evaluation = evaluateRiskGateDecision(outcome.call.response, outcome.call.request)
460
517
  observeShadow(
@@ -466,6 +523,18 @@ export function createJ1RiskGateObserver(
466
523
  }),
467
524
  sink,
468
525
  )
526
+ if (enforce) {
527
+ const risk = evaluation.riskScore
528
+ const block = risk !== null && risk >= threshold
529
+ return {
530
+ block,
531
+ riskScore: risk,
532
+ reason: block
533
+ ? `J1 enforce: risco ${risk.toFixed(2)} >= threshold ${threshold}`
534
+ : 'allow',
535
+ }
536
+ }
537
+ return
469
538
  } finally {
470
539
  clearTimeout(timer)
471
540
  }
@@ -474,6 +543,7 @@ export function createJ1RiskGateObserver(
474
543
  // be opened; any other unexpected failure lands here too. One skip
475
544
  // record, no detail, no propagation into the tool call.
476
545
  recordSkip(sink, 'skip-gate-unavailable')
546
+ return undefined
477
547
  }
478
548
  }
479
549
  }
@@ -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([
@@ -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
@@ -30,6 +30,8 @@ export type PromptApplicationReason =
30
30
  | 'skills.synthetic.narrowed'
31
31
 
32
32
  export interface PromptApplicationResult {
33
+ /** Deterministic: this turn's request looks vague/multi-concern — refine first. */
34
+ refineRecommended?: boolean
33
35
  /** Always false since beta.10: the visible marker is suppressed. */
34
36
  markerApplied: boolean
35
37
  skillsFiltered: boolean
@@ -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,
@@ -26,6 +26,9 @@ export interface TurnDecision {
26
26
  skillIds: string[]
27
27
  agent: string | null
28
28
  reasonCode: string
29
+ /** Deterministic refinement flag (no model judgment): the request looks
30
+ * multi-concern and without acceptance criteria — refine BEFORE executing. */
31
+ refineRecommended: boolean
29
32
  }
30
33
 
31
34
  export interface TurnDecisionInput {
@@ -44,6 +47,7 @@ function inactive(reasonCode: string): TurnDecision {
44
47
  skillIds: [],
45
48
  agent: null,
46
49
  reasonCode,
50
+ refineRecommended: false,
47
51
  }
48
52
  }
49
53
 
@@ -55,25 +59,127 @@ function readConfig(): UserDecisionRouterConfig | undefined {
55
59
  }
56
60
  }
57
61
 
58
- function localDecision(
62
+ /**
63
+ * Delegation-relevant skills per specialist (D3 fix, field reports beta.13-16:
64
+ * a PT-Brasil delegation matched the agent lexically but starved on skills —
65
+ * the English-lexical prefilter returned [] for the same domain). When the
66
+ * prefilter matches nothing but an agent was selected, these curated subsets
67
+ * of the agent's own grants keep the delegation fed. Pinned against the
68
+ * canonical frontmatter by tests/pantheon/local-decision-turn.test.ts.
69
+ */
70
+ const AGENT_SKILL_FALLBACK: Readonly<Record<string, readonly string[]>> = Object.freeze({
71
+ athena: ['spec-driven-development', 'verification-planning'],
72
+ apollo: ['codemap'],
73
+ themis: ['code-review-checklist', 'security-hardening'],
74
+ hermes: ['incremental-implementation', 'tdd-with-agents'],
75
+ aphrodite: ['incremental-implementation', 'visual-review-pipeline'],
76
+ demeter: ['incremental-implementation', 'tdd-with-agents'],
77
+ prometheus: ['git-workflow-and-versioning'],
78
+ hephaestus: ['tdd-with-agents'],
79
+ nyx: ['auto-continue'],
80
+ gaia: ['auto-continue'],
81
+ iris: ['artifact-management', 'git-workflow-and-versioning'],
82
+ mnemosyne: ['memory-bank', 'context-compression'],
83
+ talos: ['incremental-implementation'],
84
+ })
85
+
86
+ /** Pure decision core exposed for offline tests (D3 contract).
87
+ * @internal
88
+ */
89
+ export function localDecisionForTest(
59
90
  request: string,
60
91
  policy: LocalDecisionPolicy | undefined,
61
92
  reasonCode: string,
62
93
  ): TurnDecision {
63
- const skills = selectPantheonSkills(request)
94
+ const selection = selectPantheonSkills(request)
64
95
  const agent = hasDelegationSignal(request)
65
96
  ? recommendLocalDecisionAgent(request, policy).agent
66
97
  : null
98
+ // D3: the prefilter is English-lexical; a PT state for the SAME domain
99
+ // starved. When it matches nothing but the agent is known, fall back to the
100
+ // agent's own curated grants — never an empty recommendation for a routed
101
+ // specialist.
102
+ const fallback = agent !== null ? AGENT_SKILL_FALLBACK[agent] : undefined
103
+ const skillIds: string[] =
104
+ selection.skillIds.length > 0 || fallback === undefined ? selection.skillIds : [...fallback]
67
105
  return {
68
106
  schemaVersion: 1,
69
107
  active: true,
70
108
  source: 'local',
71
- skillIds: skills.skillIds,
109
+ skillIds,
72
110
  agent,
73
111
  reasonCode,
112
+ refineRecommended: shouldRefine(request),
74
113
  }
75
114
  }
76
115
 
116
+ /**
117
+ * DETERMINISTIC refinement trigger (field beta.22→23: the owner wants
118
+ * accessibility — badly structured prompts must not degrade processing, and
119
+ * deciding "should I refine?" via Jev is negative economics). Pure text
120
+ * signals, no model: (a) 2+ distinct action concerns, (b) long multi-clause
121
+ * text, AND (c) no acceptance-criteria markers. One positive concern OR the
122
+ * long-multi-clause shape plus absent criteria fires it.
123
+ */
124
+ const CONCERN_MARKERS: readonly string[] = [
125
+ // EN + PT: fix / improve / redesign / create / refactor / add
126
+ 'corrigir',
127
+ 'corrija',
128
+ 'arrumar',
129
+ 'consertar',
130
+ 'melhorar',
131
+ 'melhora',
132
+ 'refatorar',
133
+ 'refatora',
134
+ 'redesign',
135
+ 'redesenhar',
136
+ 'criar',
137
+ 'crie',
138
+ 'adicionar',
139
+ 'adicione',
140
+ 'implementar',
141
+ 'trocar',
142
+ 'fix',
143
+ 'improve',
144
+ 'refactor',
145
+ 'redesign',
146
+ 'create',
147
+ 'add',
148
+ 'rewrite',
149
+ 'restructure',
150
+ ]
151
+
152
+ const CRITERIA_MARKERS: readonly string[] = [
153
+ 'critério',
154
+ 'criterio',
155
+ 'critérios',
156
+ 'acceptance',
157
+ 'aceite',
158
+ 'testes de aceitação',
159
+ 'acceptance criteria',
160
+ 'done when',
161
+ 'pronto quando',
162
+ 'definition of done',
163
+ ]
164
+
165
+ export function shouldRefine(request: string): boolean {
166
+ if (typeof request !== 'string') return false
167
+ const text = request.trim()
168
+ if (text.length < 24) return false // a one-liner fix never refines
169
+ const lowered = text.toLowerCase()
170
+ if (CRITERIA_MARKERS.some((marker) => lowered.includes(marker))) return false
171
+ const concerns = CONCERN_MARKERS.filter((marker) =>
172
+ new RegExp(`(^|\\s|[^a-zà-ú])${marker}`, 'i').test(lowered),
173
+ ).length
174
+ if (concerns >= 2) return true
175
+ // Long multi-clause text with a single concern also refines (the shape of a
176
+ // vague brief): 3+ clauses via separators.
177
+ const clauses = text
178
+ .split(/[,;.]|(?:\s[eE]\s)|(?:\sy\s)/)
179
+ .filter((part) => part.trim().length > 8)
180
+ return concerns >= 1 && clauses.length >= 3
181
+ }
182
+
77
183
  /**
78
184
  * Produce the deterministic local recommendation without entering the
79
185
  * provider, consent, credential, permission, or transport path. The legacy
@@ -97,5 +203,5 @@ export async function decideLocalForTurn(input: TurnDecisionInput): Promise<Turn
97
203
  if (config === undefined || !isUserDecisionRouterEnabled(config)) return inactive('DISABLED')
98
204
 
99
205
  const policy = await loadLocalDecisionPolicy().catch(() => undefined)
100
- return localDecision(request, policy, 'LOCAL_SELECTION')
206
+ return localDecisionForTest(request, policy, 'LOCAL_SELECTION')
101
207
  }
@@ -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