Skip to main content

keel_core_api/
policy.rs

1//! Typed policy model: `keel.toml` (in its JSON form) deserialized straight
2//! into structs. Validation *is* the type system — `NonZero*` integers make
3//! zero counts unrepresentable, newtypes parse duration/rate/schedule
4//! literals in their `Deserialize` impls, and retry conditions are a closed
5//! enum. A document that deserializes is a valid policy; anything else is
6//! `KEEL-E001` with a precise field path (via `serde_path_to_error`).
7
8use core::fmt;
9use core::num::{NonZeroU32, NonZeroU64};
10use core::str::FromStr;
11use std::collections::BTreeMap;
12
13use crate::ErrorClass;
14use serde::Deserialize;
15
16/// A literal that failed to parse; surfaces through serde as the
17/// deserialization error message for the offending field.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ParseError {
20    what: &'static str,
21    input: String,
22    /// For literals that are grammatical but invalid (e.g. a schedule
23    /// composition whose segments can never all be reached): the reason,
24    /// appended so the KEEL-E001 first line says what to fix.
25    note: Option<&'static str>,
26}
27
28impl ParseError {
29    fn new(what: &'static str, input: &str) -> Self {
30        Self {
31            what,
32            input: input.to_owned(),
33            note: None,
34        }
35    }
36
37    fn with_note(what: &'static str, input: &str, note: &'static str) -> Self {
38        Self {
39            what,
40            input: input.to_owned(),
41            note: Some(note),
42        }
43    }
44}
45
46impl fmt::Display for ParseError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self.note {
49            None => write!(f, "unparseable {} literal: {:?}", self.what, self.input),
50            Some(note) => write!(
51                f,
52                "invalid {} literal: {:?} — {note}",
53                self.what, self.input
54            ),
55        }
56    }
57}
58
59impl core::error::Error for ParseError {}
60
61/// A duration literal: `200ms`, `30s`, `5m`, `2h`.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
63#[serde(try_from = "String")]
64pub struct DurationMs(pub u64);
65
66impl FromStr for DurationMs {
67    type Err = ParseError;
68
69    fn from_str(s: &str) -> Result<Self, Self::Err> {
70        let err = || ParseError::new("duration", s);
71        let s = s.trim();
72        let unit_at = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(err)?;
73        let (number, unit) = s.split_at(unit_at);
74        let n: u64 = number.parse().map_err(|_| err())?;
75        let mult = match unit {
76            "ms" => 1,
77            "s" => 1_000,
78            "m" => 60_000,
79            "h" => 3_600_000,
80            _ => return Err(err()),
81        };
82        Ok(Self(n * mult))
83    }
84}
85
86impl TryFrom<String> for DurationMs {
87    type Error = ParseError;
88
89    fn try_from(s: String) -> Result<Self, Self::Error> {
90        s.parse()
91    }
92}
93
94/// A rate literal: `90/s`, `60/min`, `10/h`. A zero limit is unrepresentable.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
96#[serde(try_from = "String")]
97pub struct Rate {
98    pub limit: NonZeroU64,
99    pub window_ms: u64,
100}
101
102impl FromStr for Rate {
103    type Err = ParseError;
104
105    fn from_str(s: &str) -> Result<Self, Self::Err> {
106        let err = || ParseError::new("rate", s);
107        let (limit, window) = s.trim().split_once('/').ok_or_else(err)?;
108        let limit: NonZeroU64 = limit.trim().parse().map_err(|_| err())?;
109        let window_ms = match window.trim() {
110            "s" | "sec" => 1_000,
111            "min" => 60_000,
112            "h" | "hour" => 3_600_000,
113            _ => return Err(err()),
114        };
115        Ok(Self { limit, window_ms })
116    }
117}
118
119impl TryFrom<String> for Rate {
120    type Error = ParseError;
121
122    fn try_from(s: String) -> Result<Self, Self::Error> {
123        s.parse()
124    }
125}
126
127/// A retry schedule per contracts/schedule-grammar.ebnf — the full algebra:
128/// one or more `andThen`-separated segments, each an `exp`/`fixed` primary
129/// with an optional cumulative-wait bound (`upTo`). Semantics are pinned
130/// normatively in conformance/README.md ("Schedule algebra"): `upTo` bounds
131/// the segment's cumulative *natural* wait and hands off to the next segment;
132/// every segment except the last must be bounded and the last never is (both
133/// degenerate shapes are configure-time `KEEL-E001`), so a schedule is always
134/// a total mapping attempt → wait.
135#[derive(Debug, Clone, PartialEq, Deserialize)]
136#[serde(try_from = "String")]
137pub struct Schedule {
138    /// Non-empty; the parser enforces `up_to_ms.is_some()` on every segment
139    /// except the last and `None` on the last.
140    pub segments: Vec<ScheduleSegment>,
141}
142
143/// One `andThen` segment: a primary plus its optional `upTo` bound.
144#[derive(Debug, Clone, Copy, PartialEq)]
145pub struct ScheduleSegment {
146    pub primary: SchedulePrimary,
147    /// `upTo` bound on this segment's cumulative natural wait, in ms.
148    pub up_to_ms: Option<u64>,
149}
150
151/// A schedule primary (`exp` / `fixed`) from the frozen grammar.
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub enum SchedulePrimary {
154    Exp {
155        base_ms: u64,
156        factor: f64,
157        cap_ms: u64,
158        jitter: bool,
159    },
160    Fixed {
161        period_ms: u64,
162    },
163}
164
165impl SchedulePrimary {
166    /// Deterministic natural wait at local attempt `a` (1-based):
167    /// `min(base * factor^(a-1), cap)`, before any jitter.
168    #[expect(
169        clippy::cast_precision_loss,
170        clippy::cast_possible_truncation,
171        clippy::cast_sign_loss,
172        clippy::cast_possible_wrap,
173        reason = "backoff arithmetic: values are small and non-negative by construction"
174    )]
175    fn wait_ms(self, attempt: u32) -> u64 {
176        match self {
177            Self::Exp {
178                base_ms,
179                factor,
180                cap_ms,
181                ..
182            } => {
183                let wait = base_ms as f64 * factor.powi(attempt as i32 - 1);
184                wait.min(cap_ms as f64).round() as u64
185            }
186            Self::Fixed { period_ms } => period_ms,
187        }
188    }
189
190    fn jitter(self) -> bool {
191        matches!(self, Self::Exp { jitter: true, .. })
192    }
193}
194
195impl Default for Schedule {
196    /// The contract default: `exp(200ms, x2, max 30s, jitter)`.
197    fn default() -> Self {
198        Self {
199            segments: vec![ScheduleSegment {
200                primary: SchedulePrimary::Exp {
201                    base_ms: 200,
202                    factor: 2.0,
203                    cap_ms: 30_000,
204                    jitter: true,
205                },
206                up_to_ms: None,
207            }],
208        }
209    }
210}
211
212impl Schedule {
213    /// Deterministic wait after failed attempt `n` (1-based), before any
214    /// jitter or `Retry-After` override.
215    #[must_use]
216    pub fn wait_ms(&self, attempt: u32) -> u64 {
217        self.wait_and_jitter(attempt).0
218    }
219
220    /// `(wait, jitter?)` for retry attempt `n` — a pure function of `n`, per
221    /// the normative walk in conformance/README.md ("Schedule algebra"):
222    /// segments hand off when the next natural wait would push the segment's
223    /// cumulative emitted total past its `upTo` bound (an exact fit stays;
224    /// handoffs cascade past segments whose bound is below their first wait),
225    /// and each segment restarts at local attempt 1 on entry. The jitter flag
226    /// is the emitting segment's — the stubs ignore it (virtual clocks); the
227    /// real core samples equal jitter, uniform in `[w/2, w]`.
228    ///
229    /// # Panics
230    /// If `segments` is empty (unrepresentable via the parser).
231    #[must_use]
232    pub fn wait_and_jitter(&self, attempt: u32) -> (u64, bool) {
233        let attempt = attempt.max(1);
234        let last = self.segments.len() - 1;
235        let (mut i, mut a, mut e) = (0_usize, 1_u32, 0_u64);
236        let mut emitted = 0_u32;
237        loop {
238            let segment = self.segments[i];
239            let wait = segment.primary.wait_ms(a);
240            // A bound on the final segment is unrepresentable via the parser;
241            // `i < last` keeps hand-constructed values total anyway.
242            if i < last
243                && let Some(bound) = segment.up_to_ms
244                && e.saturating_add(wait) > bound
245            {
246                (i, a, e) = (i + 1, 1, 0);
247                continue;
248            }
249            emitted += 1;
250            if emitted == attempt {
251                return (wait, segment.primary.jitter());
252            }
253            a += 1;
254            e = e.saturating_add(wait);
255        }
256    }
257}
258
259impl FromStr for SchedulePrimary {
260    type Err = ParseError;
261
262    fn from_str(s: &str) -> Result<Self, Self::Err> {
263        let err = || ParseError::new("schedule", s);
264        let s = s.trim();
265        if let Some(inner) = s.strip_prefix("exp(").and_then(|r| r.strip_suffix(')')) {
266            let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
267            let [base, factor, rest @ ..] = parts.as_slice() else {
268                return Err(err());
269            };
270            let base_ms = base.parse::<DurationMs>().map_err(|_| err())?.0;
271            let factor: f64 = factor
272                .strip_prefix('x')
273                .ok_or_else(err)?
274                .parse()
275                .map_err(|_| err())?;
276            let mut cap_ms = u64::MAX;
277            let mut jitter = false;
278            for part in rest {
279                if let Some(d) = part.strip_prefix("max ") {
280                    cap_ms = d.parse::<DurationMs>().map_err(|_| err())?.0;
281                } else if *part == "jitter" {
282                    jitter = true;
283                } else {
284                    return Err(err());
285                }
286            }
287            Ok(Self::Exp {
288                base_ms,
289                factor,
290                cap_ms,
291                jitter,
292            })
293        } else if let Some(inner) = s.strip_prefix("fixed(").and_then(|r| r.strip_suffix(')')) {
294            let period_ms = inner.parse::<DurationMs>().map_err(|_| err())?.0;
295            Ok(Self::Fixed { period_ms })
296        } else {
297            Err(err())
298        }
299    }
300}
301
302impl FromStr for Schedule {
303    type Err = ParseError;
304
305    fn from_str(s: &str) -> Result<Self, Self::Err> {
306        let err = || ParseError::new("schedule", s);
307        // The grammar's `ws` makes `upTo` / `andThen` space-separated tokens;
308        // tokenizing on whitespace runs and rejoining a primary's tokens with
309        // single spaces is lossless for the primary parsers (they trim around
310        // commas). Keywords never occur inside `exp(…)`/`fixed(…)` in a valid
311        // literal, so no paren tracking is needed — misplaced keywords make
312        // the primary unparseable, which is the same KEEL-E001.
313        let tokens: Vec<&str> = s.split_whitespace().collect();
314        if tokens.is_empty() {
315            return Err(err());
316        }
317        let mut segments = Vec::new();
318        for segment_tokens in tokens.split(|t| *t == "andThen") {
319            let (primary_tokens, up_to_ms) = match segment_tokens.iter().position(|t| *t == "upTo")
320            {
321                None => (segment_tokens, None),
322                Some(pos) => {
323                    // exactly `upTo <duration>`, at the segment's tail
324                    let [duration] = &segment_tokens[pos + 1..] else {
325                        return Err(err());
326                    };
327                    let bound = duration.parse::<DurationMs>().map_err(|_| err())?.0;
328                    (&segment_tokens[..pos], Some(bound))
329                }
330            };
331            if primary_tokens.is_empty() {
332                return Err(err());
333            }
334            let primary: SchedulePrimary = primary_tokens.join(" ").parse().map_err(|_| err())?;
335            segments.push(ScheduleSegment { primary, up_to_ms });
336        }
337        // Shape rule (normative, conformance/README.md "Schedule algebra"):
338        // bounded exactly on the non-final segments, so every segment is
339        // reachable and every attempt has a wait.
340        let last = segments.len() - 1;
341        if segments
342            .iter()
343            .enumerate()
344            .any(|(i, segment)| (i < last) != segment.up_to_ms.is_some())
345        {
346            return Err(ParseError::with_note(
347                "schedule",
348                s,
349                "`upTo` must bound every segment except the last, and never the last \
350                 (an unbounded segment never hands off; a bounded tail would leave \
351                 attempts without a wait — cap total retrying with `attempts`)",
352            ));
353        }
354        Ok(Self { segments })
355    }
356}
357
358impl TryFrom<String> for Schedule {
359    type Error = ParseError;
360
361    fn try_from(s: String) -> Result<Self, Self::Error> {
362        s.parse()
363    }
364}
365
366/// One retryable-error condition from `retry.on` (closed set; unknown
367/// conditions fail configuration instead of silently never matching).
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
369#[serde(try_from = "String")]
370pub enum Condition {
371    Conn,
372    Timeout,
373    Cancelled,
374    Other,
375    Class4xx,
376    Class5xx,
377    Status(u16),
378}
379
380impl Condition {
381    pub fn matches(self, class: ErrorClass, http_status: Option<u16>) -> bool {
382        match self {
383            Self::Conn => class == ErrorClass::Conn,
384            Self::Timeout => class == ErrorClass::Timeout,
385            Self::Cancelled => class == ErrorClass::Cancelled,
386            Self::Other => class == ErrorClass::Other,
387            Self::Class4xx => {
388                class == ErrorClass::Http && http_status.is_some_and(|s| (400..=499).contains(&s))
389            }
390            Self::Class5xx => {
391                class == ErrorClass::Http && http_status.is_some_and(|s| (500..=599).contains(&s))
392            }
393            Self::Status(want) => class == ErrorClass::Http && http_status == Some(want),
394        }
395    }
396}
397
398impl FromStr for Condition {
399    type Err = ParseError;
400
401    fn from_str(s: &str) -> Result<Self, Self::Err> {
402        match s {
403            "conn" => Ok(Self::Conn),
404            "timeout" => Ok(Self::Timeout),
405            "cancelled" => Ok(Self::Cancelled),
406            "other" => Ok(Self::Other),
407            "4xx" => Ok(Self::Class4xx),
408            "5xx" => Ok(Self::Class5xx),
409            // Frozen schema errorCondition grammar is `[1-5][0-9][0-9]` (100–599):
410            // require three ASCII digits in range, not any 3-char u16 (which
411            // accepted `099`→99 and `999`, outside the contract).
412            exact if exact.len() == 3 && exact.bytes().all(|b| b.is_ascii_digit()) => {
413                let code: u16 = exact
414                    .parse()
415                    .map_err(|_| ParseError::new("retry condition", s))?;
416                if (100..=599).contains(&code) {
417                    Ok(Self::Status(code))
418                } else {
419                    Err(ParseError::new("retry condition", s))
420                }
421            }
422            _ => Err(ParseError::new("retry condition", s)),
423        }
424    }
425}
426
427impl TryFrom<String> for Condition {
428    type Error = ParseError;
429
430    fn try_from(s: String) -> Result<Self, Self::Error> {
431        s.parse()
432    }
433}
434
435/// `retry = { attempts, schedule, on }`. `attempts` is the TOTAL attempt
436/// budget (first call included) — zero is unrepresentable by type.
437#[derive(Debug, Clone, PartialEq, Deserialize)]
438#[serde(default, deny_unknown_fields)]
439pub struct RetryPolicy {
440    pub attempts: NonZeroU32,
441    pub schedule: Schedule,
442    pub on: Vec<Condition>,
443}
444
445impl RetryPolicy {
446    pub const DEFAULT_ATTEMPTS: NonZeroU32 = NonZeroU32::new(3).unwrap();
447
448    /// The contract default retryable set: `["conn", "timeout", "429", "5xx"]`.
449    pub fn default_on() -> Vec<Condition> {
450        vec![
451            Condition::Conn,
452            Condition::Timeout,
453            Condition::Status(429),
454            Condition::Class5xx,
455        ]
456    }
457
458    pub fn is_retryable(&self, class: ErrorClass, http_status: Option<u16>) -> bool {
459        self.on.iter().any(|c| c.matches(class, http_status))
460    }
461}
462
463impl Default for RetryPolicy {
464    fn default() -> Self {
465        Self {
466            attempts: Self::DEFAULT_ATTEMPTS,
467            schedule: Schedule::default(),
468            on: Self::default_on(),
469        }
470    }
471}
472
473/// `breaker = { failures, cooldown, window, failure_rate, min_calls }`.
474///
475/// Two modes per the frozen schema (`$defs/breaker`), enforced identically by
476/// the real core and every stub — normative rules in `conformance/README.md`:
477/// - **count mode**: selected when `failures` is set (or no rate knob is set;
478///   `failures` then defaults to 5) — `failures` consecutive terminal failures
479///   open the breaker.
480/// - **rate mode**: selected when `failures` is absent and both `window` and
481///   `failure_rate` are set — trips when the trailing `window` holds at least
482///   `min_calls` outcomes (default 10) with `failed/total >= failure_rate`.
483///
484/// A rate-mode knob without both `window` and `failure_rate` (and without
485/// `failures`) is rejected at deserialize time (KEEL-E001): a half-configured
486/// mode must fail loudly, never silently degrade to count-mode defaults.
487#[derive(Debug, Clone, PartialEq, Deserialize)]
488#[serde(try_from = "BreakerPolicyDe")]
489pub struct BreakerPolicy {
490    /// Count-mode threshold. `None` means "not set by the user" — see
491    /// [`BreakerPolicy::mode`] for how that selects the mode.
492    pub failures: Option<NonZeroU64>,
493    pub cooldown: DurationMs,
494    pub window: Option<DurationMs>,
495    pub failure_rate: Option<f64>,
496    pub min_calls: Option<NonZeroU32>,
497}
498
499/// The breaker mode a [`BreakerPolicy`] resolves to, with every default
500/// applied — the engine/stubs consume this, never the raw knobs.
501#[derive(Debug, Clone, Copy, PartialEq)]
502pub enum BreakerMode {
503    /// `failures` consecutive terminal failures open the breaker.
504    Count { failures: NonZeroU64 },
505    /// Failure-rate tripping over a sliding window of post-retry outcomes.
506    Rate {
507        window: DurationMs,
508        failure_rate: f64,
509        min_calls: NonZeroU32,
510    },
511}
512
513impl BreakerPolicy {
514    /// Schema default for count mode's `failures`.
515    pub const DEFAULT_FAILURES: NonZeroU64 = NonZeroU64::new(5).unwrap();
516    /// Schema default for rate mode's `min_calls`.
517    pub const DEFAULT_MIN_CALLS: NonZeroU32 = NonZeroU32::new(10).unwrap();
518
519    /// The mode this policy selects (schema: "Setting `failures` selects count
520    /// mode"), with defaults applied. Deserialization already rejected
521    /// half-configured rate mode, so `window`+`failure_rate` are either both
522    /// present or irrelevant here.
523    #[must_use]
524    pub fn mode(&self) -> BreakerMode {
525        match (self.failures, self.window, self.failure_rate) {
526            (None, Some(window), Some(failure_rate)) => BreakerMode::Rate {
527                window,
528                failure_rate,
529                min_calls: self.min_calls.unwrap_or(Self::DEFAULT_MIN_CALLS),
530            },
531            (failures, _, _) => BreakerMode::Count {
532                failures: failures.unwrap_or(Self::DEFAULT_FAILURES),
533            },
534        }
535    }
536
537    /// Whether count mode was selected *while* rate-mode knobs are present —
538    /// those knobs are inert (the schema's precedence), which callers may want
539    /// to surface loudly rather than leave silent.
540    #[must_use]
541    pub fn has_inert_rate_knobs(&self) -> bool {
542        self.failures.is_some()
543            && (self.window.is_some() || self.failure_rate.is_some() || self.min_calls.is_some())
544    }
545}
546
547/// The raw deserialized shape of `breaker`, before mode-completeness
548/// validation promotes it to [`BreakerPolicy`].
549#[derive(Deserialize)]
550#[serde(default, deny_unknown_fields)]
551struct BreakerPolicyDe {
552    failures: Option<NonZeroU64>,
553    cooldown: DurationMs,
554    window: Option<DurationMs>,
555    #[serde(deserialize_with = "de_failure_rate")]
556    failure_rate: Option<f64>,
557    min_calls: Option<NonZeroU32>,
558}
559
560impl Default for BreakerPolicyDe {
561    fn default() -> Self {
562        Self {
563            failures: None,
564            cooldown: DurationMs(15_000),
565            window: None,
566            failure_rate: None,
567            min_calls: None,
568        }
569    }
570}
571
572impl TryFrom<BreakerPolicyDe> for BreakerPolicy {
573    type Error = String;
574
575    fn try_from(de: BreakerPolicyDe) -> Result<Self, Self::Error> {
576        let rate_pair = de.window.is_some() && de.failure_rate.is_some();
577        let any_rate_knob =
578            de.window.is_some() || de.failure_rate.is_some() || de.min_calls.is_some();
579        if de.failures.is_none() && any_rate_knob && !rate_pair {
580            return Err(String::from(
581                "breaker rate mode requires both `window` and `failure_rate` \
582                 (count mode sets `failures` instead)",
583            ));
584        }
585        Ok(Self {
586            failures: de.failures,
587            cooldown: de.cooldown,
588            window: de.window,
589            failure_rate: de.failure_rate,
590            min_calls: de.min_calls,
591        })
592    }
593}
594
595/// Validate `breaker.failure_rate` against the frozen schema range
596/// (`exclusiveMinimum: 0, maximum: 1`) at deserialize time, so an out-of-range or
597/// NaN value fails configuration with a precise field path (`KEEL-E001`) instead
598/// of being silently accepted — the bare `f64` used to take any value.
599fn de_failure_rate<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
600where
601    D: serde::Deserializer<'de>,
602{
603    let value = Option::<f64>::deserialize(deserializer)?;
604    if let Some(rate) = value
605        && !(rate > 0.0 && rate <= 1.0)
606    {
607        return Err(serde::de::Error::custom(format!(
608            "breaker.failure_rate must be greater than 0 and at most 1 (got {rate})"
609        )));
610    }
611    Ok(value)
612}
613
614impl Default for BreakerPolicy {
615    fn default() -> Self {
616        Self {
617            failures: None,
618            cooldown: DurationMs(15_000),
619            window: None,
620            failure_rate: None,
621            min_calls: None,
622        }
623    }
624}
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
627#[serde(rename_all = "snake_case")]
628pub enum CacheScope {
629    #[default]
630    Memory,
631    Persistent,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
635#[serde(rename_all = "snake_case")]
636pub enum CacheMode {
637    #[default]
638    Always,
639    /// Caches only when `KEEL_ENV != prod` — the LLM dev-loop cache.
640    Dev,
641}
642
643#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
644#[serde(rename_all = "snake_case")]
645pub enum CacheKeySource {
646    #[default]
647    Args,
648    Url,
649}
650
651/// `cache = { ttl, scope, mode, key }`. Caching activates only with a `ttl`.
652#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
653#[serde(default, deny_unknown_fields)]
654pub struct CachePolicy {
655    pub ttl: Option<DurationMs>,
656    pub scope: CacheScope,
657    pub mode: CacheMode,
658    pub key: CacheKeySource,
659}
660
661/// `idempotency = { header }` — the header is required by the schema.
662#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
663#[serde(deny_unknown_fields)]
664pub struct IdempotencyPolicy {
665    pub header: String,
666}
667
668/// `until = { field, terminal }` — the poll's terminal predicate (CCR-3).
669/// Non-emptiness is enforced at deserialize so an unpollable predicate is
670/// KEEL-E001 at configure, never a silent never-terminal loop.
671#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
672#[serde(try_from = "PollUntilRaw")]
673pub struct PollUntil {
674    pub field: String,
675    pub terminal: Vec<String>,
676}
677
678#[derive(Deserialize)]
679#[serde(deny_unknown_fields)]
680struct PollUntilRaw {
681    field: String,
682    terminal: Vec<String>,
683}
684
685impl TryFrom<PollUntilRaw> for PollUntil {
686    type Error = ParseError;
687
688    fn try_from(raw: PollUntilRaw) -> Result<Self, Self::Error> {
689        if raw.field.is_empty() {
690            return Err(ParseError::new("poll until.field", "(empty)"));
691        }
692        if raw.terminal.is_empty() {
693            return Err(ParseError::new("poll until.terminal", "(empty array)"));
694        }
695        Ok(Self {
696            field: raw.field,
697            terminal: raw.terminal,
698        })
699    }
700}
701
702/// `poll = { interval, deadline, until }` — poll-until-terminal (CCR-3).
703/// GET/HEAD at Level 0 only; semantics in conformance/README.md ("Poll").
704/// `interval` must be nonzero: on a virtual clock a zero interval never
705/// approaches `deadline`, looping forever, so it is rejected at deserialize
706/// (KEEL-E001) rather than left to hang at runtime.
707#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
708#[serde(try_from = "PollPolicyRaw")]
709pub struct PollPolicy {
710    pub interval: DurationMs,
711    pub deadline: DurationMs,
712    pub until: PollUntil,
713}
714
715#[derive(Deserialize)]
716#[serde(deny_unknown_fields)]
717struct PollPolicyRaw {
718    interval: DurationMs,
719    deadline: DurationMs,
720    until: PollUntil,
721}
722
723impl TryFrom<PollPolicyRaw> for PollPolicy {
724    type Error = ParseError;
725
726    fn try_from(raw: PollPolicyRaw) -> Result<Self, Self::Error> {
727        if raw.interval.0 == 0 {
728            return Err(ParseError::with_note(
729                "poll.interval",
730                "0",
731                "must be a nonzero duration",
732            ));
733        }
734        Ok(Self {
735            interval: raw.interval,
736            deadline: raw.deadline,
737            until: raw.until,
738        })
739    }
740}
741
742/// One target's policy table. Every layer is optional; a layer set at a more
743/// specific level replaces the whole layer table (no deep merge).
744#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
745#[serde(default, deny_unknown_fields)]
746pub struct TargetPolicy {
747    pub timeout: Option<DurationMs>,
748    pub retry: Option<RetryPolicy>,
749    pub breaker: Option<BreakerPolicy>,
750    pub rate: Option<Rate>,
751    pub cache: Option<CachePolicy>,
752    pub idempotency: Option<IdempotencyPolicy>,
753    pub poll: Option<PollPolicy>,
754    pub fallback: Option<Vec<String>>,
755    pub budget: Option<String>,
756}
757
758#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
759#[serde(default, deny_unknown_fields)]
760pub struct Defaults {
761    pub outbound: Option<TargetPolicy>,
762    pub llm: Option<TargetPolicy>,
763}
764
765#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
766#[serde(rename_all = "snake_case")]
767pub enum NondeterminismResponse {
768    #[default]
769    Fail,
770    Warn,
771    Branch,
772}
773
774/// What a concurrent same-identity `keel exec` does while the lease is held
775/// by a live process (CCR-4). Default `skip` — the mkdir-mutex pattern.
776#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
777#[serde(rename_all = "snake_case")]
778pub enum OnBusy {
779    #[default]
780    Skip,
781    Wait,
782    Fail,
783}
784
785/// One `[flows.match."cmd:<name>"]` rule (CCR-5): the argv patterns an
786/// in-process subprocess call site must match to be dispatched as this `cmd:`
787/// flow. `argv` is a list of per-position patterns (single-`*` wildcard
788/// dialect, docs/targeting.md); parsed and carried here, the matching itself
789/// lives in the front-end interceptors. Only in-process interception consults
790/// these — `keel exec` matches the argv typed after `--`.
791#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
792#[serde(deny_unknown_fields)]
793pub struct FlowMatchRule {
794    pub argv: Vec<String>,
795}
796
797/// Tier 2 flow designation — parsed and carried, enforced by the real core.
798#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
799#[serde(default, deny_unknown_fields)]
800pub struct FlowsPolicy {
801    pub entrypoints: Vec<String>,
802    pub on_nondeterminism: NondeterminismResponse,
803    pub on_busy: OnBusy,
804    /// `[flows.match."cmd:<name>"]` argv match rules (CCR-5), keyed by the
805    /// `cmd:<name>` entrypoint string. Parsed and carried structurally so a
806    /// keel.toml with a `[flows.match]` table configures cleanly; the
807    /// front-end subprocess interceptors are the only consumers, not the
808    /// core. `None` when the table is absent. A `BTreeMap` (not `HashMap`)
809    /// so iteration is deterministic, matching `Policy::target`.
810    #[serde(rename = "match")]
811    pub match_: Option<BTreeMap<String, FlowMatchRule>>,
812}
813
814/// A journal location literal (`policy.journal`), validated against the frozen
815/// schema pattern `^(file:.+|postgres://.+)$` at parse time so a malformed value
816/// fails configuration (KEEL-E001) rather than being silently ignored. The real
817/// core honors it at configure time: `file:` attaches a SQLite journal at that
818/// path (replacing the construction-time default), and `postgres://` fails
819/// loudly with KEEL-E005 until a Postgres backend ships.
820#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
821#[serde(try_from = "String")]
822pub struct JournalLocation(pub String);
823
824impl FromStr for JournalLocation {
825    type Err = ParseError;
826
827    fn from_str(s: &str) -> Result<Self, Self::Err> {
828        let valid = s.strip_prefix("file:").is_some_and(|rest| !rest.is_empty())
829            || s.strip_prefix("postgres://")
830                .is_some_and(|rest| !rest.is_empty());
831        if valid {
832            Ok(Self(s.to_owned()))
833        } else {
834            Err(ParseError::new("journal location", s))
835        }
836    }
837}
838
839impl TryFrom<String> for JournalLocation {
840    type Error = ParseError;
841
842    fn try_from(s: String) -> Result<Self, Self::Error> {
843        s.parse()
844    }
845}
846
847/// `[telemetry]` (`otlp_endpoint`, `console`). Parsed and carried; `Engine`
848/// exposes `otlp_endpoint` back to native front ends (`telemetry_otlp_endpoint`)
849/// which feed it to `keel-core`'s `otel::init_otlp` when built with the `otel`
850/// feature — the standard `OTEL_*` environment variables take precedence over
851/// this table (see `keel-core`'s otel module for the exact precedence rules).
852/// `console` (the local pretty-console-summary switch) is validated and
853/// carried but has no consumer yet; `Engine::configure` warns on an explicit
854/// `false` so the user is not silently surprised.
855#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
856#[serde(default, deny_unknown_fields)]
857pub struct TelemetryPolicy {
858    pub otlp_endpoint: Option<String>,
859    pub console: bool,
860}
861
862impl Default for TelemetryPolicy {
863    fn default() -> Self {
864        // Schema default: console = true.
865        Self {
866            otlp_endpoint: None,
867            console: true,
868        }
869    }
870}
871
872/// The whole `keel.toml` document (contracts/policy.schema.json), typed.
873///
874/// `deny_unknown_fields` at every object level (here and on the layer structs)
875/// makes a typo'd or unknown key a configuration error (KEEL-E001 with the exact
876/// path via `serde_path_to_error`), honoring the frozen schema's
877/// `additionalProperties: false` and E001's "an unknown key was used" — instead
878/// of the previous silent drop that ran the target on defaults the user never
879/// asked for.
880#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
881#[serde(default, deny_unknown_fields)]
882pub struct Policy {
883    pub defaults: Defaults,
884    pub target: BTreeMap<String, TargetPolicy>,
885    pub flows: Option<FlowsPolicy>,
886    /// Journal location (schema-validated), honored by the real core at
887    /// configure time (see [`JournalLocation`]).
888    pub journal: Option<JournalLocation>,
889    /// Telemetry config (schema-validated); `otlp_endpoint` is honored by
890    /// native front ends (env still wins), `console` is not yet wired — see
891    /// [`TelemetryPolicy`].
892    pub telemetry: Option<TelemetryPolicy>,
893}
894
895/// The per-layer config resolved for one target: target entry, else
896/// `defaults.llm` for `llm:*` targets, else `defaults.outbound`.
897#[derive(Debug, Clone, Default)]
898pub struct ResolvedPolicy {
899    pub timeout: Option<DurationMs>,
900    pub retry: Option<RetryPolicy>,
901    pub breaker: Option<BreakerPolicy>,
902    pub rate: Option<Rate>,
903    pub cache: Option<CachePolicy>,
904    /// `idempotency = { header }` — the knob adapters consult to *inject* a
905    /// minted idempotency key on unsafe-method calls (and to recognize a
906    /// caller-supplied one). The core itself never injects; injection lives in
907    /// the adapter per contracts/adapter-pack.md ("Idempotency-key injection").
908    pub idempotency: Option<IdempotencyPolicy>,
909    /// `poll = { interval, deadline, until }` — poll-until-terminal (CCR-3).
910    pub poll: Option<PollPolicy>,
911}
912
913impl Policy {
914    pub fn resolve(&self, target: &str) -> ResolvedPolicy {
915        ResolvedPolicy {
916            timeout: self.layer(target, |t| t.timeout.as_ref()).copied(),
917            retry: self.layer(target, |t| t.retry.as_ref()).cloned(),
918            breaker: self.layer(target, |t| t.breaker.as_ref()).cloned(),
919            rate: self.layer(target, |t| t.rate.as_ref()).copied(),
920            cache: self.layer(target, |t| t.cache.as_ref()).cloned(),
921            idempotency: self.layer(target, |t| t.idempotency.as_ref()).cloned(),
922            poll: self.layer(target, |t| t.poll.as_ref()).cloned(),
923        }
924    }
925
926    fn layer<'a, T>(
927        &'a self,
928        target: &str,
929        pick: impl Fn(&'a TargetPolicy) -> Option<&'a T>,
930    ) -> Option<&'a T> {
931        if let Some(t) = self.target.get(target)
932            && let Some(v) = pick(t)
933        {
934            return Some(v);
935        }
936        if target.starts_with("llm:")
937            && let Some(llm) = self.defaults.llm.as_ref()
938            && let Some(v) = pick(llm)
939        {
940            return Some(v);
941        }
942        self.defaults.outbound.as_ref().and_then(pick)
943    }
944}
945
946#[cfg(test)]
947mod tests {
948    use super::*;
949    use serde_json::json;
950
951    #[test]
952    fn duration_literals() {
953        assert_eq!("200ms".parse(), Ok(DurationMs(200)));
954        assert_eq!("30s".parse(), Ok(DurationMs(30_000)));
955        assert_eq!("5m".parse(), Ok(DurationMs(300_000)));
956        assert_eq!("2h".parse(), Ok(DurationMs(7_200_000)));
957        assert!("30".parse::<DurationMs>().is_err());
958        assert!("30sec".parse::<DurationMs>().is_err());
959        assert!("-1s".parse::<DurationMs>().is_err());
960    }
961
962    #[test]
963    fn rate_literals() {
964        let rate: Rate = "90/s".parse().unwrap();
965        assert_eq!((rate.limit.get(), rate.window_ms), (90, 1_000));
966        let rate: Rate = "60/min".parse().unwrap();
967        assert_eq!((rate.limit.get(), rate.window_ms), (60, 60_000));
968        assert!("0/s".parse::<Rate>().is_err(), "zero limit unrepresentable");
969        assert!("10/day".parse::<Rate>().is_err());
970    }
971
972    #[test]
973    fn schedule_exp_waits_and_cap() {
974        let schedule: Schedule = "exp(1s, x2, max 4s)".parse().unwrap();
975        let waits: Vec<u64> = (1..=4).map(|n| schedule.wait_ms(n)).collect();
976        assert_eq!(waits, [1_000, 2_000, 4_000, 4_000]);
977    }
978
979    #[test]
980    fn schedule_fixed_and_rejections() {
981        assert_eq!(
982            "fixed(1s)".parse::<Schedule>(),
983            Ok(Schedule {
984                segments: vec![ScheduleSegment {
985                    primary: SchedulePrimary::Fixed { period_ms: 1_000 },
986                    up_to_ms: None,
987                }],
988            })
989        );
990        assert!("linear(1s)".parse::<Schedule>().is_err());
991    }
992
993    #[test]
994    fn schedule_composition_parses_the_spec_example() {
995        // architecture-spec §4.1 / the frozen grammar's own example
996        let schedule: Schedule = "exp(1s, x2, max 5m) upTo 10m andThen fixed(1m)"
997            .parse()
998            .unwrap();
999        assert_eq!(
1000            schedule.segments,
1001            vec![
1002                ScheduleSegment {
1003                    primary: SchedulePrimary::Exp {
1004                        base_ms: 1_000,
1005                        factor: 2.0,
1006                        cap_ms: 300_000,
1007                        jitter: false,
1008                    },
1009                    up_to_ms: Some(600_000),
1010                },
1011                ScheduleSegment {
1012                    primary: SchedulePrimary::Fixed { period_ms: 60_000 },
1013                    up_to_ms: None,
1014                },
1015            ]
1016        );
1017        // The grammar's ws is "one or more spaces": extra spacing still parses.
1018        assert_eq!(
1019            "exp(1s, x2, max 5m)  upTo  10m  andThen  fixed(1m)".parse::<Schedule>(),
1020            Ok(schedule)
1021        );
1022    }
1023
1024    #[test]
1025    fn schedule_composition_hands_off_when_the_bound_would_be_overshot() {
1026        let schedule: Schedule = "exp(1s, x2) upTo 4s andThen fixed(500ms)".parse().unwrap();
1027        let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
1028        // 1s + 2s = 3s fits; the natural 4s would overshoot the 4s bound.
1029        assert_eq!(waits, [1_000, 2_000, 500, 500, 500]);
1030    }
1031
1032    #[test]
1033    fn schedule_composition_exact_fit_stays_and_cascade_skips() {
1034        let schedule: Schedule =
1035            "fixed(1s) upTo 3s andThen fixed(10s) upTo 5s andThen fixed(250ms)"
1036                .parse()
1037                .unwrap();
1038        let waits: Vec<u64> = (1..=6).map(|n| schedule.wait_ms(n)).collect();
1039        // Three 1s waits fill upTo 3s exactly (e + w == bound stays); the 10s
1040        // segment's first wait exceeds its own 5s bound, so it contributes
1041        // zero waits and the handoff cascades to the 250ms tail.
1042        assert_eq!(waits, [1_000, 1_000, 1_000, 250, 250, 250]);
1043    }
1044
1045    #[test]
1046    fn schedule_composition_restarts_exp_and_tracks_jitter_per_segment() {
1047        let schedule: Schedule = "fixed(1s) upTo 2s andThen exp(100ms, x3, jitter)"
1048            .parse()
1049            .unwrap();
1050        // exp restarts at local attempt 1 after the handoff.
1051        let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
1052        assert_eq!(waits, [1_000, 1_000, 100, 300, 900]);
1053        // jitter is the emitting segment's flag, not schedule-global.
1054        assert_eq!(schedule.wait_and_jitter(1), (1_000, false));
1055        assert_eq!(schedule.wait_and_jitter(3), (100, true));
1056    }
1057
1058    #[test]
1059    fn schedule_composition_shape_rule_rejections() {
1060        // Grammatical but invalid shapes fail configure-time (KEEL-E001), per
1061        // conformance/README.md "Schedule algebra": a non-final segment
1062        // without upTo never hands off; a bounded final segment would leave
1063        // attempts without a wait.
1064        for degenerate in [
1065            "fixed(1s) andThen fixed(2s)",
1066            "exp(1s, x2, max 5m) upTo 10m",
1067            "fixed(1s) upTo 3s andThen fixed(2s) andThen fixed(4s)",
1068            "fixed(1s) upTo 3s andThen fixed(2s) upTo 5s",
1069        ] {
1070            let error = degenerate.parse::<Schedule>().unwrap_err();
1071            assert!(
1072                error.to_string().contains("upTo"),
1073                "{degenerate}: expected the shape-rule note, got {error}"
1074            );
1075        }
1076        // Broken composition syntax stays a plain parse rejection.
1077        for broken in [
1078            "fixed(1s) upTo",
1079            "upTo 3s andThen fixed(1s)",
1080            "fixed(1s) upTo 1s upTo 2s andThen fixed(1s)",
1081            "fixed(1s) andThen",
1082            "andThen fixed(1s)",
1083            "fixed(1s) upTo 3s fixed(2s)",
1084        ] {
1085            assert!(
1086                broken.parse::<Schedule>().is_err(),
1087                "{broken} must be rejected"
1088            );
1089        }
1090    }
1091
1092    #[test]
1093    fn condition_matching() {
1094        let on = RetryPolicy::default_on();
1095        let matches = |class, status| on.iter().any(|c| c.matches(class, status));
1096        assert!(matches(ErrorClass::Conn, None));
1097        assert!(matches(ErrorClass::Http, Some(429)));
1098        assert!(matches(ErrorClass::Http, Some(503)));
1099        assert!(!matches(ErrorClass::Http, Some(400)));
1100        assert!(!matches(ErrorClass::Cancelled, None));
1101        assert!("teapot".parse::<Condition>().is_err());
1102        // Exact-status literals follow the frozen schema grammar [1-5][0-9][0-9].
1103        assert_eq!("429".parse::<Condition>(), Ok(Condition::Status(429)));
1104        assert_eq!("100".parse::<Condition>(), Ok(Condition::Status(100)));
1105        assert_eq!("599".parse::<Condition>(), Ok(Condition::Status(599)));
1106        for bad in ["999", "099", "600", "000", "12", "1234", "1x9"] {
1107            assert!(bad.parse::<Condition>().is_err(), "{bad} must be rejected");
1108        }
1109    }
1110
1111    #[test]
1112    fn zero_attempts_is_unrepresentable() {
1113        let doc = json!({ "target": { "x": { "retry": { "attempts": 0 } } } });
1114        let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
1115        assert_eq!(err.path().to_string(), "target.x.retry.attempts");
1116    }
1117
1118    #[test]
1119    fn breaker_failure_rate_range_is_enforced() {
1120        // Frozen schema: breaker.failure_rate is exclusiveMinimum 0, maximum 1.
1121        let bad = |rate: serde_json::Value| {
1122            let doc = json!({ "target": { "x": { "breaker": { "failure_rate": rate } } } });
1123            serde_path_to_error::deserialize::<_, Policy>(&doc)
1124        };
1125        for rate in [json!(0.0), json!(-0.1), json!(1.5), json!(2.0)] {
1126            let err = bad(rate.clone()).unwrap_err();
1127            assert_eq!(
1128                err.path().to_string(),
1129                "target.x.breaker.failure_rate",
1130                "out-of-range failure_rate {rate} must fail at its path"
1131            );
1132        }
1133        // In-range values (0, 1] deserialize fine (paired with `window`:
1134        // rate mode requires both knobs).
1135        for rate in [0.01_f64, 0.5, 1.0] {
1136            let doc = json!({
1137                "target": { "x": { "breaker": { "window": "30s", "failure_rate": rate } } }
1138            });
1139            let policy = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap();
1140            let breaker = policy.target["x"].breaker.as_ref().unwrap();
1141            assert_eq!(breaker.failure_rate, Some(rate));
1142        }
1143    }
1144
1145    #[test]
1146    fn breaker_mode_selection_follows_the_schema() {
1147        let breaker = |doc: serde_json::Value| -> BreakerPolicy {
1148            let doc = json!({ "target": { "x": { "breaker": doc } } });
1149            let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1150            policy.target["x"].breaker.clone().unwrap()
1151        };
1152
1153        // Empty table: count mode on the schema default (failures = 5).
1154        assert_eq!(
1155            breaker(json!({})).mode(),
1156            BreakerMode::Count {
1157                failures: BreakerPolicy::DEFAULT_FAILURES
1158            }
1159        );
1160
1161        // Both rate knobs, no `failures`: rate mode, min_calls defaults to 10.
1162        assert_eq!(
1163            breaker(json!({ "window": "30s", "failure_rate": 0.5 })).mode(),
1164            BreakerMode::Rate {
1165                window: DurationMs(30_000),
1166                failure_rate: 0.5,
1167                min_calls: BreakerPolicy::DEFAULT_MIN_CALLS,
1168            }
1169        );
1170        assert_eq!(
1171            breaker(json!({ "window": "10s", "failure_rate": 1.0, "min_calls": 4 })).mode(),
1172            BreakerMode::Rate {
1173                window: DurationMs(10_000),
1174                failure_rate: 1.0,
1175                min_calls: NonZeroU32::new(4).unwrap(),
1176            }
1177        );
1178
1179        // "Setting `failures` selects count mode" (frozen schema): rate knobs
1180        // present alongside it are inert, and the policy says so.
1181        let mixed = breaker(json!({ "failures": 3, "window": "30s", "failure_rate": 0.5 }));
1182        assert_eq!(
1183            mixed.mode(),
1184            BreakerMode::Count {
1185                failures: NonZeroU64::new(3).unwrap()
1186            }
1187        );
1188        assert!(mixed.has_inert_rate_knobs());
1189        assert!(!breaker(json!({ "failures": 3 })).has_inert_rate_knobs());
1190    }
1191
1192    #[test]
1193    fn half_configured_breaker_rate_mode_is_rejected() {
1194        // A rate-mode knob without both `window` and `failure_rate` (and
1195        // without `failures`) must fail at configure, not silently run count
1196        // mode the user never asked for.
1197        for doc in [
1198            json!({ "window": "30s" }),
1199            json!({ "failure_rate": 0.5 }),
1200            json!({ "min_calls": 10 }),
1201            json!({ "window": "30s", "min_calls": 10 }),
1202            json!({ "failure_rate": 0.5, "min_calls": 10 }),
1203        ] {
1204            let policy = json!({ "target": { "x": { "breaker": doc } } });
1205            let err = serde_path_to_error::deserialize::<_, Policy>(&policy).unwrap_err();
1206            assert_eq!(err.path().to_string(), "target.x.breaker", "doc: {doc}");
1207            assert!(
1208                err.inner().to_string().contains("rate mode requires both"),
1209                "doc {doc}: got {}",
1210                err.inner()
1211            );
1212        }
1213        // `failures` present makes any knob combination count mode (schema
1214        // precedence), so those documents stay valid.
1215        let policy =
1216            json!({ "target": { "x": { "breaker": { "failures": 3, "window": "30s" } } } });
1217        assert!(serde_path_to_error::deserialize::<_, Policy>(&policy).is_ok());
1218    }
1219
1220    #[test]
1221    fn unknown_key_is_rejected_with_its_path() {
1222        // A typo'd nested key: the frozen schema's additionalProperties:false and
1223        // E001's "an unknown key was used" mean this must fail, not silently run
1224        // on the defaults.
1225        let doc = json!({ "target": { "api.stripe.com": { "retry": { "atempts": 10 } } } });
1226        let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
1227        assert!(
1228            err.inner().to_string().contains("atempts")
1229                || err.inner().to_string().contains("unknown field"),
1230            "expected an unknown-field error, got {}",
1231            err.inner()
1232        );
1233    }
1234
1235    #[test]
1236    fn unknown_top_level_and_layer_keys_are_rejected() {
1237        assert!(
1238            serde_path_to_error::deserialize::<_, Policy>(&json!({ "bogus_top": true })).is_err()
1239        );
1240        assert!(
1241            serde_path_to_error::deserialize::<_, Policy>(
1242                &json!({ "target": { "api.x": { "retrys": {} } } })
1243            )
1244            .is_err(),
1245            "a mistyped layer table must be rejected, not dropped"
1246        );
1247    }
1248
1249    #[test]
1250    fn journal_and_telemetry_parse_and_validate() {
1251        let doc = json!({
1252            "journal": "file:/srv/keel/journal.db",
1253            "telemetry": { "otlp_endpoint": "http://collector:4317" }
1254        });
1255        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1256        assert_eq!(
1257            policy.journal.unwrap(),
1258            JournalLocation("file:/srv/keel/journal.db".to_owned())
1259        );
1260        let telemetry = policy.telemetry.unwrap();
1261        assert_eq!(
1262            telemetry.otlp_endpoint.as_deref(),
1263            Some("http://collector:4317")
1264        );
1265        assert!(telemetry.console, "schema default console = true");
1266
1267        // A journal string that matches neither `file:` nor `postgres://` fails.
1268        let bad = json!({ "journal": "sqlite:/tmp/x.db" });
1269        assert!(serde_path_to_error::deserialize::<_, Policy>(&bad).is_err());
1270    }
1271
1272    #[test]
1273    fn idempotency_resolves_like_any_other_layer() {
1274        // The `idempotency` layer must surface through `resolve()` so adapters
1275        // (via the front ends) and the engine can honor the injection contract
1276        // (contracts/adapter-pack.md "Idempotency-key injection").
1277        let doc = json!({
1278            "defaults": {
1279                "outbound": { "idempotency": { "header": "X-Idem" } },
1280                "llm": { "idempotency": { "header": "X-Llm-Idem" } }
1281            },
1282            "target": {
1283                "api.stripe.com": { "idempotency": { "header": "Idempotency-Key" } },
1284                "api.plain.example": { "timeout": "1s" }
1285            }
1286        });
1287        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1288
1289        // Exact target entry wins.
1290        let stripe = policy.resolve("api.stripe.com");
1291        assert_eq!(
1292            stripe.idempotency.as_ref().map(|i| i.header.as_str()),
1293            Some("Idempotency-Key")
1294        );
1295        // llm:* falls to defaults.llm, then anything else to defaults.outbound.
1296        let llm = policy.resolve("llm:openai");
1297        assert_eq!(
1298            llm.idempotency.as_ref().map(|i| i.header.as_str()),
1299            Some("X-Llm-Idem")
1300        );
1301        let plain = policy.resolve("api.plain.example");
1302        assert_eq!(
1303            plain.idempotency.as_ref().map(|i| i.header.as_str()),
1304            Some("X-Idem")
1305        );
1306        // No idempotency anywhere: resolves to None.
1307        let empty: Policy = serde_path_to_error::deserialize(&json!({})).unwrap();
1308        assert!(empty.resolve("api.stripe.com").idempotency.is_none());
1309    }
1310
1311    #[test]
1312    fn poll_policy_parses_and_resolves() {
1313        let policy: Policy = serde_json::from_value(serde_json::json!({
1314            "target": { "api.jobs.example": { "poll": {
1315                "interval": "10s", "deadline": "90s",
1316                "until": { "field": "status", "terminal": ["completed", "failed"] }
1317            } } }
1318        }))
1319        .expect("valid poll policy");
1320        let resolved = policy.resolve("api.jobs.example");
1321        let poll = resolved.poll.expect("poll resolved");
1322        assert_eq!(poll.interval.0, 10_000);
1323        assert_eq!(poll.deadline.0, 90_000);
1324        assert_eq!(poll.until.field, "status");
1325        assert_eq!(poll.until.terminal, vec!["completed", "failed"]);
1326    }
1327
1328    #[test]
1329    fn poll_rejects_empty_terminal_and_empty_field() {
1330        for bad in [
1331            serde_json::json!({ "interval": "10s", "deadline": "90s",
1332                "until": { "field": "status", "terminal": [] } }),
1333            serde_json::json!({ "interval": "10s", "deadline": "90s",
1334                "until": { "field": "", "terminal": ["done"] } }),
1335            serde_json::json!({ "interval": "10s",
1336                "until": { "field": "status", "terminal": ["done"] } }),
1337        ] {
1338            let doc = serde_json::json!({ "target": { "x": { "poll": bad } } });
1339            assert!(serde_json::from_value::<Policy>(doc).is_err());
1340        }
1341    }
1342
1343    #[test]
1344    fn poll_rejects_zero_interval() {
1345        let doc = serde_json::json!({ "target": { "x": { "poll": {
1346            "interval": "0ms", "deadline": "90s",
1347            "until": { "field": "status", "terminal": ["done"] }
1348        } } } });
1349        assert!(serde_json::from_value::<Policy>(doc).is_err());
1350
1351        let doc = serde_json::json!({ "target": { "x": { "poll": {
1352            "interval": "1ms", "deadline": "90s",
1353            "until": { "field": "status", "terminal": ["done"] }
1354        } } } });
1355        assert!(serde_json::from_value::<Policy>(doc).is_ok());
1356    }
1357
1358    #[test]
1359    fn layer_resolution_precedence() {
1360        let doc = json!({
1361            "defaults": {
1362                "outbound": { "retry": { "attempts": 3 }, "rate": "9/s" },
1363                "llm": { "retry": { "attempts": 6 } }
1364            },
1365            "target": { "llm:openai": { "cache": { "ttl": "10m" } } }
1366        });
1367        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1368
1369        // llm:* target: cache from its own entry, retry from defaults.llm,
1370        // rate falls through to defaults.outbound
1371        let llm = policy.resolve("llm:openai");
1372        assert_eq!(llm.cache.unwrap().ttl, Some(DurationMs(600_000)));
1373        assert_eq!(llm.retry.unwrap().attempts.get(), 6);
1374        assert_eq!(llm.rate.unwrap().limit.get(), 9);
1375
1376        // plain target: everything from defaults.outbound
1377        let plain = policy.resolve("api.example.com");
1378        assert_eq!(plain.retry.unwrap().attempts.get(), 3);
1379        assert!(plain.cache.is_none());
1380    }
1381
1382    #[test]
1383    fn flows_on_busy_parses_with_skip_default() {
1384        let p: Policy = serde_json::from_value(serde_json::json!({
1385            "flows": { "entrypoints": ["cmd:autonomous-run"], "on_busy": "wait" }
1386        }))
1387        .unwrap();
1388        assert_eq!(p.flows.as_ref().unwrap().on_busy, OnBusy::Wait);
1389        let p: Policy = serde_json::from_value(serde_json::json!({ "flows": {} })).unwrap();
1390        assert_eq!(p.flows.unwrap().on_busy, OnBusy::Skip);
1391    }
1392
1393    #[test]
1394    fn flows_match_cmd_rules_parse() {
1395        // CCR-5: `[flows.match."cmd:<name>"] argv = [...]` parses structurally
1396        // into the carried `match_` map (renamed from the reserved `match`).
1397        let p: Policy = serde_json::from_value(serde_json::json!({
1398            "flows": {
1399                "entrypoints": ["cmd:nightly-etl"],
1400                "match": { "cmd:nightly-etl": { "argv": ["*/run_etl.sh", "--env=prod"] } }
1401            }
1402        }))
1403        .unwrap();
1404        let flows = p.flows.unwrap();
1405        let rules = flows.match_.expect("match table carried");
1406        assert_eq!(
1407            rules["cmd:nightly-etl"].argv,
1408            vec!["*/run_etl.sh".to_owned(), "--env=prod".to_owned()]
1409        );
1410        // Absent `[flows.match]` leaves `match_` None (struct-level default).
1411        let p: Policy = serde_json::from_value(serde_json::json!({ "flows": {} })).unwrap();
1412        assert!(p.flows.unwrap().match_.is_none());
1413        // An unknown key inside a rule is rejected (deny_unknown_fields).
1414        assert!(
1415            serde_json::from_value::<Policy>(serde_json::json!({
1416                "flows": { "match": { "cmd:x": { "argv": ["a"], "bogus": 1 } } }
1417            }))
1418            .is_err()
1419        );
1420    }
1421}