Skip to main content

firstpass_core/
config.rs

1//! Routing configuration (SPEC §8.4) — declarative, agent-first.
2//!
3//! Config is the policy an operator (or agent) hands Firstpass: an ordered list of routes,
4//! each matching a slice of traffic to a mode, a model ladder, and gates; plus budget caps
5//! and escalation rules. The first matching route wins, so specific routes go first and a
6//! bare `match = {}` catch-all goes last.
7
8use crate::error::{Error, Result};
9use crate::features::{Features, TaskKind};
10use serde::{Deserialize, Serialize};
11use std::time::Duration;
12
13/// Serving mode for a route (SPEC glossary).
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Mode {
17    /// Gate before serving; escalate on fail. The output is proven before the caller sees it.
18    Enforce,
19    /// Serve immediately, gate asynchronously — verdicts feed learning only. Zero added latency,
20    /// zero risk; the default for onboarding unfamiliar traffic.
21    Observe,
22}
23
24/// Named routing-mode presets: coherent (accuracy/cost/latency) constraint bundles layered
25/// on top of the existing escalation knobs. A mode is a **resolver** over existing config,
26/// not a new engine — it overrides only the knobs it has an opinion on; everything else
27/// comes from the route/global config unchanged.
28///
29/// `Balanced` (the default) is a strict no-op: with no mode set anywhere, behaviour is
30/// byte-identical to existing behaviour. All other modes are opt-in overlays.
31///
32/// Set per-request via the `x-firstpass-mode` header, per-route via `routing_mode = "..."`,
33/// or globally via the `FIRSTPASS_MODE_PROFILE` env var.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
35#[serde(rename_all = "lowercase")]
36pub enum RoutingMode {
37    /// Forward without routing or gating; verdicts are asynchronous learning signals only.
38    /// Maps to the existing observe passthrough path. Zero added latency, zero quality proof.
39    Observe,
40    /// Prefer cheapest start; no speculative prefetch.
41    /// Tradeoff: lowest token spend; can serve lower quality on hard or heavy traffic.
42    Cost,
43    /// Today's default — bandit start, configured thresholds, configured speculation.
44    /// **This preset is a strict no-op: byte-identical to existing behaviour when applied.**
45    #[default]
46    Balanced,
47    /// One extra escalation rung allowed; serial (no speculative prefetch waste).
48    /// Tradeoff: higher quality ceiling at higher cost; still bounded by gate verification.
49    Quality,
50    /// `speculation = 1` always: always prefetch one rung ahead to cut p95 latency.
51    /// Tradeoff: pays 1 wasted speculative call when the cheap rung passes.
52    Latency,
53    /// Start at the top (most expensive) ladder rung; verification as insurance.
54    /// Tradeoff: highest quality, highest cost per call; bandit is bypassed; savings are minimal.
55    Max,
56}
57
58impl RoutingMode {
59    /// Lowercase string name, for use in headers and trace fields.
60    #[must_use]
61    pub fn as_str(self) -> &'static str {
62        match self {
63            Self::Observe => "observe",
64            Self::Cost => "cost",
65            Self::Balanced => "balanced",
66            Self::Quality => "quality",
67            Self::Latency => "latency",
68            Self::Max => "max",
69        }
70    }
71
72    /// All named modes in display order, for discovery surfaces (capabilities, MCP, CLI).
73    pub const ALL: &'static [Self] = &[
74        Self::Observe,
75        Self::Cost,
76        Self::Balanced,
77        Self::Quality,
78        Self::Latency,
79        Self::Max,
80    ];
81
82    /// The knob overrides this mode applies on top of the route/global escalation config.
83    /// `None` fields are left unchanged — modes only override where they have an opinion.
84    ///
85    /// **`Balanced` returns all `None`/`false`: it is a strict no-op by invariant.**
86    #[must_use]
87    pub fn preset(self) -> ModePreset {
88        match self {
89            // Observe: handled as a passthrough redirect before EnforceCtx; preset is unused.
90            Self::Observe => ModePreset {
91                speculation: None,
92                max_rungs_delta: None,
93                start_at_top: false,
94                description: "shadow mode: forward without gating; verdicts are async learning signals only",
95                tradeoff: "zero added latency, zero quality proof; use to observe before enforcing",
96            },
97            // Cost: kill speculative spend; let the bandit start cheap.
98            Self::Cost => ModePreset {
99                speculation: Some(0),
100                max_rungs_delta: None,
101                start_at_top: false,
102                description: "no speculative prefetch; bandit start on cheapest rung",
103                tradeoff: "lowest token spend; can serve lower quality on hard or heavy traffic",
104            },
105            // Balanced: all None — strict no-op so existing behaviour is preserved.
106            Self::Balanced => ModePreset {
107                speculation: None,
108                max_rungs_delta: None,
109                start_at_top: false,
110                description: "bandit start, configured thresholds and speculation (default — no behavioral change)",
111                tradeoff: "today's tuned balance; add a mode only when you need a different point",
112            },
113            // Quality: one more rung; no speculative waste.
114            Self::Quality => ModePreset {
115                speculation: Some(0),
116                max_rungs_delta: Some(1),
117                start_at_top: false,
118                description: "one extra escalation rung; serial (no speculative waste)",
119                tradeoff: "higher quality ceiling at higher cost; still bounded by gate verification",
120            },
121            // Latency: speculation=1 always; pay 1 wasted call to cut p95.
122            Self::Latency => ModePreset {
123                speculation: Some(1),
124                max_rungs_delta: None,
125                start_at_top: false,
126                description: "speculation=1: always prefetch one rung ahead to cut p95 latency",
127                tradeoff: "pays 1 wasted speculative call when cheap rung passes; speculation_band is overridden",
128            },
129            // Max: jump to top rung immediately; verification as insurance.
130            Self::Max => ModePreset {
131                speculation: Some(0),
132                max_rungs_delta: None,
133                start_at_top: true,
134                description: "start at the top (most expensive) ladder rung; verification as insurance",
135                tradeoff: "highest quality, highest cost per call; bandit bypassed; savings minimal",
136            },
137        }
138    }
139}
140
141/// Knob overrides a [`RoutingMode`] applies on top of the route/global escalation config.
142/// Only non-`None` fields override; absent fields leave the config value unchanged.
143///
144/// `Balanced` returns all `None`/`false` — it is a strict no-op.
145#[derive(Debug, Clone, Copy)]
146pub struct ModePreset {
147    /// Override for `escalation.speculation`. `None` = no override (config value unchanged).
148    pub speculation: Option<u32>,
149    /// Additive delta applied to `max_rungs_per_request`. `None` = no change.
150    /// Applied as `(current + delta).max(1)`.
151    pub max_rungs_delta: Option<i32>,
152    /// When `true`, start at the last ladder rung (top quality), bypassing the bandit.
153    pub start_at_top: bool,
154    /// One-line description of what this mode targets.
155    pub description: &'static str,
156    /// Honest tradeoff: what you gain and what you give up.
157    pub tradeoff: &'static str,
158}
159
160/// Top-level configuration document.
161#[derive(Debug, Clone, Default, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct Config {
164    /// Ordered routes; first match wins.
165    #[serde(rename = "route", default)]
166    pub routes: Vec<Route>,
167    /// Spend caps.
168    #[serde(default)]
169    pub budget: Budget,
170    /// Escalation limits and promotion rules.
171    #[serde(default)]
172    pub escalation: Escalation,
173    /// Served-failure guardrail (ADR 0009 D3). Absent (the default) means nothing watches the
174    /// served-failure rate and behaviour is byte-identical to before.
175    #[serde(default)]
176    pub guardrail: Option<crate::guardrail::Guardrail>,
177    /// Seconds a demoted route stays demoted before the guardrail will consider it again.
178    /// Deliberately long: re-promoting on one good window makes routing flap, and every flap is
179    /// a visible behaviour change for real users.
180    #[serde(default = "default_guardrail_cooldown")]
181    pub guardrail_cooldown_secs: i64,
182    /// User-defined subprocess gates (SPEC §8.1), referenced by `id` from a route's `gates` /
183    /// `deferred_gates`. Declared as `[[gate]]` sections in TOML.
184    #[serde(rename = "gate", default)]
185    pub gate_defs: Vec<GateDef>,
186    /// Per-deployment price overrides, replacing the built-in defaults for the named models.
187    /// List prices drift and enterprise contracts differ — savings math is only honest when the
188    /// operator can pin THEIR prices. Declared as `[[price]]` sections in TOML.
189    #[serde(rename = "price", default)]
190    pub price_defs: Vec<PriceDef>,
191    /// Extra model providers a ladder can route to, beyond the built-in `anthropic` / `openai`.
192    /// Any OpenAI-compatible endpoint (Groq, Together, Fireworks, DeepSeek, Mistral, xAI,
193    /// OpenRouter, Ollama, vLLM, Azure, …) is one `[[provider]]` entry — no rebuild. Declared as
194    /// `[[provider]]` sections; a ladder rung is then `<id>/<model>`.
195    #[serde(rename = "provider", default)]
196    pub providers: Vec<ProviderDef>,
197}
198
199/// The wire API a provider speaks. `anthropic` = Messages API; `openai` = Chat Completions API
200/// (the de-facto standard that nearly every hosted and open-source model host implements);
201/// `gemini` = Google's Generative Language API (`generateContent`).
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum Dialect {
205    /// Anthropic Messages API (`POST /v1/messages`).
206    Anthropic,
207    /// OpenAI Chat Completions API (`POST /v1/chat/completions`).
208    Openai,
209    /// Google Gemini Generative Language API (`POST /v1beta/models/<model>:generateContent`),
210    /// authenticated with an API key in the `x-goog-api-key` header.
211    Gemini,
212}
213
214/// How a provider call is credentialed — orthogonal to [`Dialect`] (ADR 0006): dialect shapes the
215/// request/response body, auth scheme shapes how the request is signed/credentialed. Default
216/// (`api_key_env` / BYOK header) is unchanged for every existing `[[provider]]` entry.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
218#[serde(rename_all = "snake_case")]
219pub enum AuthScheme {
220    /// API key in a header (`x-api-key`, `Authorization: Bearer`, or `x-goog-api-key`) — today's
221    /// behavior for `anthropic` / `openai` / `gemini`.
222    #[default]
223    ApiKey,
224    /// AWS SigV4 request signing (Bedrock) — credentials from `AWS_ACCESS_KEY_ID` /
225    /// `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`, region-scoped.
226    AwsSigv4,
227    /// GCP OAuth2 bearer token (Vertex AI) — minted and cached by `gcp_auth` from
228    /// `GOOGLE_APPLICATION_CREDENTIALS` or the ambient environment.
229    GcpOauth,
230}
231
232/// A model provider a ladder can route to. Declared as `[[provider]]` in TOML; referenced from a
233/// ladder as `<id>/<model>` (e.g. `groq/llama-3.3-70b-versatile`).
234#[derive(Debug, Clone, Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct ProviderDef {
237    /// Ladder prefix for this provider, e.g. `"groq"`. Overrides a built-in of the same id.
238    pub id: String,
239    /// Which wire API it speaks.
240    pub dialect: Dialect,
241    /// Base URL, e.g. `"https://api.groq.com/openai"` or `"http://localhost:11434"` for Ollama.
242    /// Unused for `aws_sigv4/gcp_oauth` auth (those construct the URL from `region`/`project`).
243    #[serde(default)]
244    pub base_url: String,
245    /// Env var the API key is read from at call time, e.g. `"GROQ_API_KEY"`. Omit for a keyless
246    /// endpoint (local Ollama / vLLM). Per-request BYOK headers still apply to the built-in
247    /// `anthropic` / `openai` providers.
248    #[serde(default)]
249    pub api_key_env: Option<String>,
250    /// How this provider's requests are credentialed. `api_key` (default) is byte-identical to
251    /// today; `aws_sigv4` / `gcp_oauth` are the Bedrock/Vertex auth schemes (ADR 0006).
252    #[serde(default)]
253    pub auth: AuthScheme,
254    /// Cloud region, e.g. `"us-east-1"` — required for `aws_sigv4` (Bedrock) and `gcp_oauth`
255    /// (Vertex).
256    #[serde(default)]
257    pub region: Option<String>,
258    /// GCP project id — required for `gcp_oauth` (Vertex).
259    #[serde(default)]
260    pub project: Option<String>,
261}
262
263/// A per-deployment price override for one model (`provider/model`), USD per 1M tokens.
264#[derive(Debug, Clone, Deserialize)]
265#[serde(deny_unknown_fields)]
266pub struct PriceDef {
267    /// The ladder id this price applies to, e.g. `"anthropic/claude-haiku-4-5"`.
268    pub model: String,
269    /// USD per 1M input (prompt) tokens.
270    pub input_per_mtok: f64,
271    /// USD per 1M output (completion) tokens.
272    pub output_per_mtok: f64,
273}
274
275/// A user-defined gate (SPEC §8.1). Exactly one kind per definition:
276/// - **subprocess** (`cmd`): any executable that reads the candidate as JSON on **stdin** (never
277///   argv — injection-resistant) and emits `{"verdict":"pass|fail|abstain", ...}` on stdout.
278/// - **judge** (`judge`): a native LLM-judge gate that grades the candidate against a rubric.
279/// - **consistency** (`consistency`): a self-consistency uncertainty gate that scores the
280///   candidate by agreement with k fresh samples of the same model (Wang et al. 2022).
281/// - **schema** (`schema`): validates the candidate (parsed as JSON) against a JSON-Schema
282///   subset (top-level `type` / `required` / per-property `type`).
283#[derive(Debug, Clone, Deserialize)]
284#[serde(deny_unknown_fields)]
285pub struct GateDef {
286    /// The id a route references this gate by (must be unique and not shadow a built-in gate id).
287    pub id: String,
288    /// Subprocess command: program first, then its args — e.g. `["pytest", "-q"]`. Set this **or**
289    /// `judge` / `consistency` / `schema`, not both.
290    #[serde(default)]
291    pub cmd: Vec<String>,
292    /// Hard timeout in milliseconds for a subprocess gate; it abstains (`timeout`) if the process
293    /// runs longer.
294    #[serde(default = "default_gate_timeout_ms")]
295    pub timeout_ms: u64,
296    /// LLM-judge configuration. Set this **or** `cmd` / `consistency` / `schema`, not both.
297    #[serde(default)]
298    pub judge: Option<JudgeDef>,
299    /// Self-consistency configuration. Set this **or** `cmd` / `judge` / `schema`, not both.
300    #[serde(default)]
301    pub consistency: Option<ConsistencyDef>,
302    /// JSON-Schema (subset) the candidate must satisfy. Set this **or** `cmd` / `judge` /
303    /// `consistency`, not both.
304    #[serde(default)]
305    pub schema: Option<serde_json::Value>,
306    /// What an **abstain** from this gate means for serving (§7.2). `fail_open` (default): an
307    /// abstaining gate never blocks serving — availability over strictness, today's behavior.
308    /// `fail_closed`: an abstain blocks serving exactly like a `Fail` — strictness over
309    /// availability, for gates whose silence must never be mistaken for approval.
310    #[serde(default)]
311    pub on_abstain: AbstainPolicy,
312}
313
314/// Per-gate abstain policy (§7.2): what happens to serving when the gate can't produce a verdict.
315#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
316#[serde(rename_all = "snake_case")]
317pub enum AbstainPolicy {
318    /// An abstain never blocks serving (the historical behavior).
319    #[default]
320    FailOpen,
321    /// An abstain blocks serving exactly like a `Fail`.
322    FailClosed,
323}
324
325/// Configuration for a native LLM-judge gate (SPEC §8.3): a separate model grades the candidate
326/// against a rubric. The runner enforces maker ≠ checker (a model never grades its own output) and
327/// treats the candidate as data, not instructions.
328#[derive(Debug, Clone, Deserialize)]
329#[serde(deny_unknown_fields)]
330pub struct JudgeDef {
331    /// The judge model, as `provider/model` (must differ from the candidate's model at runtime).
332    pub model: String,
333    /// Pass iff the judge's score ≥ this threshold, in `[0, 1]`.
334    #[serde(default = "default_judge_threshold")]
335    pub threshold: f64,
336    /// What "good" means for this route — handed to the judge as the grading rubric.
337    #[serde(default)]
338    pub rubric: Option<String>,
339}
340
341/// Configuration for a self-consistency uncertainty gate: resample the original request `k` times
342/// on the same model and score the candidate by agreement with the fresh samples.
343///
344/// Research basis: Wang et al. 2022 (self-consistency) and Farquhar et al., *Nature* 2024
345/// (semantic entropy). Answers a model reliably reproduces are far likelier correct; disagreement
346/// flags hallucination. This produces a continuous confidence score the conformal threshold
347/// machinery can calibrate.
348///
349/// **maker == checker is intentional** — unlike a judge gate, self-consistency is definitionally
350/// self-referential. This is the mechanism, not a bug.
351#[derive(Debug, Clone, Deserialize)]
352#[serde(deny_unknown_fields)]
353pub struct ConsistencyDef {
354    /// The model used for resampling, as `provider/model`. May equal the candidate's model —
355    /// self-consistency is self-referential by design.
356    pub model: String,
357    /// Number of resample calls. Must be in `[2, 8]`; defaults to `3`.
358    #[serde(default = "default_consistency_k")]
359    pub k: u32,
360    /// Pass iff the mean agreement score ≥ this threshold, in `[0, 1]`.
361    pub threshold: f64,
362}
363
364/// Default subprocess-gate timeout: 30s. Long enough for a test suite, short enough to bound the
365/// enforce-path tail.
366fn default_gate_timeout_ms() -> u64 {
367    30_000
368}
369
370/// Default judge pass threshold.
371fn default_judge_threshold() -> f64 {
372    0.7
373}
374
375/// Default self-consistency k (resample count).
376fn default_consistency_k() -> u32 {
377    3
378}
379
380/// One routing rule.
381#[derive(Debug, Clone, Deserialize)]
382#[serde(deny_unknown_fields)]
383pub struct Route {
384    /// The traffic this route claims. An empty match (`{}`) matches everything.
385    #[serde(rename = "match", default)]
386    pub match_: Match,
387    /// Serving mode.
388    pub mode: Mode,
389    /// Model ladder, cheapest first, as `provider/model` strings.
390    #[serde(default)]
391    pub ladder: Vec<String>,
392    /// Inline gates run before serving (enforce mode).
393    #[serde(default)]
394    pub gates: Vec<String>,
395    /// Gates run asynchronously after serving; their verdicts attach to the trace as a
396    /// learning signal and never block the response.
397    #[serde(default)]
398    pub deferred_gates: Vec<String>,
399    /// Per-route routing-mode preset. Overrides `FIRSTPASS_MODE_PROFILE`; overridden by the
400    /// per-request `x-firstpass-mode` header. Absent (default `None`) falls through to the
401    /// global default, then `Balanced` — byte-identical to existing behaviour.
402    #[serde(default)]
403    pub routing_mode: Option<RoutingMode>,
404    /// Percentage rollout (ADR 0009 D1): enforce only a slice of this route's matched traffic,
405    /// held constant per session so a conversation never flips arm mid-thread. Absent (the
406    /// default) enforces all matched traffic — byte-identical to existing behaviour.
407    #[serde(default)]
408    pub rollout: Option<crate::rollout::Rollout>,
409    /// Shadow scoring (ADR 0009 D2): on a sample of *observed* requests, run the ladder off the
410    /// hot path and record what would have been served and what it would have cost. Absent (the
411    /// default) leaves observe exactly as it was. Makes real model calls when enabled, which is
412    /// why `max_usd_per_day` is required rather than defaulted.
413    #[serde(default)]
414    pub shadow: Option<crate::rollout::Shadow>,
415}
416
417/// Predicate over a request's [`Features`]. Every present field is an AND-constraint; absent
418/// fields are wildcards.
419#[derive(Debug, Clone, Default, Deserialize)]
420#[serde(deny_unknown_fields)]
421pub struct Match {
422    /// Require a specific calling agent.
423    #[serde(default)]
424    pub agent: Option<String>,
425    /// Require the subagent to be one of these (or this one, if a bare string).
426    #[serde(default)]
427    pub subagent: Option<StringOrVec>,
428    /// Require a specific task kind.
429    #[serde(default)]
430    pub task_kind: Option<TaskKind>,
431    /// Require the language to be one of these (or this one, if a bare string).
432    #[serde(default)]
433    pub language: Option<StringOrVec>,
434}
435
436impl Match {
437    /// Whether `f` satisfies every present constraint.
438    #[must_use]
439    pub fn matches(&self, f: &Features) -> bool {
440        if let Some(agent) = &self.agent
441            && f.agent.as_deref() != Some(agent.as_str())
442        {
443            return false;
444        }
445        if let Some(subs) = &self.subagent {
446            match &f.subagent {
447                Some(s) if subs.contains(s) => {}
448                _ => return false,
449            }
450        }
451        if let Some(tk) = self.task_kind
452            && f.task_kind != tk
453        {
454            return false;
455        }
456        if let Some(langs) = &self.language {
457            match &f.language {
458                Some(l) if langs.contains(l) => {}
459                _ => return false,
460            }
461        }
462        true
463    }
464}
465
466/// A field that accepts either a single string or a list of strings in TOML/JSON.
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468#[serde(untagged)]
469pub enum StringOrVec {
470    /// A single value.
471    One(String),
472    /// A set of values.
473    Many(Vec<String>),
474}
475
476impl StringOrVec {
477    /// Whether `needle` is contained in this value.
478    #[must_use]
479    pub fn contains(&self, needle: &str) -> bool {
480        match self {
481            StringOrVec::One(s) => s == needle,
482            StringOrVec::Many(v) => v.iter().any(|s| s == needle),
483        }
484    }
485}
486
487/// What to do when a spend cap is hit (SPEC §8.4 — never brick the customer).
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
489#[serde(rename_all = "snake_case")]
490pub enum OnExhausted {
491    /// Serve the best attempt seen so far (default).
492    #[default]
493    ServeBestAttempt,
494    /// Return a structured error instead of serving.
495    Error,
496}
497
498/// Spend caps. `None` means "no cap".
499#[derive(Debug, Clone, Default, Deserialize)]
500#[serde(deny_unknown_fields)]
501pub struct Budget {
502    /// Max USD per single request (across all rungs + gates).
503    #[serde(default)]
504    pub per_request_usd: Option<f64>,
505    /// Max USD per session.
506    #[serde(default)]
507    pub per_session_usd: Option<f64>,
508    /// Max USD per day.
509    #[serde(default)]
510    pub per_day_usd: Option<f64>,
511    /// Behaviour when a cap is reached.
512    #[serde(default)]
513    pub on_exhausted: OnExhausted,
514}
515
516/// Escalation limits and session-level promotion.
517#[derive(Debug, Clone, Deserialize)]
518#[serde(deny_unknown_fields)]
519pub struct Escalation {
520    /// Hard ceiling on rungs climbed within one request.
521    #[serde(default = "default_max_rungs")]
522    pub max_rungs_per_request: u32,
523    /// Optionally start higher for the rest of a session that keeps failing.
524    #[serde(default)]
525    pub session_promotion: Option<SessionPromotion>,
526    /// Prefetch depth: fire this many rungs ahead concurrently to trade wasted spend for latency.
527    /// `0` (default) is serial — one call at a time. The served result is identical either way.
528    #[serde(default)]
529    pub speculation: u32,
530    /// Calibrated conformal serve threshold: a rung is served iff its aggregate gate score is
531    /// `>=` this value (SPEC §10.1). `None` (default) keeps the original rule — serve iff the
532    /// aggregate gate verdict is `Pass` — byte-identical to today.
533    #[serde(default)]
534    pub serve_threshold: Option<f64>,
535    /// Online/adaptive conformal (Gibbs-Candès ACI): when set, the serve threshold is tracked
536    /// **live** from deferred feedback instead of held fixed, so served-failure stays at target under
537    /// distribution shift. `None` (default) uses the fixed `serve_threshold` above — byte-identical.
538    #[serde(default)]
539    pub adaptive: Option<AdaptiveConfig>,
540    /// Anytime-valid risk control (ADR 0011). Takes precedence over `adaptive` once it certifies.
541    #[serde(default)]
542    pub eprocess: Option<EProcessConfig>,
543    /// Route tool-calling / multimodal requests through enforce (ADR 0005). **Default `true`**:
544    /// agent traffic — the target workload — is gated out of the box. A per-request fidelity
545    /// guard still applies: structured content only routes when every ladder rung's provider
546    /// carries it verbatim (Anthropic-dialect today); otherwise the request falls back to
547    /// transparent observe passthrough rather than risking corruption. Set `false` to restore
548    /// the pre-ADR-0005 behavior (structured requests always pass through un-gated).
549    #[serde(default = "default_enforce_structured")]
550    pub enforce_structured: bool,
551    /// UCB1 start-rung bandit: learn which rung to START the ladder on per request context, to
552    /// cut expected cost by skipping rungs that almost always fail for this context. `None`
553    /// (default) starts every request at rung 0 — byte-identical to today. Prediction may only
554    /// choose where the ladder STARTS; gating, escalation, and serving are untouched.
555    #[serde(default)]
556    pub bandit: Option<BanditConfig>,
557    /// Last-resort context condensing. `None` (default) = a conversation that overflows every
558    /// rung's context window fails, which is today's behaviour.
559    ///
560    /// Deliberately not a general trimming knob: condensing routinely would mean the gate verifies
561    /// an answer produced from a prompt the client never sent, and the receipt would attest to a
562    /// decision about a different question than the one asked. This fires only once the ladder is
563    /// exhausted, where the choice is no longer "faithful vs degraded" but "degraded vs failed".
564    #[serde(default)]
565    pub condense: Option<CondenseConfig>,
566    /// Insert Anthropic prompt-cache breakpoints on the stable prefix (system + tools).
567    /// `false` (default) = today's behaviour: whatever the caller sent, unchanged.
568    ///
569    /// Opt-in because it is a bet on your traffic, not a free optimisation. A cache write costs
570    /// 1.25x base input and a read 0.1x, so roughly one reuse of the prefix covers the premium and
571    /// everything after it saves heavily. A long agent session with a fixed system prompt and tool
572    /// set reuses constantly; single-shot traffic never does, and pays a 25% surcharge on the
573    /// prefix for nothing.
574    #[serde(default)]
575    pub prompt_cache: bool,
576    /// Replay a previously **verified** answer for an identical prompt, skipping the ladder
577    /// entirely. `None` (default) = every request runs the ladder, byte-identical to today.
578    ///
579    /// Unlike an ordinary response cache, an entry is written only when the receipt shows the
580    /// request was served on a passing verdict — so a hit cannot serve something that was never
581    /// proven. The receipt records `served_from: cache` and `cache_source`, naming the decision
582    /// whose gate passed.
583    #[serde(default)]
584    pub verified_cache: Option<VerifiedCacheConfig>,
585    /// Speculative-deferral band: when set (and the bandit has a warm gate-pass estimate for
586    /// the chosen start rung), speculative prefetch fires **only** when that estimate falls
587    /// inside `[low, high]` — the marginal zone where the next rung is *probably but not
588    /// certainly* needed, which is where parallel spend buys the most latency (speculative
589    /// cascades). Outside the band (confident pass or confident fail-through) requests run
590    /// serial and the speculative tokens are saved. `None` (default) = `speculation` applies
591    /// unconditionally, byte-identical to today. No bandit / cold context ⇒ band inapplicable
592    /// ⇒ configured `speculation` applies.
593    #[serde(default)]
594    pub speculation_band: Option<[f64; 2]>,
595    /// Epsilon-greedy start-rung exploration: randomise a fraction of start-rung choices and
596    /// record propensities so IPS/SNIPS off-policy estimates are valid. `None` (default) →
597    /// deterministic policy — byte-identical to today. See [`ExplorationConfig`].
598    #[serde(default)]
599    pub exploration: Option<ExplorationConfig>,
600    /// Shadow probe (ADR 0008 Phase 1): measure the k-sample gate-pass-count signal on a
601    /// sampled fraction of enforce requests without changing serving or the served cost.
602    /// `None` (default) = off = zero extra provider calls = byte-identical to today.
603    #[serde(default)]
604    pub probe: Option<ProbeConfig>,
605    /// Per-query gate-pass predictor (ADR 0008 Phase 2): a learned `P(gate-pass | rung,
606    /// features)` model, trained online from receipts and recorded on the receipt in shadow.
607    /// `None` (default) = off = byte-identical to today (no predictor, no `predicted_pass`).
608    #[serde(default)]
609    pub predictor: Option<PredictorConfig>,
610    /// Elastic verification (ADR 0008 Phase 3): skip the named expensive gates on a serve when the
611    /// cheap **visible** gate score clears the conformally-calibrated threshold λ. `None` (default)
612    /// runs every gate on every serve — byte-identical to today's uniform verification. See
613    /// [`ElasticConfig`].
614    #[serde(default)]
615    pub elastic: Option<ElasticConfig>,
616}
617
618/// Per-query gate-pass predictor configuration (ADR 0008 Phase 2). The model is an online
619/// logistic regression (`firstpass_core::predictor::PassPredictor`) trained from the trace
620/// store. Its prediction is recorded on the receipt in **shadow** — it does not change routing
621/// in this phase; whether it is good enough to act on is decided offline (`firstpass
622/// predictor-eval`).
623#[derive(Debug, Clone, Copy, Deserialize)]
624#[serde(deny_unknown_fields)]
625pub struct PredictorConfig {
626    /// SGD learning rate, in `(0, 1]`. Validated by [`Config::parse`].
627    #[serde(default = "default_predictor_lr")]
628    pub lr: f64,
629    /// L2 shrinkage on the weights (bias excluded), `>= 0`. Validated by [`Config::parse`].
630    #[serde(default = "default_predictor_l2")]
631    pub l2: f64,
632}
633
634fn default_predictor_lr() -> f64 {
635    0.05
636}
637
638fn default_predictor_l2() -> f64 {
639    1e-4
640}
641
642/// Config for anytime-valid risk control ([`crate::eprocess::EProcessRiskControl`], ADR 0011).
643///
644/// Opt-in and additive. Absent, the router behaves exactly as before. Present, the certified
645/// threshold takes precedence over `[escalation.adaptive]` **once something is certified** — before
646/// that it contributes nothing, because a controller that has proven nothing must not hand out a
647/// number.
648#[derive(Debug, Clone, Deserialize)]
649#[serde(deny_unknown_fields)]
650pub struct EProcessConfig {
651    /// Target served-failure rate the bound holds to.
652    pub alpha: f64,
653    /// Family-wise error budget, across every grid threshold and every round jointly.
654    pub delta: f64,
655    /// Betting fraction. Clamped internally so a large value cannot annihilate a threshold.
656    #[serde(default = "default_bet")]
657    pub bet: f64,
658    /// Candidate thresholds. Kept small on purpose: the Bonferroni crossing level is `n/delta`, so
659    /// evidence required per threshold grows linearly in grid size.
660    #[serde(default = "default_grid")]
661    pub grid: Vec<f64>,
662}
663
664fn default_bet() -> f64 {
665    0.5
666}
667
668/// A 21-point grid over `[0,1]`. Fine enough to pick a useful threshold, coarse enough that the
669/// Bonferroni correction stays affordable.
670fn default_grid() -> Vec<f64> {
671    (0..=20).map(|i| f64::from(i) / 20.0).collect()
672}
673
674/// Config for online/adaptive conformal serving ([`crate::conformal::AdaptiveConformal`]).
675#[derive(Debug, Clone, Deserialize)]
676#[serde(deny_unknown_fields)]
677pub struct AdaptiveConfig {
678    /// Target served-failure rate the online loop holds to.
679    pub alpha: f64,
680    /// Step size (default 0.02) — larger tracks shift faster but noisier.
681    #[serde(default = "default_adaptive_gamma")]
682    pub gamma: f64,
683}
684
685fn default_adaptive_gamma() -> f64 {
686    0.02
687}
688
689/// Epsilon-greedy start-rung exploration: a fraction `epsilon` of requests start at a
690/// uniformly-random rung so that propensities are logged and IPS/SNIPS off-policy estimates
691/// are valid (Horvitz-Thompson 1952; SNIPS: Swaminathan & Joachims 2015). The bandit still
692/// observes all gate verdicts — including from exploration draws — so learning is uninterrupted.
693///
694/// Every request under this policy records `policy.propensity` in the trace: the probability the
695/// logging policy had of choosing the start rung it actually chose. Old traces (before this field
696/// was added) serialize byte-identically (propensity is omitted when `None`).
697///
698/// Absent (default) → deterministic policy — no exploration, no propensity recorded,
699/// byte-identical to today.
700#[derive(Debug, Clone, Deserialize)]
701#[serde(deny_unknown_fields)]
702pub struct ExplorationConfig {
703    /// Fraction of requests routed to a uniformly-random start rung instead of the greedy
704    /// choice. Must be finite and in `(0, 0.5]`; validated by [`Config::parse`].
705    /// A small `epsilon` (0.05–0.1) is usually enough: it keeps learning alive and makes
706    /// IPS/SNIPS estimates valid at low cost in exploration waste.
707    pub epsilon: f64,
708}
709
710/// Shadow-probe configuration (ADR 0008 Phase 1): measure the validated k-sample
711/// gate-pass-count signal on a sampled fraction of requests WITHOUT changing serving.
712///
713/// **Cost caveat**: `sample_rate × k` extra model calls (at the `start_rung` model) per
714/// sampled request — measurement only, nothing served changes. Default absent = off = zero
715/// extra provider calls, byte-identical to today. Enable only when you want to collect the
716/// regime signal for offline analysis.
717#[derive(Debug, Clone, Copy, Deserialize)]
718#[serde(deny_unknown_fields)]
719pub struct ProbeConfig {
720    /// Number of parallel probe samples per request. Must be in `[2, 8]`; validated by
721    /// [`Config::parse`]. Each sample is one model call at the `start_rung` model.
722    pub k: u32,
723    /// Fraction of requests that trigger the probe, in `[0, 1]`. `0.0` = never; `1.0` = always.
724    /// Must be finite; validated by [`Config::parse`].
725    pub sample_rate: f64,
726}
727
728/// Elastic-verification serving config (ADR 0008 Phase 3). When present, the gates named in
729/// `expensive_gates` are treated as *skippable*: a rung serves without running them when the
730/// **visible** (cheap, always-run) gate score is `>= lambda` — the elastic three-regime rule,
731/// validated offline (`firstpass-bench --elastic`, artifact `docs/benchmarks/elastic-validation.txt`).
732///
733/// The load-bearing invariant (ADR 0008): the un-verified serves carry the *same* distribution-free
734/// served-failure bound as the verified ones **only when `lambda` was conformally calibrated on
735/// representative data and the workload has not drifted**. `lambda` is therefore operator-supplied
736/// from a calibration run — obtain it from `firstpass calibrate` / the offline `--elastic` harness,
737/// never hand-tuned. `alpha`/`delta`/`calibration_id` are recorded verbatim on every skip receipt so
738/// an auditor can check the bound held against realized deferred outcomes.
739///
740/// Default-off: absent config = today's uniform cascade, byte-identical. Applies to the serial
741/// engine only; if `speculation > 0` is also configured the expensive gates still run (conservative
742/// — running more gates never weakens the bound).
743#[derive(Debug, Clone, Deserialize, PartialEq)]
744#[serde(deny_unknown_fields)]
745pub struct ElasticConfig {
746    /// Gate ids that may be skipped when the visible signal clears `lambda`. Ids **not** listed
747    /// here are "visible" (cheap, e.g. `non-empty`/`json-valid`/`schema`) and always run — they are
748    /// the probe signal. Must be non-empty; validated by [`Config::parse`].
749    pub expensive_gates: Vec<String>,
750    /// Calibrated skip threshold λ: serve without the expensive gates iff the visible gate score is
751    /// `>= lambda`. Must be finite and in `[0, 1]`; validated by [`Config::parse`].
752    pub lambda: f64,
753    /// Target served-failure rate α the λ was calibrated at. Recorded on every skip receipt for
754    /// audit; not enforced per-request (the calibration already baked it into λ).
755    #[serde(default)]
756    pub alpha: Option<f64>,
757    /// Confidence level (1−δ) the λ was calibrated at. Recorded on every skip receipt for audit.
758    #[serde(default)]
759    pub delta: Option<f64>,
760    /// Provenance id of the calibration run that produced λ. Recorded on every skip receipt so the
761    /// skip traces back to the exact conformal calibration that authorized it.
762    #[serde(default)]
763    pub calibration_id: Option<String>,
764}
765
766/// Last-resort context condensing (§8.4). See [`Escalation::condense`].
767#[derive(Debug, Clone, Deserialize)]
768#[serde(deny_unknown_fields)]
769pub struct CondenseConfig {
770    /// Opening turns to keep — usually where the task definition lives.
771    #[serde(default = "default_condense_keep_head")]
772    pub keep_head: usize,
773    /// Closing turns to keep — the live thread.
774    #[serde(default = "default_condense_keep_tail")]
775    pub keep_tail: usize,
776}
777
778const fn default_condense_keep_head() -> usize {
779    2
780}
781
782const fn default_condense_keep_tail() -> usize {
783    6
784}
785
786/// Verified-response cache (§8.4). See [`Escalation::verified_cache`].
787#[derive(Debug, Clone, Deserialize)]
788#[serde(deny_unknown_fields)]
789pub struct VerifiedCacheConfig {
790    /// How long a proven answer stays replayable.
791    ///
792    /// A proof has a shelf life: the model, the gate, and the world all move. Short by default
793    /// because replaying a stale answer confidently is worse than paying to re-derive it.
794    #[serde(default = "default_cache_ttl_secs")]
795    pub ttl_secs: u64,
796    /// Hard cap on entries; oldest evicted first. In-process store only — a Redis-backed cache is
797    /// bounded by its TTL and the server's own eviction policy.
798    #[serde(default = "default_cache_max_entries")]
799    pub max_entries: usize,
800    /// Redis URL for a **shared** cache across replicas. Absent (default) = in-process only.
801    ///
802    /// Without it the cache is per-replica: behind N instances the same answer is cached N times
803    /// over, the hit rate drops roughly by N, and — the part that matters — a retraction only
804    /// reaches the replica that received the feedback, leaving the other N-1 serving an answer
805    /// that has been disproven.
806    ///
807    /// Requires the `redis-cache` build feature. Configuring a URL without it is rejected at
808    /// startup rather than silently ignored: a cache that quietly stays per-replica looks
809    /// identical to one that is working.
810    #[serde(default)]
811    pub redis_url: Option<String>,
812}
813
814const fn default_cache_ttl_secs() -> u64 {
815    15 * 60
816}
817
818const fn default_cache_max_entries() -> usize {
819    10_000
820}
821
822/// Config for the UCB1 start-rung bandit (`firstpass_proxy::bandit::StartRungBandit`).
823///
824/// Absent (`None`) → start every request at rung 0 (byte-identical to today).
825#[derive(Debug, Clone, Deserialize)]
826#[serde(deny_unknown_fields)]
827pub struct BanditConfig {
828    /// Minimum total gate-verdict observations in a context bucket before the bandit's
829    /// prediction kicks in. Below this, every request starts at rung 0 (cold-start safety).
830    #[serde(default = "default_bandit_min_observations")]
831    pub min_observations: usize,
832    /// UCB1 exploration constant `c` (Auer et al. 2002). Higher values explore more; 1.0 is the
833    /// theoretical default. Must be finite and `>= 0`; validated by [`Config::parse`].
834    #[serde(default = "default_bandit_exploration")]
835    pub exploration: f64,
836    /// Selection algorithm. `"ucb1"` (default) is deterministic and auditable; `"thompson"`
837    /// samples Beta posteriors — stochastic by nature, so every decision logs a non-degenerate
838    /// propensity (clean IPS/SNIPS/DR off-policy estimates without the epsilon overlay) and
839    /// pairs with `discount` for non-stationary traffic.
840    #[serde(default)]
841    pub algorithm: BanditAlgorithm,
842    /// Per-observation multiplicative decay of a context's counts, in `(0, 1]`. `1.0`
843    /// (default) = no forgetting. `0.99` adapts to model churn / workload drift at the cost
844    /// of a slightly noisier estimate. Validated by [`Config::parse`].
845    #[serde(default = "default_bandit_discount")]
846    pub discount: f64,
847}
848
849/// Start-rung bandit selection algorithm.
850#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
851#[serde(rename_all = "lowercase")]
852pub enum BanditAlgorithm {
853    /// Deterministic UCB1 (Auer et al. 2002).
854    #[default]
855    Ucb1,
856    /// Thompson sampling with Beta posteriors (Chapelle & Li 2011).
857    Thompson,
858}
859
860fn default_bandit_discount() -> f64 {
861    1.0
862}
863
864fn default_bandit_min_observations() -> usize {
865    50
866}
867
868fn default_bandit_exploration() -> f64 {
869    1.0
870}
871
872const fn default_max_rungs() -> u32 {
873    3
874}
875
876/// Structured (tools/images) enforce is on by default — the fidelity guard in the proxy keeps
877/// it safe (verbatim-carry rungs only).
878fn default_enforce_structured() -> bool {
879    true
880}
881
882impl Default for Escalation {
883    fn default() -> Self {
884        Self {
885            max_rungs_per_request: default_max_rungs(),
886            session_promotion: None,
887            speculation: 0,
888            serve_threshold: None,
889            adaptive: None,
890            eprocess: None,
891            enforce_structured: default_enforce_structured(),
892            speculation_band: None,
893            bandit: None,
894            condense: None,
895            prompt_cache: false,
896            verified_cache: None,
897            exploration: None,
898            probe: None,
899            predictor: None,
900            elastic: None,
901        }
902    }
903}
904
905/// "After N failures within a window, promote this session's starting rung."
906#[derive(Debug, Clone, Deserialize)]
907#[serde(deny_unknown_fields)]
908pub struct SessionPromotion {
909    /// Failure count that triggers promotion.
910    pub after_failures: u32,
911    /// Sliding window, e.g. `"30m"`. Also the idle TTL: a session untouched for this long forgets
912    /// its promotion, so a reused session id never inherits a stale rung.
913    pub window: String,
914    /// Re-probe one rung below the promotion every `probe_every` turns.
915    ///
916    /// Without this, promotion is a **ratchet**: a session that escalates once stays expensive for
917    /// its whole life, so every later turn — including the trivial ones — pays the higher rung.
918    /// The periodic probe is the only way a promotion comes back down. `1` re-probes every turn
919    /// (promotion effectively off); large values approach a permanent ratchet.
920    #[serde(default = "default_promotion_probe_every")]
921    pub probe_every: u32,
922    /// Hard cap on tracked sessions; oldest evicted first. A routing optimisation must never be
923    /// able to exhaust memory on a proxy under load. In-process only — a Redis-backed store is
924    /// bounded by its TTL and the server's own eviction policy, and a per-replica cap on a shared
925    /// store would have each replica evicting the others' sessions.
926    #[serde(default = "default_promotion_max_sessions")]
927    pub max_sessions: usize,
928    /// Redis URL for promotion state shared across replicas. Absent (default) = in-process only.
929    ///
930    /// Without it, promotion fragments behind a load balancer: a session that escalated on one
931    /// replica starts cold on the next, so the escalation tax this exists to remove is paid again
932    /// on roughly (N-1)/N of turns — configured, reporting nothing wrong, doing a fraction of its
933    /// job. Requires the `redis-cache` build feature.
934    #[serde(default)]
935    pub redis_url: Option<String>,
936}
937
938const fn default_promotion_probe_every() -> u32 {
939    // Every 5th turn probes one rung down: quick enough to recover from an over-promotion, rare
940    // enough that the escalation tax is still mostly avoided.
941    5
942}
943
944const fn default_promotion_max_sessions() -> usize {
945    10_000
946}
947
948impl SessionPromotion {
949    /// Parse [`SessionPromotion::window`] into a [`Duration`].
950    ///
951    /// # Errors
952    /// Returns [`Error::BadDuration`] if the window is not `<int><unit>` with unit in `s`/`m`/`h`/`d`.
953    pub fn window_duration(&self) -> Result<Duration> {
954        parse_window(&self.window)
955    }
956}
957
958/// Parse a compact duration like `30m`, `2h`, `90s`, `1d`.
959fn parse_window(s: &str) -> Result<Duration> {
960    let s = s.trim();
961    let split = s
962        .find(|c: char| c.is_ascii_alphabetic())
963        .ok_or_else(|| Error::BadDuration(s.to_owned()))?;
964    let (num, unit) = s.split_at(split);
965    let n: u64 = num
966        .trim()
967        .parse()
968        .map_err(|_| Error::BadDuration(s.to_owned()))?;
969    let secs = match unit {
970        "s" => n,
971        "m" => n.saturating_mul(60),
972        "h" => n.saturating_mul(3600),
973        "d" => n.saturating_mul(86_400),
974        _ => return Err(Error::BadDuration(s.to_owned())),
975    };
976    Ok(Duration::from_secs(secs))
977}
978
979/// A parsed `provider/model` reference.
980#[derive(Debug, Clone, PartialEq, Eq)]
981pub struct ModelRef {
982    /// Provider segment, e.g. `anthropic`.
983    pub provider: String,
984    /// Model segment, e.g. `claude-haiku-4-5`.
985    pub model: String,
986}
987
988impl ModelRef {
989    /// Parse a `provider/model` string.
990    ///
991    /// # Errors
992    /// Returns [`Error::BadModelRef`] if the input is not exactly one `provider/model` pair.
993    pub fn parse(s: &str) -> Result<Self> {
994        match s.split_once('/') {
995            Some((p, m)) if !p.is_empty() && !m.is_empty() && !m.contains('/') => Ok(Self {
996                provider: p.to_owned(),
997                model: m.to_owned(),
998            }),
999            _ => Err(Error::BadModelRef(s.to_owned())),
1000        }
1001    }
1002}
1003
1004const fn default_guardrail_cooldown() -> i64 {
1005    3_600
1006}
1007
1008impl Config {
1009    /// Parse a TOML configuration document.
1010    ///
1011    /// # Errors
1012    /// Returns [`Error::Config`] on invalid TOML or unknown fields, or [`Error::InvalidConfig`] on
1013    /// an invalid gate definition (not exactly one of `cmd`/`judge`, a judge threshold outside
1014    /// `[0,1]`, or a duplicate/blank `id`).
1015    pub fn parse(toml_str: &str) -> Result<Self> {
1016        let config: Self = toml::from_str(toml_str)?;
1017        // A nonsensical rollout percent must fail loudly at parse: silently clamping it would
1018        // ramp a different amount of traffic than the operator asked for, and they would only
1019        // notice via a savings figure that never moved.
1020        for (i, route) in config.routes.iter().enumerate() {
1021            if let Some(r) = &route.rollout {
1022                r.validate()
1023                    .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
1024            }
1025            if let Some(sh) = &route.shadow {
1026                sh.validate()
1027                    .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
1028            }
1029        }
1030        if let Some(g) = &config.guardrail {
1031            g.validate().map_err(Error::InvalidConfig)?;
1032        }
1033        if let Some(p) = &config.escalation.session_promotion {
1034            // `window` is also the idle TTL, so an unparseable one would silently disable expiry.
1035            p.window_duration()?;
1036            // probe_every = 0 would make promotion one-way: a session that escalated once stays on
1037            // the expensive rung for its whole life, including the trivial turns at the end. That
1038            // is a cost regression an operator would only find in a bill, so it is rejected here
1039            // rather than quietly coerced to something they did not ask for.
1040            if p.probe_every == 0 {
1041                return Err(Error::InvalidConfig(
1042                    "[escalation.session_promotion] probe_every must be >= 1. It is how a promoted \
1043                     session ever returns to a cheaper rung; 0 would pin it permanently."
1044                        .to_owned(),
1045                ));
1046            }
1047            if p.max_sessions == 0 {
1048                return Err(Error::InvalidConfig(
1049                    "[escalation.session_promotion] max_sessions must be >= 1".to_owned(),
1050                ));
1051            }
1052        }
1053        let mut seen = std::collections::HashSet::new();
1054        for def in &config.gate_defs {
1055            if def.id.trim().is_empty() {
1056                return Err(Error::InvalidConfig("gate id must not be empty".to_owned()));
1057            }
1058            // Exactly one kind: `cmd`, `judge`, `consistency`, or `schema` — never more, never none.
1059            let kinds_set = [
1060                !def.cmd.is_empty(),
1061                def.judge.is_some(),
1062                def.consistency.is_some(),
1063                def.schema.is_some(),
1064            ]
1065            .iter()
1066            .filter(|&&b| b)
1067            .count();
1068            if kinds_set != 1 {
1069                return Err(Error::InvalidConfig(format!(
1070                    "gate {:?} must set exactly one of `cmd`, `judge`, `consistency`, or `schema`",
1071                    def.id
1072                )));
1073            }
1074            if let Some(judge) = &def.judge
1075                && !(0.0..=1.0).contains(&judge.threshold)
1076            {
1077                return Err(Error::InvalidConfig(format!(
1078                    "gate {:?} judge threshold {} is outside [0, 1]",
1079                    def.id, judge.threshold
1080                )));
1081            }
1082            if let Some(c) = &def.consistency {
1083                if !(2..=8).contains(&c.k) {
1084                    return Err(Error::InvalidConfig(format!(
1085                        "gate {:?} consistency k {} is outside [2, 8]",
1086                        def.id, c.k
1087                    )));
1088                }
1089                if !(0.0..=1.0).contains(&c.threshold) {
1090                    return Err(Error::InvalidConfig(format!(
1091                        "gate {:?} consistency threshold {} is outside [0, 1]",
1092                        def.id, c.threshold
1093                    )));
1094                }
1095            }
1096            if !seen.insert(def.id.as_str()) {
1097                return Err(Error::InvalidConfig(format!(
1098                    "duplicate gate id {:?}",
1099                    def.id
1100                )));
1101            }
1102        }
1103        for price in &config.price_defs {
1104            if price.model.trim().is_empty() {
1105                return Err(Error::InvalidConfig(
1106                    "price model must not be empty".to_owned(),
1107                ));
1108            }
1109            let ok = |v: f64| v.is_finite() && v >= 0.0;
1110            if !ok(price.input_per_mtok) || !ok(price.output_per_mtok) {
1111                return Err(Error::InvalidConfig(format!(
1112                    "price for {:?} must be finite and >= 0",
1113                    price.model
1114                )));
1115            }
1116        }
1117        config.validate_ladders_are_priced()?;
1118        if let Some(b) = &config.escalation.bandit {
1119            if !b.exploration.is_finite() || b.exploration < 0.0 {
1120                return Err(Error::InvalidConfig(format!(
1121                    "bandit.exploration must be finite and >= 0, got {}",
1122                    b.exploration
1123                )));
1124            }
1125            if !b.discount.is_finite() || b.discount <= 0.0 || b.discount > 1.0 {
1126                return Err(Error::InvalidConfig(format!(
1127                    "bandit.discount must be in (0, 1], got {}",
1128                    b.discount
1129                )));
1130            }
1131        }
1132        if let Some([lo, hi]) = config.escalation.speculation_band {
1133            let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v);
1134            if !ok(lo) || !ok(hi) || lo > hi {
1135                return Err(Error::InvalidConfig(format!(
1136                    "escalation.speculation_band must satisfy 0 <= low <= high <= 1, got [{lo}, {hi}]"
1137                )));
1138            }
1139        }
1140        // An out-of-range e-process grid must be REJECTED, not silently filtered.
1141        // `EProcessRiskControl::new` drops non-finite entries so a bad grid cannot panic, but
1142        // dropping is the wrong contract for config: an operator who writes a grid of `[2.0, 3.0]`
1143        // gets an empty grid, which certifies nothing, and the report then reads "no threshold
1144        // certified" — indistinguishable from insufficient data. Same failure shape as the
1145        // Bonferroni collapse in ADR 0011, arriving through a typo instead. Flagged in review.
1146        if let Some(ep) = &config.escalation.eprocess {
1147            if !ep.alpha.is_finite() || ep.alpha <= 0.0 || ep.alpha >= 1.0 {
1148                return Err(Error::InvalidConfig(format!(
1149                    "escalation.eprocess.alpha must be finite and in (0, 1), got {}",
1150                    ep.alpha
1151                )));
1152            }
1153            if !ep.delta.is_finite() || ep.delta <= 0.0 || ep.delta >= 1.0 {
1154                return Err(Error::InvalidConfig(format!(
1155                    "escalation.eprocess.delta must be finite and in (0, 1), got {}",
1156                    ep.delta
1157                )));
1158            }
1159            // `bet` completes the set. The runtime clamps it to a safe range so it cannot
1160            // annihilate a threshold, but clamping is not validation: `bet = 0.0` clamps to 0.0,
1161            // the betting factor becomes exactly 1 on every update, the e-value never moves, and
1162            // NOTHING can ever certify. Silent and permanent — the same "reads as insufficient
1163            // data" failure as an empty grid. I validated alpha, delta and grid and left this one,
1164            // which review caught.
1165            if !ep.bet.is_finite() || ep.bet <= 0.0 || ep.bet > 1.0 {
1166                return Err(Error::InvalidConfig(format!(
1167                    "escalation.eprocess.bet must be finite and in (0, 1], got {}",
1168                    ep.bet
1169                )));
1170            }
1171            if ep.grid.is_empty() {
1172                return Err(Error::InvalidConfig(
1173                    "escalation.eprocess.grid must not be empty — an empty grid certifies nothing"
1174                        .to_owned(),
1175                ));
1176            }
1177            if let Some(bad) = ep
1178                .grid
1179                .iter()
1180                .find(|g| !g.is_finite() || **g < 0.0 || **g > 1.0)
1181            {
1182                return Err(Error::InvalidConfig(format!(
1183                    "escalation.eprocess.grid values must be finite and in [0, 1], got {bad}"
1184                )));
1185            }
1186        }
1187        if let Some(exp) = &config.escalation.exploration
1188            && (!exp.epsilon.is_finite() || exp.epsilon <= 0.0 || exp.epsilon > 0.5)
1189        {
1190            return Err(Error::InvalidConfig(format!(
1191                "escalation.exploration.epsilon must be finite and in (0, 0.5], got {}",
1192                exp.epsilon
1193            )));
1194        }
1195        if let Some(probe) = &config.escalation.probe {
1196            if !(2..=8).contains(&probe.k) {
1197                return Err(Error::InvalidConfig(format!(
1198                    "escalation.probe.k must be in [2, 8], got {}",
1199                    probe.k
1200                )));
1201            }
1202            if !probe.sample_rate.is_finite() || !(0.0..=1.0).contains(&probe.sample_rate) {
1203                return Err(Error::InvalidConfig(format!(
1204                    "escalation.probe.sample_rate must be finite and in [0, 1], got {}",
1205                    probe.sample_rate
1206                )));
1207            }
1208        }
1209        if let Some(pred) = &config.escalation.predictor {
1210            if !pred.lr.is_finite() || !(0.0..=1.0).contains(&pred.lr) || pred.lr == 0.0 {
1211                return Err(Error::InvalidConfig(format!(
1212                    "escalation.predictor.lr must be finite and in (0, 1], got {}",
1213                    pred.lr
1214                )));
1215            }
1216            if !pred.l2.is_finite() || pred.l2 < 0.0 {
1217                return Err(Error::InvalidConfig(format!(
1218                    "escalation.predictor.l2 must be finite and >= 0, got {}",
1219                    pred.l2
1220                )));
1221            }
1222        }
1223        if let Some(elastic) = &config.escalation.elastic {
1224            if elastic.expensive_gates.is_empty() {
1225                return Err(Error::InvalidConfig(
1226                    "escalation.elastic.expensive_gates must name at least one gate to skip".into(),
1227                ));
1228            }
1229            if !elastic.lambda.is_finite() || !(0.0..=1.0).contains(&elastic.lambda) {
1230                return Err(Error::InvalidConfig(format!(
1231                    "escalation.elastic.lambda must be finite and in [0, 1], got {}",
1232                    elastic.lambda
1233                )));
1234            }
1235        }
1236        Ok(config)
1237    }
1238
1239    /// The first route whose match claims `f`, or `None` if no route matches.
1240    #[must_use]
1241    pub fn route_for(&self, f: &Features) -> Option<&Route> {
1242        self.routes.iter().find(|r| r.match_.matches(f))
1243    }
1244
1245    /// The effective price table: built-in defaults with this config's `[[price]]` blocks applied.
1246    #[must_use]
1247    pub fn price_table(&self) -> crate::cost::PriceTable {
1248        self.price_defs
1249            .iter()
1250            .fold(crate::cost::PriceTable::defaults(), |table, p| {
1251                table.with_override(
1252                    p.model.clone(),
1253                    crate::cost::ModelPrice {
1254                        input_per_mtok: p.input_per_mtok,
1255                        output_per_mtok: p.output_per_mtok,
1256                    },
1257                )
1258            })
1259    }
1260
1261    /// Every ladder rung must resolve to a price.
1262    ///
1263    /// An unpriced rung is not a missing number, it is a **fabricated one**: the router falls
1264    /// back to `$0.00` for that call, so the receipt reports a spend nobody measured and a
1265    /// `[budget]` cap fed by that total can never trip. The built-in table only knows the
1266    /// first-party models, so this is precisely the bring-your-own-provider path.
1267    ///
1268    /// A genuinely free rung (a local model you host) is still legal — declare it as an
1269    /// explicit `[[price]]` of `0`, so the receipt's `$0.00` is a stated fact rather than a
1270    /// silent fallback.
1271    fn validate_ladders_are_priced(&self) -> Result<()> {
1272        let prices = self.price_table();
1273        for (i, route) in self.routes.iter().enumerate() {
1274            for rung in &route.ladder {
1275                if prices.get(rung).is_none() {
1276                    return Err(Error::InvalidConfig(format!(
1277                        "route[{i}] ladder rung {rung:?} has no price, so its cost would be \
1278                         recorded as $0.00 and any [budget] cap would never trip. Declare it:\n\n\
1279                         [[price]]\nmodel = {rung:?}\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n\n\
1280                         (use the real per-1M-token prices; 0.0 is correct only for a model you \
1281                         host yourself)"
1282                    )));
1283                }
1284            }
1285        }
1286        Ok(())
1287    }
1288}
1289
1290#[cfg(test)]
1291mod tests {
1292    use super::*;
1293    use crate::features::Features;
1294
1295    const SPEC_CONFIG: &str = r#"
1296[[route]]
1297match = { agent = "claude-code", subagent = ["test-runner", "explore"] }
1298mode  = "enforce"
1299ladder = ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1300gates  = ["schema", "judge-diff"]
1301
1302[[route]]
1303match = { task_kind = "code_edit" }
1304mode  = "enforce"
1305ladder = ["anthropic/claude-sonnet-5", "anthropic/claude-opus-4-8"]
1306gates  = ["patch-applies", "lint-diff", "judge-diff"]
1307deferred_gates = ["compiles", "tests"]
1308
1309[[route]]
1310match = {}
1311mode  = "observe"
1312ladder = ["anthropic/claude-opus-4-8"]
1313
1314[budget]
1315per_request_usd = 0.50
1316per_session_usd = 10.00
1317per_day_usd     = 250.00
1318on_exhausted    = "serve_best_attempt"
1319
1320[escalation]
1321max_rungs_per_request = 3
1322session_promotion = { after_failures = 3, window = "30m" }
1323"#;
1324
1325    #[test]
1326    fn parses_the_spec_example() {
1327        let c = Config::parse(SPEC_CONFIG).unwrap();
1328        assert_eq!(c.routes.len(), 3);
1329        assert_eq!(c.routes[0].mode, Mode::Enforce);
1330        assert_eq!(
1331            c.routes[0].ladder,
1332            ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1333        );
1334        assert_eq!(c.routes[1].deferred_gates, ["compiles", "tests"]);
1335        assert_eq!(c.budget.per_request_usd, Some(0.50));
1336        assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1337        assert_eq!(c.escalation.max_rungs_per_request, 3);
1338        let sp = c.escalation.session_promotion.as_ref().unwrap();
1339        assert_eq!(sp.after_failures, 3);
1340        assert_eq!(sp.window_duration().unwrap(), Duration::from_secs(1800));
1341    }
1342
1343    #[test]
1344    fn first_matching_route_wins() {
1345        let c = Config::parse(SPEC_CONFIG).unwrap();
1346
1347        // claude-code / test-runner -> route 0
1348        let mut f = Features::new(TaskKind::Explore);
1349        f.agent = Some("claude-code".into());
1350        f.subagent = Some("test-runner".into());
1351        let r = c.route_for(&f).unwrap();
1352        assert_eq!(r.ladder[0], "anthropic/claude-haiku-4-5");
1353
1354        // a code_edit with no agent -> route 1 (route 0's agent constraint fails)
1355        let f2 = Features::new(TaskKind::CodeEdit);
1356        let r2 = c.route_for(&f2).unwrap();
1357        assert_eq!(r2.gates, ["patch-applies", "lint-diff", "judge-diff"]);
1358
1359        // anything else -> catch-all observe route
1360        let f3 = Features::new(TaskKind::Chat);
1361        let r3 = c.route_for(&f3).unwrap();
1362        assert_eq!(r3.mode, Mode::Observe);
1363    }
1364
1365    #[test]
1366    fn shipped_example_config_parses() {
1367        // The repo ships `firstpass.example.toml` for users to copy. If it drifts
1368        // from the schema, this fails in CI rather than at a user's first run.
1369        let toml = include_str!("../../../firstpass.example.toml");
1370        let c = Config::parse(toml).expect("firstpass.example.toml must parse");
1371        assert_eq!(c.routes.len(), 3);
1372        assert_eq!(c.routes[0].mode, Mode::Enforce);
1373    }
1374
1375    #[test]
1376    fn parses_gate_definitions() {
1377        let toml = r#"
1378[[route]]
1379match = {}
1380mode  = "enforce"
1381ladder = ["anthropic/claude-haiku-4-5"]
1382gates  = ["my-tests"]
1383
1384[[gate]]
1385id  = "my-tests"
1386cmd = ["pytest", "-q"]
1387
1388[[gate]]
1389id         = "judge"
1390cmd        = ["bash", "-c", "./judge.sh"]
1391timeout_ms = 60000
1392"#;
1393        let c = Config::parse(toml).unwrap();
1394        assert_eq!(c.gate_defs.len(), 2);
1395        assert_eq!(c.gate_defs[0].id, "my-tests");
1396        assert_eq!(c.gate_defs[0].cmd, ["pytest", "-q"]);
1397        assert_eq!(c.gate_defs[0].timeout_ms, 30_000, "default timeout applies");
1398        assert_eq!(c.gate_defs[1].timeout_ms, 60_000);
1399    }
1400
1401    #[test]
1402    fn rejects_invalid_gate_definitions() {
1403        let empty_cmd = "[[gate]]\nid = \"g\"\ncmd = []\n";
1404        assert!(matches!(
1405            Config::parse(empty_cmd),
1406            Err(Error::InvalidConfig(_))
1407        ));
1408
1409        let dup = "[[gate]]\nid = \"g\"\ncmd = [\"a\"]\n[[gate]]\nid = \"g\"\ncmd = [\"b\"]\n";
1410        assert!(matches!(Config::parse(dup), Err(Error::InvalidConfig(_))));
1411    }
1412
1413    #[test]
1414    fn parses_consistency_gate_definition() {
1415        let toml = r#"
1416[[gate]]
1417id          = "uncertainty"
1418consistency = { model = "anthropic/claude-haiku-4-5", k = 5, threshold = 0.6 }
1419"#;
1420        let c = Config::parse(toml).unwrap();
1421        assert_eq!(c.gate_defs.len(), 1);
1422        let cons = c.gate_defs[0].consistency.as_ref().unwrap();
1423        assert_eq!(cons.model, "anthropic/claude-haiku-4-5");
1424        assert_eq!(cons.k, 5);
1425        assert!((cons.threshold - 0.6).abs() < 1e-9);
1426    }
1427
1428    #[test]
1429    fn consistency_k_defaults_to_3() {
1430        let toml = "[[gate]]\nid = \"u\"\nconsistency = { model = \"anthropic/claude-haiku-4-5\", threshold = 0.7 }\n";
1431        let c = Config::parse(toml).unwrap();
1432        assert_eq!(c.gate_defs[0].consistency.as_ref().unwrap().k, 3);
1433    }
1434
1435    #[test]
1436    fn rejects_exactly_one_of_violations_for_consistency() {
1437        // cmd + consistency — two kinds set
1438        let both = "[[gate]]\nid = \"g\"\ncmd = [\"x\"]\nconsistency = { model = \"a/b\", threshold = 0.5 }\n";
1439        assert!(matches!(Config::parse(both), Err(Error::InvalidConfig(_))));
1440
1441        // consistency k out of bounds
1442        let bad_k =
1443            "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 1, threshold = 0.5 }\n";
1444        assert!(matches!(Config::parse(bad_k), Err(Error::InvalidConfig(_))));
1445
1446        let bad_k2 =
1447            "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 9, threshold = 0.5 }\n";
1448        assert!(matches!(
1449            Config::parse(bad_k2),
1450            Err(Error::InvalidConfig(_))
1451        ));
1452
1453        // consistency threshold out of bounds
1454        let bad_thresh =
1455            "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", threshold = 1.1 }\n";
1456        assert!(matches!(
1457            Config::parse(bad_thresh),
1458            Err(Error::InvalidConfig(_))
1459        ));
1460    }
1461
1462    #[test]
1463    fn parses_adaptive_conformal_config() {
1464        let c = Config::parse("[escalation.adaptive]\nalpha = 0.1\n").unwrap();
1465        let a = c
1466            .escalation
1467            .adaptive
1468            .expect("[escalation.adaptive] should parse");
1469        assert!((a.alpha - 0.1).abs() < 1e-9);
1470        assert!((a.gamma - 0.02).abs() < 1e-9, "gamma defaults to 0.02");
1471        // Absent => None (fixed-threshold serving, default byte-identical behavior).
1472        assert!(Config::parse("").unwrap().escalation.adaptive.is_none());
1473    }
1474
1475    #[test]
1476    fn parses_provider_entries_and_ladders_can_reference_them() {
1477        let c = Config::parse(
1478            r#"
1479[[provider]]
1480id = "groq"
1481dialect = "openai"
1482base_url = "https://api.groq.com/openai"
1483api_key_env = "GROQ_API_KEY"
1484
1485[[provider]]
1486id = "ollama"
1487dialect = "openai"
1488base_url = "http://localhost:11434"
1489
1490# A bring-your-own provider has no built-in price, so the ladder must declare one or the
1491# receipt would report $0.00 for every Groq call.
1492[[price]]
1493model = "groq/llama-3.3-70b-versatile"
1494input_per_mtok = 0.59
1495output_per_mtok = 0.79
1496
1497[[route]]
1498match = {}
1499mode = "enforce"
1500ladder = ["groq/llama-3.3-70b-versatile", "anthropic/claude-sonnet-5"]
1501"#,
1502        )
1503        .unwrap();
1504        assert_eq!(c.providers.len(), 2);
1505        let groq = &c.providers[0];
1506        assert_eq!(groq.id, "groq");
1507        assert_eq!(groq.dialect, Dialect::Openai);
1508        assert_eq!(groq.base_url, "https://api.groq.com/openai");
1509        assert_eq!(groq.api_key_env.as_deref(), Some("GROQ_API_KEY"));
1510        // A keyless local endpoint (Ollama) parses with no api_key_env.
1511        assert_eq!(c.providers[1].id, "ollama");
1512        assert!(c.providers[1].api_key_env.is_none());
1513        // Absent => no extra providers (built-ins only).
1514        assert!(Config::parse("").unwrap().providers.is_empty());
1515    }
1516
1517    #[test]
1518    fn parses_aws_sigv4_provider_and_defaults_auth_to_api_key() {
1519        let c = Config::parse(
1520            r#"
1521[[provider]]
1522id = "bedrock"
1523dialect = "anthropic"
1524auth = "aws_sigv4"
1525region = "us-east-1"
1526"#,
1527        )
1528        .unwrap();
1529        let bedrock = &c.providers[0];
1530        assert_eq!(bedrock.auth, AuthScheme::AwsSigv4);
1531        assert_eq!(bedrock.region.as_deref(), Some("us-east-1"));
1532        assert!(bedrock.project.is_none());
1533
1534        // Omitting `auth` on an existing provider entry defaults to ApiKey (I1: no behavior
1535        // change for today's `[[provider]]` entries).
1536        let c2 = Config::parse(
1537            r#"
1538[[provider]]
1539id = "groq"
1540dialect = "openai"
1541base_url = "https://api.groq.com/openai"
1542"#,
1543        )
1544        .unwrap();
1545        assert_eq!(c2.providers[0].auth, AuthScheme::ApiKey);
1546    }
1547
1548    #[test]
1549    fn all_documented_provider_shapes_parse() {
1550        // The exact `[[provider]]` shapes shown in the README / usage page / firstpass.example.toml.
1551        // This is the guard that the documented provider instructions stay valid — one entry per
1552        // dialect/auth combination we tell users to write.
1553        let c = Config::parse(
1554            r#"
1555[[provider]]
1556id = "groq"
1557dialect = "openai"
1558base_url = "https://api.groq.com/openai"
1559api_key_env = "GROQ_API_KEY"
1560
1561[[provider]]
1562id = "ollama"
1563dialect = "openai"
1564base_url = "http://localhost:11434"
1565
1566[[provider]]
1567id = "gemini"
1568dialect = "gemini"
1569base_url = "https://generativelanguage.googleapis.com"
1570api_key_env = "GEMINI_API_KEY"
1571
1572[[provider]]
1573id = "bedrock"
1574dialect = "anthropic"
1575auth = "aws_sigv4"
1576region = "us-east-1"
1577
1578[[provider]]
1579id = "vertex"
1580dialect = "anthropic"
1581auth = "gcp_oauth"
1582region = "us-east5"
1583project = "my-gcp-project"
1584"#,
1585        )
1586        .expect("every documented provider shape must parse");
1587        assert_eq!(c.providers.len(), 5);
1588
1589        let gemini = c.providers.iter().find(|p| p.id == "gemini").unwrap();
1590        assert_eq!(gemini.dialect, Dialect::Gemini);
1591        assert_eq!(gemini.auth, AuthScheme::ApiKey);
1592
1593        let vertex = c.providers.iter().find(|p| p.id == "vertex").unwrap();
1594        assert_eq!(vertex.auth, AuthScheme::GcpOauth);
1595        assert_eq!(vertex.region.as_deref(), Some("us-east5"));
1596        assert_eq!(vertex.project.as_deref(), Some("my-gcp-project"));
1597    }
1598
1599    #[test]
1600    fn empty_match_is_wildcard() {
1601        let m = Match::default();
1602        assert!(m.matches(&Features::new(TaskKind::Other)));
1603    }
1604
1605    #[test]
1606    fn subagent_list_membership() {
1607        let c = Config::parse(SPEC_CONFIG).unwrap();
1608        let route0 = &c.routes[0];
1609        let mut f = Features::new(TaskKind::Other);
1610        f.agent = Some("claude-code".into());
1611        f.subagent = Some("docs-writer".into()); // not in [test-runner, explore]
1612        assert!(!route0.match_.matches(&f));
1613        f.subagent = Some("explore".into());
1614        assert!(route0.match_.matches(&f));
1615    }
1616
1617    #[test]
1618    fn model_ref_parsing() {
1619        let m = ModelRef::parse("anthropic/claude-haiku-4-5").unwrap();
1620        assert_eq!(m.provider, "anthropic");
1621        assert_eq!(m.model, "claude-haiku-4-5");
1622        assert!(ModelRef::parse("no-slash").is_err());
1623        assert!(ModelRef::parse("/model").is_err());
1624        assert!(ModelRef::parse("a/b/c").is_err());
1625    }
1626
1627    #[test]
1628    fn window_parsing_units_and_errors() {
1629        assert_eq!(parse_window("90s").unwrap(), Duration::from_secs(90));
1630        assert_eq!(parse_window("30m").unwrap(), Duration::from_secs(1800));
1631        assert_eq!(parse_window("2h").unwrap(), Duration::from_secs(7200));
1632        assert_eq!(parse_window("1d").unwrap(), Duration::from_secs(86_400));
1633        assert!(parse_window("30x").is_err());
1634        assert!(parse_window("abc").is_err());
1635    }
1636
1637    #[test]
1638    fn empty_config_defaults() {
1639        let c = Config::parse("").unwrap();
1640        assert!(c.routes.is_empty());
1641        assert_eq!(c.escalation.max_rungs_per_request, 3);
1642        assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1643    }
1644
1645    // ── ExplorationConfig parse / validation ──────────────────────────────────
1646
1647    #[test]
1648    fn parses_exploration_config() {
1649        let c = Config::parse("[escalation.exploration]\nepsilon = 0.1\n").unwrap();
1650        let exp = c
1651            .escalation
1652            .exploration
1653            .expect("[escalation.exploration] should parse");
1654        assert!((exp.epsilon - 0.1).abs() < 1e-12);
1655        // Absent => None (deterministic policy, byte-identical behavior).
1656        assert!(Config::parse("").unwrap().escalation.exploration.is_none());
1657    }
1658
1659    /// An out-of-range e-process grid must be REJECTED at parse, not silently filtered.
1660    ///
1661    /// `EProcessRiskControl::new` drops non-finite entries so a bad grid cannot panic — correct for
1662    /// a library, wrong for config. An operator who writes `grid = [2.0, 3.0]` would otherwise get
1663    /// an empty grid, certify nothing, and read "no threshold certified" in the report:
1664    /// indistinguishable from insufficient data. The same silent-collapse shape as the Bonferroni
1665    /// failure in ADR 0011, arriving through a typo. Flagged in review.
1666    #[test]
1667    fn an_out_of_range_eprocess_grid_is_rejected_not_filtered() {
1668        let good = "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.05\ngrid = [0.0, 0.5, 1.0]\n";
1669        assert!(Config::parse(good).is_ok(), "a valid grid must parse");
1670
1671        for bad in [
1672            "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.05\ngrid = [2.0]\n",
1673            "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.05\ngrid = [-0.5, 0.5]\n",
1674            "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.05\ngrid = []\n",
1675        ] {
1676            assert!(
1677                matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1678                "must reject: {bad}"
1679            );
1680        }
1681    }
1682
1683    /// `alpha` and `delta` are probabilities. Zero or one makes the guarantee vacuous or
1684    /// unreachable — `delta = 0` in particular means the crossing level is infinite and nothing can
1685    /// ever certify, which is a silent no-op rather than an error at runtime.
1686    #[test]
1687    fn degenerate_eprocess_alpha_or_delta_is_rejected() {
1688        for bad in [
1689            "[escalation.eprocess]\nalpha = 0.0\ndelta = 0.05\n",
1690            "[escalation.eprocess]\nalpha = 1.0\ndelta = 0.05\n",
1691            "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.0\n",
1692            "[escalation.eprocess]\nalpha = 0.1\ndelta = 1.0\n",
1693            // bet = 0 clamps to 0 at runtime: the betting factor is always 1, the e-value never
1694            // moves, and nothing can ever certify. Silent, permanent, and indistinguishable from
1695            // insufficient data.
1696            "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.05\nbet = 0.0\n",
1697            "[escalation.eprocess]\nalpha = 0.1\ndelta = 0.05\nbet = 1.5\n",
1698        ] {
1699            assert!(
1700                matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1701                "must reject: {bad}"
1702            );
1703        }
1704    }
1705
1706    #[test]
1707    fn exploration_epsilon_boundary_valid() {
1708        // Upper bound 0.5 is allowed.
1709        let c = Config::parse("[escalation.exploration]\nepsilon = 0.5\n").unwrap();
1710        assert!((c.escalation.exploration.unwrap().epsilon - 0.5).abs() < 1e-12);
1711    }
1712
1713    #[test]
1714    fn exploration_epsilon_above_half_rejected() {
1715        let bad = "[escalation.exploration]\nepsilon = 0.51\n";
1716        assert!(
1717            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1718            "epsilon > 0.5 must be rejected"
1719        );
1720    }
1721
1722    #[test]
1723    fn exploration_epsilon_zero_rejected() {
1724        let bad = "[escalation.exploration]\nepsilon = 0.0\n";
1725        assert!(
1726            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1727            "epsilon = 0 must be rejected (must be strictly positive)"
1728        );
1729    }
1730
1731    #[test]
1732    fn exploration_epsilon_negative_rejected() {
1733        let bad = "[escalation.exploration]\nepsilon = -0.1\n";
1734        assert!(
1735            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1736            "epsilon < 0 must be rejected"
1737        );
1738    }
1739
1740    #[test]
1741    fn gate_def_schema_and_on_abstain_parse() {
1742        let toml = r#"
1743[[route]]
1744match = {}
1745mode = "enforce"
1746ladder = ["anthropic/claude-haiku-4-5"]
1747gates = ["extract-shape"]
1748
1749[[gate]]
1750id = "extract-shape"
1751schema = { type = "object", required = ["name"] }
1752on_abstain = "fail_closed"
1753"#;
1754        let config = Config::parse(toml).expect("schema gate def must parse");
1755        let def = &config.gate_defs[0];
1756        assert_eq!(def.id, "extract-shape");
1757        let schema = def.schema.as_ref().expect("schema captured");
1758        assert_eq!(schema["type"], "object");
1759        assert_eq!(def.on_abstain, AbstainPolicy::FailClosed);
1760    }
1761
1762    #[test]
1763    fn gate_def_on_abstain_defaults_fail_open() {
1764        let toml = r#"
1765[[route]]
1766match = {}
1767mode = "enforce"
1768ladder = ["anthropic/claude-haiku-4-5"]
1769
1770[[gate]]
1771id = "tests"
1772cmd = ["true"]
1773"#;
1774        let config = Config::parse(toml).expect("parse");
1775        assert_eq!(config.gate_defs[0].on_abstain, AbstainPolicy::FailOpen);
1776    }
1777
1778    #[test]
1779    fn gate_def_rejects_schema_plus_cmd() {
1780        let toml = r#"
1781[[route]]
1782match = {}
1783mode = "enforce"
1784ladder = ["anthropic/claude-haiku-4-5"]
1785
1786[[gate]]
1787id = "both"
1788cmd = ["true"]
1789schema = { type = "object" }
1790"#;
1791        let err = Config::parse(toml).unwrap_err();
1792        assert!(
1793            err.to_string().contains("exactly one"),
1794            "two kinds must be rejected: {err}"
1795        );
1796    }
1797
1798    #[test]
1799    fn price_overrides_parse_and_validate() {
1800        let toml = r#"
1801[[route]]
1802match = {}
1803mode = "observe"
1804ladder = ["anthropic/claude-haiku-4-5"]
1805
1806[[price]]
1807model = "anthropic/claude-haiku-4-5"
1808input_per_mtok = 0.8
1809output_per_mtok = 4.0
1810"#;
1811        let config = Config::parse(toml).expect("price override must parse");
1812        assert_eq!(config.price_defs[0].model, "anthropic/claude-haiku-4-5");
1813        assert!((config.price_defs[0].input_per_mtok - 0.8).abs() < 1e-12);
1814
1815        let bad = toml.replace("input_per_mtok = 0.8", "input_per_mtok = -1.0");
1816        assert!(Config::parse(&bad).is_err(), "negative price rejected");
1817    }
1818
1819    // ── RoutingMode / ModePreset ──────────────────────────────────────────────
1820
1821    /// The Balanced preset must be a strict no-op: all overrides None/false.
1822    /// This is the invariant that guarantees byte-identical behaviour when no mode is set.
1823    #[test]
1824    fn balanced_preset_is_strict_noop() {
1825        let p = RoutingMode::Balanced.preset();
1826        assert!(
1827            p.speculation.is_none(),
1828            "Balanced must not override speculation"
1829        );
1830        assert!(
1831            p.max_rungs_delta.is_none(),
1832            "Balanced must not override max_rungs"
1833        );
1834        assert!(!p.start_at_top, "Balanced must not set start_at_top");
1835    }
1836
1837    #[test]
1838    fn cost_preset_disables_speculation() {
1839        let p = RoutingMode::Cost.preset();
1840        assert_eq!(p.speculation, Some(0));
1841        assert!(p.max_rungs_delta.is_none());
1842        assert!(!p.start_at_top);
1843    }
1844
1845    #[test]
1846    fn quality_preset_bumps_max_rungs_and_disables_speculation() {
1847        let p = RoutingMode::Quality.preset();
1848        assert_eq!(p.max_rungs_delta, Some(1));
1849        assert_eq!(p.speculation, Some(0));
1850        assert!(!p.start_at_top);
1851    }
1852
1853    #[test]
1854    fn latency_preset_enables_speculation() {
1855        let p = RoutingMode::Latency.preset();
1856        assert_eq!(p.speculation, Some(1));
1857        assert!(p.max_rungs_delta.is_none());
1858        assert!(!p.start_at_top);
1859    }
1860
1861    #[test]
1862    fn max_preset_sets_start_at_top_and_disables_speculation() {
1863        let p = RoutingMode::Max.preset();
1864        assert!(p.start_at_top);
1865        assert_eq!(p.speculation, Some(0));
1866        assert!(p.max_rungs_delta.is_none());
1867    }
1868
1869    #[test]
1870    fn routing_mode_as_str_roundtrips() {
1871        for mode in RoutingMode::ALL {
1872            let s = mode.as_str();
1873            let back: RoutingMode = serde_json::from_str(&format!("\"{s}\"")).unwrap();
1874            assert_eq!(*mode, back, "as_str/serde roundtrip for {s}");
1875        }
1876    }
1877
1878    #[test]
1879    fn routing_mode_defaults_to_balanced() {
1880        assert_eq!(RoutingMode::default(), RoutingMode::Balanced);
1881    }
1882
1883    #[test]
1884    fn route_routing_mode_parses_and_defaults_to_none() {
1885        // Absent → None (byte-identical, no behavioral change).
1886        let no_mode = Config::parse(
1887            "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n",
1888        )
1889        .unwrap();
1890        assert_eq!(no_mode.routes[0].routing_mode, None);
1891
1892        // Explicit cost mode.
1893        let with_mode = Config::parse(
1894            "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\nrouting_mode = \"cost\"\n",
1895        )
1896        .unwrap();
1897        assert_eq!(with_mode.routes[0].routing_mode, Some(RoutingMode::Cost));
1898    }
1899
1900    #[test]
1901    fn all_routing_modes_have_non_empty_description_and_tradeoff() {
1902        for mode in RoutingMode::ALL {
1903            let p = mode.preset();
1904            assert!(
1905                !p.description.is_empty(),
1906                "mode {} has empty description",
1907                mode.as_str()
1908            );
1909            assert!(
1910                !p.tradeoff.is_empty(),
1911                "mode {} has empty tradeoff",
1912                mode.as_str()
1913            );
1914        }
1915    }
1916
1917    #[test]
1918    fn bandit_thompson_and_band_parse_and_validate() {
1919        let toml = r#"
1920[[route]]
1921match = {}
1922mode = "enforce"
1923ladder = ["anthropic/claude-haiku-4-5"]
1924
1925[escalation]
1926speculation = 1
1927speculation_band = [0.3, 0.7]
1928
1929[escalation.bandit]
1930algorithm = "thompson"
1931discount = 0.98
1932"#;
1933        let config = Config::parse(toml).expect("thompson + band must parse");
1934        let b = config.escalation.bandit.as_ref().unwrap();
1935        assert_eq!(b.algorithm, BanditAlgorithm::Thompson);
1936        assert!((b.discount - 0.98).abs() < 1e-12);
1937        assert_eq!(config.escalation.speculation_band, Some([0.3, 0.7]));
1938
1939        // Defaults: ucb1, discount 1.0, no band.
1940        let plain = Config::parse(
1941            "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.bandit]\n",
1942        )
1943        .unwrap();
1944        let b = plain.escalation.bandit.as_ref().unwrap();
1945        assert_eq!(b.algorithm, BanditAlgorithm::Ucb1);
1946        assert!((b.discount - 1.0).abs() < 1e-12);
1947
1948        // Bad discount and bad band are rejected.
1949        assert!(Config::parse(&toml.replace("discount = 0.98", "discount = 0.0")).is_err());
1950        assert!(
1951            Config::parse(&toml.replace(
1952                "speculation_band = [0.3, 0.7]",
1953                "speculation_band = [0.9, 0.2]"
1954            ))
1955            .is_err()
1956        );
1957    }
1958
1959    // ── ProbeConfig parse / validation ───────────────────────────────────────
1960
1961    #[test]
1962    fn probe_absent_defaults_to_none() {
1963        // Default off = byte-identical to today.
1964        let c = Config::parse("").unwrap();
1965        assert!(c.escalation.probe.is_none());
1966    }
1967
1968    #[test]
1969    fn parses_valid_probe_config() {
1970        let c = Config::parse("[escalation.probe]\nk = 5\nsample_rate = 0.1\n").unwrap();
1971        let p = c.escalation.probe.expect("[escalation.probe] should parse");
1972        assert_eq!(p.k, 5);
1973        assert!((p.sample_rate - 0.1).abs() < 1e-12);
1974    }
1975
1976    #[test]
1977    fn probe_sample_rate_boundaries_accepted() {
1978        // 0.0 (never probe) and 1.0 (always probe) are both valid.
1979        let c0 = Config::parse("[escalation.probe]\nk = 2\nsample_rate = 0.0\n").unwrap();
1980        assert!((c0.escalation.probe.unwrap().sample_rate - 0.0).abs() < 1e-12);
1981        let c1 = Config::parse("[escalation.probe]\nk = 8\nsample_rate = 1.0\n").unwrap();
1982        assert!((c1.escalation.probe.unwrap().sample_rate - 1.0).abs() < 1e-12);
1983    }
1984
1985    #[test]
1986    fn probe_rejects_k_below_2() {
1987        let bad = "[escalation.probe]\nk = 1\nsample_rate = 0.5\n";
1988        assert!(
1989            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1990            "k=1 must be rejected"
1991        );
1992    }
1993
1994    #[test]
1995    fn probe_rejects_k_above_8() {
1996        let bad = "[escalation.probe]\nk = 9\nsample_rate = 0.5\n";
1997        assert!(
1998            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1999            "k=9 must be rejected"
2000        );
2001    }
2002
2003    #[test]
2004    fn probe_rejects_sample_rate_above_1() {
2005        let bad = "[escalation.probe]\nk = 5\nsample_rate = 1.5\n";
2006        assert!(
2007            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
2008            "sample_rate=1.5 must be rejected"
2009        );
2010    }
2011
2012    #[test]
2013    fn probe_rejects_negative_sample_rate() {
2014        let bad = "[escalation.probe]\nk = 5\nsample_rate = -0.1\n";
2015        assert!(
2016            matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
2017            "negative sample_rate must be rejected"
2018        );
2019    }
2020
2021    #[test]
2022    fn predictor_config_parses_and_validates() {
2023        let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\nlr = 0.05\nl2 = 0.001\n";
2024        let cfg = Config::parse(base).expect("valid predictor must parse");
2025        let pred = cfg.escalation.predictor.unwrap();
2026        assert!((pred.lr - 0.05).abs() < 1e-12 && (pred.l2 - 0.001).abs() < 1e-12);
2027        // defaults when omitted
2028        let d = Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\n").unwrap();
2029        assert!(d.escalation.predictor.is_some());
2030        // bad lr / l2 rejected
2031        assert!(Config::parse(&base.replace("lr = 0.05", "lr = 0.0")).is_err());
2032        assert!(Config::parse(&base.replace("lr = 0.05", "lr = 1.5")).is_err());
2033        assert!(Config::parse(&base.replace("l2 = 0.001", "l2 = -1.0")).is_err());
2034    }
2035
2036    /// An unpriced ladder rung must be rejected at parse. The router prices a call with
2037    /// `cost_usd(..).unwrap_or(0.0)`, so accepting one would put a spend nobody measured into a
2038    /// tamper-evident receipt and leave every `[budget]` cap permanently un-trippable — the two
2039    /// failures this product can least afford.
2040    #[test]
2041    fn unpriced_ladder_rung_is_rejected_and_an_explicit_price_fixes_it() {
2042        let unpriced =
2043            "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"ollama/qwen2.5-coder:7b\"]\n";
2044        let err = Config::parse(unpriced).expect_err("an unpriced rung must not parse");
2045        let msg = err.to_string();
2046        assert!(
2047            msg.contains("ollama/qwen2.5-coder:7b") && msg.contains("[[price]]"),
2048            "the error must name the rung and the fix, got: {msg}"
2049        );
2050
2051        // A self-hosted model really is free — but it has to SAY so.
2052        let declared = format!(
2053            "[[price]]\nmodel = \"ollama/qwen2.5-coder:7b\"\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n{unpriced}"
2054        );
2055        let cfg = Config::parse(&declared).expect("an explicit zero price is legal");
2056        assert_eq!(
2057            cfg.price_table()
2058                .get("ollama/qwen2.5-coder:7b")
2059                .unwrap()
2060                .input_per_mtok,
2061            0.0
2062        );
2063
2064        // The built-in first-party models still need no ceremony.
2065        assert!(
2066            Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n").is_ok()
2067        );
2068    }
2069
2070    /// Shadow is off unless asked for, and a nonsensical setting must fail loudly at parse rather
2071    /// than being clamped — a silently-corrected ceiling would spend a different amount than the
2072    /// operator authorised.
2073    #[test]
2074    fn shadow_config_parses_and_validates() {
2075        let base = "[[route]]\nmatch = {}\nmode = \"observe\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
2076        let none = Config::parse(base).unwrap();
2077        assert!(
2078            none.routes[0].shadow.is_none(),
2079            "shadow must be off by default"
2080        );
2081
2082        let ok = Config::parse(&format!(
2083            "{base}[route.shadow]\nsample_rate = 0.25\nmax_usd_per_day = 5.0\n"
2084        ))
2085        .unwrap();
2086        let sh = ok.routes[0].shadow.expect("shadow parsed");
2087        assert!((sh.sample_rate - 0.25).abs() < f64::EPSILON);
2088        assert!((sh.max_usd_per_day - 5.0).abs() < f64::EPSILON);
2089
2090        for bad in [
2091            "sample_rate = 1.5\nmax_usd_per_day = 5.0",
2092            "sample_rate = -0.1\nmax_usd_per_day = 5.0",
2093            "sample_rate = 0.1\nmax_usd_per_day = -1.0",
2094        ] {
2095            assert!(
2096                Config::parse(&format!("{base}[route.shadow]\n{bad}\n")).is_err(),
2097                "invalid shadow config accepted: {bad}"
2098            );
2099        }
2100    }
2101
2102    /// Same for rollout: absent by default, invalid percent rejected at parse.
2103    #[test]
2104    fn rollout_config_parses_and_validates() {
2105        let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
2106        assert!(Config::parse(base).unwrap().routes[0].rollout.is_none());
2107        let ok = Config::parse(&format!(
2108            "{base}[route.rollout]\npercent = 5.0\nkey = \"session\"\n"
2109        ))
2110        .unwrap();
2111        assert!((ok.routes[0].rollout.unwrap().percent - 5.0).abs() < f64::EPSILON);
2112        assert!(Config::parse(&format!("{base}[route.rollout]\npercent = 140.0\n")).is_err());
2113    }
2114}