Skip to main content

adk_eval/
ledger.rs

1//! Ledger statistics: per-dimension baselines and drift detection over a content-free
2//! activity ledger (spec 3.2 §7.10, §10 E1).
3//!
4//! The agent kernel keeps an append-only, content-free activity ledger. This module holds
5//! the statistics over it as pure functions — no I/O and no model — so the kernel's
6//! maintenance tick and the `cargo adk eval --ledger` CI gate run the same code.
7//!
8//! | Rule | Value |
9//! |------|-------|
10//! | Baseline | Median and MAD over a rolling 28-day window, per dimension and [`DayClass`] |
11//! | Warm-up | 14 days with a value in the baseline window before a dimension can deviate |
12//! | Comparison windows | The last 7 and the last 14 days; a day class deviates only when both do |
13//! | Deviation | `\|recent − baseline\| > max(k·MAD, floor)`, k = 2.5, a floor per dimension |
14//! | Meaningful | Two dimensions deviating, or one deviating for 10 days running |
15//! | Cooldown | 7 days per dimension after an observation includes it |
16//!
17//! The baseline window ends the day before the 14-day comparison window starts, so a drift
18//! inside the comparison windows does not move the baseline it is measured against.
19//!
20//! The statistics take plain daily series — [`DailyValue`]s keyed by dimension name — so a
21//! caller that aggregates its own ledger store passes series directly. [`LedgerRow`] is the
22//! export format, one camelCase JSON object per line with the §7.10 columns, and
23//! [`daily_series`] derives the dimensions an export carries.
24//!
25//! # Example
26//!
27//! ```
28//! use std::collections::BTreeMap;
29//!
30//! use adk_eval::ledger::{DailyValue, DeviationConfig, assess};
31//! use chrono::{Days, NaiveDate};
32//!
33//! // Six weeks: four with the last activity at 17:30 and 20 tool calls a day, then two
34//! // with the last activity at 19:30 and 40 tool calls.
35//! let start = NaiveDate::from_ymd_opt(2026, 8, 31).unwrap();
36//! let daily = |before: f64, after: f64| -> Vec<DailyValue> {
37//!     (0..42)
38//!         .map(|day| DailyValue::new(start + Days::new(day), if day < 28 { before } else { after }))
39//!         .collect()
40//! };
41//! let series = BTreeMap::from([
42//!     ("activity.last_minute".to_string(), daily(1050.0, 1170.0)),
43//!     ("tool_call.count".to_string(), daily(20.0, 40.0)),
44//! ]);
45//!
46//! let assessment = assess(&series, &DeviationConfig::default()).unwrap();
47//! assert_eq!(assessment.report.deviating(), ["activity.last_minute", "tool_call.count"]);
48//! // Two deviating dimensions are a meaningful drift.
49//! assert!(assessment.meaningful);
50//! ```
51
52use std::collections::{BTreeMap, BTreeSet};
53
54use chrono::{DateTime, Datelike, Days, FixedOffset, NaiveDate, Timelike, Weekday};
55use serde::{Deserialize, Serialize};
56
57/// Days in the rolling baseline window (spec 3.2 §7.10).
58pub const BASELINE_WINDOW_DAYS: u32 = 28;
59
60/// Days with a value in the baseline window before a dimension can deviate (spec 3.2 §7.10).
61pub const WARM_UP_DAYS: u32 = 14;
62
63/// The comparison windows, in days, each ending on the day under test (spec 3.2 §7.10).
64pub const RECENT_WINDOW_DAYS: [u32; 2] = [7, 14];
65
66/// The MAD multiplier of the deviation test (spec 3.2 §7.10).
67pub const DEVIATION_K: f64 = 2.5;
68
69/// Deviating dimensions that make a drift meaningful on their own (spec 3.2 §7.10).
70pub const MEANINGFUL_DIMENSIONS: usize = 2;
71
72/// Days a single dimension deviates in a row before its drift is meaningful (spec 3.2 §7.10).
73pub const MEANINGFUL_RUN_DAYS: u32 = 10;
74
75/// Days after an observation before it can include the same dimension again (spec 3.2 §7.10).
76pub const COOLDOWN_DAYS: u32 = 7;
77
78/// The floor of the time-of-day dimensions [`daily_series`] derives, in minutes.
79///
80/// Spec 3.2 §7.10 takes its rules from Agentrix §8.2, which gives 45 minutes as the floor for
81/// the end of the working day.
82pub const ACTIVITY_MINUTE_FLOOR: f64 = 45.0;
83
84// ── Statistics ──────────────────────────────────────────────────
85
86/// Returns the median of the finite values, or `None` when there are none (spec 3.2 §7.10).
87///
88/// An even count takes the mean of the two middle values. NaN and infinite values are
89/// ignored.
90///
91/// # Example
92///
93/// ```
94/// use adk_eval::ledger::median;
95///
96/// assert_eq!(median(&[3.0, 1.0, 2.0]), Some(2.0));
97/// assert_eq!(median(&[4.0, 1.0, 2.0, 3.0]), Some(2.5));
98/// assert_eq!(median(&[f64::NAN]), None);
99/// ```
100pub fn median(values: &[f64]) -> Option<f64> {
101    let mut finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
102    if finite.is_empty() {
103        return None;
104    }
105    finite.sort_by(f64::total_cmp);
106    let mid = finite.len() / 2;
107    if finite.len().is_multiple_of(2) {
108        // Halving each value first cannot overflow.
109        Some(finite[mid - 1] / 2.0 + finite[mid] / 2.0)
110    } else {
111        Some(finite[mid])
112    }
113}
114
115/// Returns the median absolute deviation of the finite values from their median, or `None`
116/// when there are none (spec 3.2 §7.10).
117///
118/// The MAD is unscaled: the deviation test multiplies it by k = 2.5 directly. NaN and
119/// infinite values are ignored.
120///
121/// # Example
122///
123/// ```
124/// use adk_eval::ledger::mad;
125///
126/// // Median 2; absolute deviations 1, 0, 1, 7; their median is 1.
127/// assert_eq!(mad(&[1.0, 2.0, 3.0, 9.0]), Some(1.0));
128/// assert_eq!(mad(&[5.0, 5.0, 5.0]), Some(0.0));
129/// ```
130pub fn mad(values: &[f64]) -> Option<f64> {
131    let center = median(values)?;
132    let deviations: Vec<f64> = values
133        .iter()
134        .filter(|value| value.is_finite())
135        .map(|value| (value - center).abs())
136        .collect();
137    median(&deviations)
138}
139
140/// Whether a day is a weekday or a weekend day; baselines are kept per class (spec 3.2 §7.10).
141///
142/// # Example
143///
144/// ```
145/// use adk_eval::ledger::DayClass;
146/// use chrono::NaiveDate;
147///
148/// let saturday = NaiveDate::from_ymd_opt(2026, 10, 24).unwrap();
149/// assert_eq!(DayClass::of(saturday), DayClass::Weekend);
150/// ```
151#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153pub enum DayClass {
154    /// Monday to Friday.
155    Weekday,
156    /// Saturday and Sunday.
157    Weekend,
158}
159
160impl DayClass {
161    /// Both classes, weekday first.
162    pub const ALL: [DayClass; 2] = [DayClass::Weekday, DayClass::Weekend];
163
164    /// Returns the class of `date`.
165    pub fn of(date: NaiveDate) -> Self {
166        match date.weekday() {
167            Weekday::Sat | Weekday::Sun => DayClass::Weekend,
168            Weekday::Mon | Weekday::Tue | Weekday::Wed | Weekday::Thu | Weekday::Fri => {
169                DayClass::Weekday
170            }
171        }
172    }
173}
174
175/// One day's value of one dimension (spec 3.2 §7.10).
176///
177/// A series holds at most one value per day; a day without a value is absent, not zero.
178///
179/// # Example
180///
181/// ```
182/// use adk_eval::ledger::DailyValue;
183/// use chrono::NaiveDate;
184///
185/// let point = DailyValue::new(NaiveDate::from_ymd_opt(2026, 10, 22).unwrap(), 1110.0);
186/// assert_eq!(point.value, 1110.0);
187/// ```
188#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct DailyValue {
191    /// The day, in the user's local calendar.
192    pub date: NaiveDate,
193    /// The dimension's value on that day.
194    pub value: f64,
195}
196
197impl DailyValue {
198    /// Creates a daily value.
199    pub fn new(date: NaiveDate, value: f64) -> Self {
200        Self { date, value }
201    }
202}
203
204/// The median and MAD of one dimension and day class over a 28-day window (spec 3.2 §7.10).
205///
206/// # Example
207///
208/// ```
209/// use adk_eval::ledger::{DailyValue, DayClass, baseline};
210/// use chrono::{Days, NaiveDate};
211///
212/// let end = NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(); // a Friday
213/// let series: Vec<DailyValue> =
214///     (0..28).map(|back| DailyValue::new(end - Days::new(back), 100.0)).collect();
215/// let weekdays = baseline(&series, DayClass::Weekday, end).unwrap();
216/// assert_eq!((weekdays.median, weekdays.mad, weekdays.samples), (100.0, 0.0, 20));
217/// // MAD zero: the floor alone decides.
218/// assert!(weekdays.deviates(110.0, 2.5, 5.0));
219/// assert!(!weekdays.deviates(110.0, 2.5, 10.0));
220/// ```
221#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct DimensionBaseline {
224    /// The day class the baseline covers.
225    pub class: DayClass,
226    /// The last day of the window; the window is the 28 days ending here.
227    pub window_end: NaiveDate,
228    /// The median of the class's values in the window.
229    pub median: f64,
230    /// The median absolute deviation of those values.
231    pub mad: f64,
232    /// How many values the window held.
233    pub samples: usize,
234}
235
236impl DimensionBaseline {
237    /// Returns `max(k·MAD, floor)`, the largest distance from the median that is not a
238    /// deviation.
239    pub fn threshold(&self, k: f64, floor: f64) -> f64 {
240        (k * self.mad).max(floor)
241    }
242
243    /// Returns `true` when `|recent − median| > max(k·MAD, floor)`.
244    pub fn deviates(&self, recent: f64, k: f64, floor: f64) -> bool {
245        (recent - self.median).abs() > self.threshold(k, floor)
246    }
247}
248
249/// Returns the baseline of `class` over the 28 days ending on `window_end`, or `None` when
250/// the window holds no value of that class (spec 3.2 §7.10).
251pub fn baseline(
252    series: &[DailyValue],
253    class: DayClass,
254    window_end: NaiveDate,
255) -> Option<DimensionBaseline> {
256    let values = window_values(series, class, window_end, BASELINE_WINDOW_DAYS);
257    Some(DimensionBaseline {
258        class,
259        window_end,
260        median: median(&values)?,
261        mad: mad(&values)?,
262        samples: values.iter().filter(|value| value.is_finite()).count(),
263    })
264}
265
266/// How far a dimension's baseline has learned: days with a value in its window against the
267/// 14 the warm-up requires (spec 3.2 §7.10).
268///
269/// # Example
270///
271/// ```
272/// use adk_eval::ledger::WarmUp;
273///
274/// assert!(!WarmUp { observed_days: 13, required_days: 14 }.is_complete());
275/// assert!(WarmUp { observed_days: 14, required_days: 14 }.is_complete());
276/// ```
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
278#[serde(rename_all = "camelCase")]
279pub struct WarmUp {
280    /// Distinct days with a value in the baseline window, both day classes together.
281    pub observed_days: u32,
282    /// Days the warm-up requires, [`WARM_UP_DAYS`].
283    pub required_days: u32,
284}
285
286impl WarmUp {
287    /// Returns `true` once the baseline has learned from enough days to be compared against.
288    pub fn is_complete(&self) -> bool {
289        self.observed_days >= self.required_days
290    }
291}
292
293/// Returns the warm-up of a dimension whose baseline window ends on `window_end`
294/// (spec 3.2 §7.10).
295pub fn warm_up(series: &[DailyValue], window_end: NaiveDate) -> WarmUp {
296    let start = window_start(window_end, BASELINE_WINDOW_DAYS);
297    let days: BTreeSet<NaiveDate> = series
298        .iter()
299        .filter(|point| point.value.is_finite() && point.date >= start && point.date <= window_end)
300        .map(|point| point.date)
301        .collect();
302    WarmUp {
303        observed_days: u32::try_from(days.len()).unwrap_or(u32::MAX),
304        required_days: WARM_UP_DAYS,
305    }
306}
307
308/// Returns the last day of the baseline window for a test on `as_of`: the day before the
309/// 14-day comparison window starts (spec 3.2 §7.10).
310pub fn baseline_window_end(as_of: NaiveDate) -> NaiveDate {
311    let longest = RECENT_WINDOW_DAYS.iter().copied().max().unwrap_or(0);
312    as_of.checked_sub_days(Days::new(u64::from(longest))).unwrap_or(NaiveDate::MIN)
313}
314
315/// The deviation test's settings: k and the floor of each dimension (spec 3.2 §7.10).
316///
317/// The default sets k = 2.5, a floor of [`ACTIVITY_MINUTE_FLOOR`] for the two time-of-day
318/// dimensions [`daily_series`] derives, and a floor of 0 for every other dimension.
319///
320/// # Example
321///
322/// ```
323/// use adk_eval::ledger::DeviationConfig;
324///
325/// let config = DeviationConfig::default().with_floor("tool_call.count", 2.0);
326/// assert_eq!(config.floor("tool_call.count"), 2.0);
327/// assert_eq!(config.floor("activity.last_minute"), 45.0);
328/// assert_eq!(config.floor("approval.count"), 0.0);
329/// ```
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
331#[serde(rename_all = "camelCase")]
332pub struct DeviationConfig {
333    /// The MAD multiplier, [`DEVIATION_K`] by default.
334    pub k: f64,
335    /// Floors by dimension name.
336    pub floors: BTreeMap<String, f64>,
337    /// The floor of a dimension without its own.
338    pub default_floor: f64,
339}
340
341impl Default for DeviationConfig {
342    fn default() -> Self {
343        Self {
344            k: DEVIATION_K,
345            floors: BTreeMap::from([
346                (ACTIVITY_FIRST_MINUTE.to_string(), ACTIVITY_MINUTE_FLOOR),
347                (ACTIVITY_LAST_MINUTE.to_string(), ACTIVITY_MINUTE_FLOOR),
348            ]),
349            default_floor: 0.0,
350        }
351    }
352}
353
354impl DeviationConfig {
355    /// Sets the floor of one dimension.
356    pub fn with_floor(mut self, dimension: impl Into<String>, floor: f64) -> Self {
357        self.floors.insert(dimension.into(), floor);
358        self
359    }
360
361    /// Sets the floor of every dimension without its own.
362    pub fn with_default_floor(mut self, floor: f64) -> Self {
363        self.default_floor = floor;
364        self
365    }
366
367    /// Returns the floor of `dimension`.
368    pub fn floor(&self, dimension: &str) -> f64 {
369        self.floors.get(dimension).copied().unwrap_or(self.default_floor)
370    }
371}
372
373/// One comparison window of one day class (spec 3.2 §7.10).
374#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase")]
376pub struct WindowTest {
377    /// The window's length in days, ending on the day under test.
378    pub days: u32,
379    /// The median of the class's values in the window; `None` when it holds none.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub recent_median: Option<f64>,
382    /// How many values the window held.
383    pub samples: usize,
384    /// Whether the window's median is further from the baseline than the threshold.
385    pub deviates: bool,
386}
387
388/// The deviation test of one dimension and day class (spec 3.2 §7.10).
389#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
390#[serde(rename_all = "camelCase")]
391pub struct ClassDeviation {
392    /// The day class.
393    pub class: DayClass,
394    /// The class's baseline; `None` when the baseline window holds no value of the class.
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub baseline: Option<DimensionBaseline>,
397    /// `max(k·MAD, floor)` for the baseline.
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub threshold: Option<f64>,
400    /// The 7-day and the 14-day window.
401    pub windows: Vec<WindowTest>,
402    /// `true` when the warm-up is complete and every window deviates.
403    pub deviating: bool,
404}
405
406/// The deviation test of one dimension on one day (spec 3.2 §7.10).
407#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct DimensionDeviation {
410    /// The dimension's name.
411    pub dimension: String,
412    /// The floor the test used.
413    pub floor: f64,
414    /// How far the dimension's baseline has learned.
415    pub warm_up: WarmUp,
416    /// The weekday and the weekend test.
417    pub classes: Vec<ClassDeviation>,
418    /// `true` when either day class deviates.
419    pub deviating: bool,
420}
421
422/// Runs the deviation test for one dimension on `as_of` (spec 3.2 §7.10).
423///
424/// For each day class it compares the medians of the last 7 and the last 14 days, `as_of`
425/// included, with the baseline of the 28 days before the 14-day window. The class deviates
426/// when the warm-up is complete and both windows satisfy
427/// `|recent − baseline| > max(k·MAD, floor)`; a window or a baseline without a value of the
428/// class does not deviate.
429///
430/// # Example
431///
432/// ```
433/// use adk_eval::ledger::{DailyValue, DeviationConfig, check_dimension};
434/// use chrono::{Days, NaiveDate};
435///
436/// let start = NaiveDate::from_ymd_opt(2026, 8, 31).unwrap();
437/// let series: Vec<DailyValue> = (0..42)
438///     .map(|day| DailyValue::new(start + Days::new(day), if day < 28 { 1050.0 } else { 1170.0 }))
439///     .collect();
440/// let as_of = start + Days::new(41);
441/// let test = check_dimension("activity.last_minute", &series, as_of, &DeviationConfig::default());
442/// assert!(test.warm_up.is_complete());
443/// assert!(test.deviating);
444/// ```
445pub fn check_dimension(
446    dimension: &str,
447    series: &[DailyValue],
448    as_of: NaiveDate,
449    config: &DeviationConfig,
450) -> DimensionDeviation {
451    let window_end = baseline_window_end(as_of);
452    let warm_up = warm_up(series, window_end);
453    let floor = config.floor(dimension);
454    let classes: Vec<ClassDeviation> = DayClass::ALL
455        .iter()
456        .map(|&class| {
457            let baseline = baseline(series, class, window_end);
458            let windows: Vec<WindowTest> = RECENT_WINDOW_DAYS
459                .iter()
460                .map(|&days| {
461                    let values = window_values(series, class, as_of, days);
462                    let recent_median = median(&values);
463                    let deviates = match (recent_median, &baseline) {
464                        (Some(recent), Some(baseline)) => {
465                            baseline.deviates(recent, config.k, floor)
466                        }
467                        (None, _) | (_, None) => false,
468                    };
469                    WindowTest {
470                        days,
471                        recent_median,
472                        samples: values.iter().filter(|value| value.is_finite()).count(),
473                        deviates,
474                    }
475                })
476                .collect();
477            ClassDeviation {
478                class,
479                threshold: baseline.map(|baseline| baseline.threshold(config.k, floor)),
480                baseline,
481                deviating: warm_up.is_complete() && windows.iter().all(|window| window.deviates),
482                windows,
483            }
484        })
485        .collect();
486    DimensionDeviation {
487        dimension: dimension.to_string(),
488        floor,
489        warm_up,
490        deviating: classes.iter().any(|class| class.deviating),
491        classes,
492    }
493}
494
495/// The deviation test of every dimension on one day (spec 3.2 §7.10).
496#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
497#[serde(rename_all = "camelCase")]
498pub struct DeviationReport {
499    /// The day under test, the last day of both comparison windows.
500    pub as_of: NaiveDate,
501    /// One test per dimension, sorted by name.
502    pub dimensions: Vec<DimensionDeviation>,
503}
504
505impl DeviationReport {
506    /// Returns the names of the deviating dimensions, sorted.
507    pub fn deviating(&self) -> Vec<&str> {
508        self.dimensions
509            .iter()
510            .filter(|dimension| dimension.deviating)
511            .map(|dimension| dimension.dimension.as_str())
512            .collect()
513    }
514}
515
516/// Runs [`check_dimension`] for every dimension of `series` on `as_of` (spec 3.2 §7.10).
517pub fn check_series(
518    series: &BTreeMap<String, Vec<DailyValue>>,
519    as_of: NaiveDate,
520    config: &DeviationConfig,
521) -> DeviationReport {
522    DeviationReport {
523        as_of,
524        dimensions: series
525            .iter()
526            .map(|(dimension, values)| check_dimension(dimension, values, as_of, config))
527            .collect(),
528    }
529}
530
531// ── Meaningful drift and cooldown ───────────────────────────────
532
533/// Returns `true` when deviating dimensions with these run lengths, in days, are a
534/// meaningful drift: two dimensions, or one that has deviated for 10 days (spec 3.2 §7.10).
535///
536/// # Example
537///
538/// ```
539/// use adk_eval::ledger::is_meaningful;
540///
541/// assert!(!is_meaningful(&[9]));
542/// assert!(is_meaningful(&[10]));
543/// assert!(is_meaningful(&[1, 1]));
544/// assert!(!is_meaningful(&[]));
545/// ```
546pub fn is_meaningful(run_days: &[u32]) -> bool {
547    run_days.len() >= MEANINGFUL_DIMENSIONS
548        || run_days.iter().any(|&days| days >= MEANINGFUL_RUN_DAYS)
549}
550
551/// The drift a caller carries from one daily tick to the next: when each deviating
552/// dimension's run started, and when each dimension was last observed (spec 3.2 §7.10).
553///
554/// [`DriftState::advance`] is a pure transition: it returns the next state and leaves this one
555/// unchanged, so the kernel can persist the state between ticks.
556///
557/// # Example
558///
559/// ```
560/// use adk_eval::ledger::DriftState;
561/// use chrono::{Days, NaiveDate};
562///
563/// let day = NaiveDate::from_ymd_opt(2026, 10, 1).unwrap();
564/// // Two dimensions deviate: meaningful, so both are observed.
565/// let step = DriftState::default().advance(day, &["activity.last_minute", "tool_call.count"]);
566/// assert_eq!(step.observed, ["activity.last_minute", "tool_call.count"]);
567///
568/// // Six days later both are still in their cooldown.
569/// let later = step.state.advance(day + Days::new(6), &["activity.last_minute", "tool_call.count"]);
570/// assert!(later.observed.is_empty());
571///
572/// // On the seventh day the cooldown is over.
573/// let again = later.state.advance(day + Days::new(7), &["activity.last_minute", "tool_call.count"]);
574/// assert_eq!(again.observed.len(), 2);
575/// ```
576#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
577#[serde(rename_all = "camelCase")]
578pub struct DriftState {
579    /// The first day of each deviating dimension's current run of deviating days.
580    pub deviating_since: BTreeMap<String, NaiveDate>,
581    /// The day an observation last included each dimension.
582    pub last_observed: BTreeMap<String, NaiveDate>,
583}
584
585/// A deviating dimension's current run (spec 3.2 §7.10).
586#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
587#[serde(rename_all = "camelCase")]
588pub struct DriftRun {
589    /// The dimension's name.
590    pub dimension: String,
591    /// The first day of the run.
592    pub since: NaiveDate,
593    /// The run's length in calendar days, both ends included.
594    pub days: u32,
595    /// `true` when an observation included the dimension less than 7 days ago.
596    pub cooling_down: bool,
597}
598
599/// The result of one [`DriftState::advance`] (spec 3.2 §7.10).
600#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
601#[serde(rename_all = "camelCase")]
602pub struct DriftStep {
603    /// The state to carry to the next tick.
604    pub state: DriftState,
605    /// Every deviating dimension's run, sorted by name, cooling down or not.
606    pub runs: Vec<DriftRun>,
607    /// The dimensions an observation on this day includes, sorted; empty when there is no
608    /// observation.
609    pub observed: Vec<String>,
610}
611
612impl DriftState {
613    /// Returns `true` when an observation included `dimension` less than 7 days before `day`.
614    pub fn in_cooldown(&self, dimension: &str, day: NaiveDate) -> bool {
615        self.last_observed
616            .get(dimension)
617            .is_some_and(|last| (day - *last).num_days() < i64::from(COOLDOWN_DAYS))
618    }
619
620    /// Records the dimensions deviating on `day` and decides whether `day` has an
621    /// observation (spec 3.2 §7.10).
622    ///
623    /// A deviating dimension starts a run or continues its run; a dimension not in
624    /// `deviating` ends its run. The dimensions out of their cooldown are the candidates, and
625    /// when their runs are meaningful ([`is_meaningful`]) the observation includes every
626    /// candidate and starts its cooldown. Calling it twice for the same day observes nothing
627    /// the second time.
628    pub fn advance(&self, day: NaiveDate, deviating: &[&str]) -> DriftStep {
629        let mut names: Vec<&str> = deviating.to_vec();
630        names.sort_unstable();
631        names.dedup();
632
633        let mut state = DriftState {
634            deviating_since: BTreeMap::new(),
635            last_observed: self.last_observed.clone(),
636        };
637        let runs: Vec<DriftRun> = names
638            .into_iter()
639            .map(|name| {
640                let since = self
641                    .deviating_since
642                    .get(name)
643                    .copied()
644                    .filter(|since| *since <= day)
645                    .unwrap_or(day);
646                state.deviating_since.insert(name.to_string(), since);
647                DriftRun {
648                    dimension: name.to_string(),
649                    since,
650                    days: u32::try_from((day - since).num_days() + 1).unwrap_or(u32::MAX),
651                    cooling_down: self.in_cooldown(name, day),
652                }
653            })
654            .collect();
655
656        let candidates: Vec<&DriftRun> = runs.iter().filter(|run| !run.cooling_down).collect();
657        let candidate_days: Vec<u32> = candidates.iter().map(|run| run.days).collect();
658        let observed: Vec<String> = if is_meaningful(&candidate_days) {
659            candidates.iter().map(|run| run.dimension.clone()).collect()
660        } else {
661            Vec::new()
662        };
663        for dimension in &observed {
664            state.last_observed.insert(dimension.clone(), day);
665        }
666        DriftStep { state, runs, observed }
667    }
668}
669
670// ── Regression gate ─────────────────────────────────────────────
671
672/// The state of a whole ledger on its last day, as the `cargo adk eval --ledger` gate reads
673/// it (spec 3.2 §7.10, §10 E1).
674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
675#[serde(rename_all = "camelCase")]
676pub struct LedgerAssessment {
677    /// The first day with a value in any dimension.
678    pub first_day: NaiveDate,
679    /// The last day with a value in any dimension; the day under test.
680    pub last_day: NaiveDate,
681    /// The deviation test on the last day.
682    pub report: DeviationReport,
683    /// The runs of the dimensions deviating on the last day, sorted by name.
684    pub runs: Vec<DriftRun>,
685    /// `true` when those runs are meaningful, cooldown not applied.
686    pub meaningful: bool,
687}
688
689/// Replays the daily deviation test over every day of `series` and assesses its last day
690/// (spec 3.2 §7.10, §10 E1). Returns `None` when `series` holds no value.
691///
692/// Each calendar day from the first to the last runs [`check_series`] and advances a
693/// [`DriftState`], so each run length is what a daily tick would have recorded. The
694/// assessment is meaningful when the last day's runs are ([`is_meaningful`]); the cooldown
695/// is not applied, since a regression gate keeps failing while a drift lasts.
696pub fn assess(
697    series: &BTreeMap<String, Vec<DailyValue>>,
698    config: &DeviationConfig,
699) -> Option<LedgerAssessment> {
700    let dates = || series.values().flatten().map(|point| point.date);
701    let first_day = dates().min()?;
702    let last_day = dates().max()?;
703
704    let mut state = DriftState::default();
705    let mut runs = Vec::new();
706    let mut report = check_series(series, first_day, config);
707    for day in first_day.iter_days().take_while(|day| *day <= last_day) {
708        report = check_series(series, day, config);
709        let step = state.advance(day, &report.deviating());
710        state = step.state;
711        runs = step.runs;
712    }
713    let run_days: Vec<u32> = runs.iter().map(|run| run.days).collect();
714    Some(LedgerAssessment {
715        first_day,
716        last_day,
717        report,
718        meaningful: is_meaningful(&run_days),
719        runs,
720    })
721}
722
723// ── Ledger export ───────────────────────────────────────────────
724
725/// The minute of the day of a day's first ledger row, a dimension of [`daily_series`].
726pub const ACTIVITY_FIRST_MINUTE: &str = "activity.first_minute";
727
728/// The minute of the day of a day's last ledger row, a dimension of [`daily_series`].
729pub const ACTIVITY_LAST_MINUTE: &str = "activity.last_minute";
730
731/// One row of an exported activity ledger, with the columns of spec 3.2 §7.10.
732///
733/// A ledger is content-free: a row records what kind of thing happened, when, for how long
734/// and to which hashed subject — never a payload, a prompt or a secret. An export is one
735/// camelCase JSON object per line; fields this type does not know are ignored.
736///
737/// ```text
738/// {"ts":"2026-10-22T19:20:04+03:00","partition":"work","agent":"assistant","kind":"tool_call","effect":"read_only","durationMs":182,"subjectHash":"hmac-sha256:5f2c…","meta":{"attempt":1},"traceId":"4bf92f35…"}
739/// ```
740///
741/// # Example
742///
743/// ```
744/// use adk_eval::ledger::LedgerRow;
745///
746/// let row: LedgerRow = serde_json::from_str(
747///     r#"{"ts":"2026-10-22T19:20:04+03:00","partition":"work","agent":"assistant","kind":"wake"}"#,
748/// )
749/// .unwrap();
750/// assert_eq!(row.kind, "wake");
751/// assert_eq!(row.duration_ms, None);
752/// ```
753#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
754#[serde(rename_all = "camelCase")]
755pub struct LedgerRow {
756    /// When the row was written, RFC 3339 with the offset of the user's local time; its day
757    /// and time of day are read in that offset.
758    pub ts: DateTime<FixedOffset>,
759    /// The partition the activity belongs to.
760    pub partition: String,
761    /// The agent that acted.
762    pub agent: String,
763    /// What happened: `intent`, `tool_call`, `approval`, `rejection`, `observation`, `wake`,
764    /// `proposal`, or another kind the kernel defines.
765    pub kind: String,
766    /// The effect class of the action, such as `read_only`.
767    #[serde(default, skip_serializing_if = "Option::is_none")]
768    pub effect: Option<String>,
769    /// How long the action took.
770    #[serde(default, skip_serializing_if = "Option::is_none")]
771    pub duration_ms: Option<u64>,
772    /// An HMAC of the action's subject, never the subject itself.
773    #[serde(default, skip_serializing_if = "Option::is_none")]
774    pub subject_hash: Option<String>,
775    /// Small, schema-checked metadata; numbers only feed the statistics.
776    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
777    pub meta: serde_json::Map<String, serde_json::Value>,
778    /// The trace the row belongs to.
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub trace_id: Option<String>,
781}
782
783/// A line of a ledger export that is not a [`LedgerRow`] (spec 3.2 §7.10).
784#[derive(Debug, thiserror::Error)]
785#[error(
786    "ledger line {line} is not a ledger row: {source}. Each line must be one JSON object with \
787     ts (RFC 3339 with an offset), partition, agent and kind, and optionally effect, \
788     durationMs, subjectHash, meta and traceId"
789)]
790pub struct LedgerParseError {
791    /// The one-based line number.
792    pub line: usize,
793    /// Why the line did not parse.
794    #[source]
795    pub source: serde_json::Error,
796}
797
798/// Parses a ledger export, one JSON object per line; blank lines are skipped
799/// (spec 3.2 §7.10).
800///
801/// # Errors
802///
803/// Returns [`LedgerParseError`] for the first line that is not a [`LedgerRow`].
804///
805/// # Example
806///
807/// ```
808/// use adk_eval::ledger::parse_jsonl;
809///
810/// let export = r#"
811/// {"ts":"2026-10-22T09:02:00+03:00","partition":"default","agent":"assistant","kind":"intent"}
812///
813/// {"ts":"2026-10-22T09:03:10+03:00","partition":"default","agent":"assistant","kind":"tool_call","durationMs":140}
814/// "#;
815/// assert_eq!(parse_jsonl(export).unwrap().len(), 2);
816/// assert_eq!(parse_jsonl("{}").unwrap_err().line, 1);
817/// ```
818pub fn parse_jsonl(text: &str) -> Result<Vec<LedgerRow>, LedgerParseError> {
819    text.lines()
820        .enumerate()
821        .filter(|(_, line)| !line.trim().is_empty())
822        .map(|(index, line)| {
823            serde_json::from_str(line)
824                .map_err(|source| LedgerParseError { line: index + 1, source })
825        })
826        .collect()
827}
828
829/// Derives one daily series per dimension from ledger rows (spec 3.2 §7.10).
830///
831/// A row's day and time of day are read in the offset of its timestamp. Days without a row
832/// have no value in any dimension.
833///
834/// | Dimension | Daily value |
835/// |-----------|-------------|
836/// | `activity.first_minute` | Minute of the day of the first row |
837/// | `activity.last_minute` | Minute of the day of the last row |
838/// | `<kind>.count` | Rows of that kind; 0 on a day with rows of other kinds only |
839/// | `<kind>.duration_ms` | Median `durationMs` of that kind's rows that carry one |
840/// | `<kind>.meta.<key>` | Sum of that kind's numeric top-level `meta` values under `key` |
841///
842/// # Example
843///
844/// ```
845/// use adk_eval::ledger::{daily_series, parse_jsonl};
846///
847/// let rows = parse_jsonl(
848///     r#"{"ts":"2026-10-22T09:00:00+03:00","partition":"default","agent":"a","kind":"tool_call","durationMs":100}
849/// {"ts":"2026-10-22T17:30:00+03:00","partition":"default","agent":"a","kind":"tool_call","durationMs":300}"#,
850/// )
851/// .unwrap();
852/// let series = daily_series(&rows);
853/// assert_eq!(series["tool_call.count"][0].value, 2.0);
854/// assert_eq!(series["tool_call.duration_ms"][0].value, 200.0);
855/// assert_eq!(series["activity.last_minute"][0].value, 17.0 * 60.0 + 30.0);
856/// ```
857pub fn daily_series(rows: &[LedgerRow]) -> BTreeMap<String, Vec<DailyValue>> {
858    let mut days: BTreeMap<NaiveDate, Vec<&LedgerRow>> = BTreeMap::new();
859    for row in rows {
860        days.entry(row.ts.date_naive()).or_default().push(row);
861    }
862    let kinds: BTreeSet<&str> = rows.iter().map(|row| row.kind.as_str()).collect();
863
864    let mut series: BTreeMap<String, Vec<DailyValue>> = BTreeMap::new();
865    let mut push = |dimension: String, date: NaiveDate, value: f64| {
866        series.entry(dimension).or_default().push(DailyValue::new(date, value));
867    };
868    for (&date, day_rows) in &days {
869        let minutes: Vec<f64> = day_rows
870            .iter()
871            .map(|row| f64::from(row.ts.time().num_seconds_from_midnight()) / 60.0)
872            .collect();
873        let first = minutes.iter().copied().fold(f64::INFINITY, f64::min);
874        let last = minutes.iter().copied().fold(f64::NEG_INFINITY, f64::max);
875        push(ACTIVITY_FIRST_MINUTE.to_string(), date, first);
876        push(ACTIVITY_LAST_MINUTE.to_string(), date, last);
877
878        for kind in &kinds {
879            let of_kind: Vec<&LedgerRow> =
880                day_rows.iter().copied().filter(|row| row.kind == *kind).collect();
881            push(format!("{kind}.count"), date, of_kind.len() as f64);
882
883            let durations: Vec<f64> =
884                of_kind.iter().filter_map(|row| row.duration_ms).map(|ms| ms as f64).collect();
885            if let Some(duration) = median(&durations) {
886                push(format!("{kind}.duration_ms"), date, duration);
887            }
888
889            let mut sums: BTreeMap<&str, f64> = BTreeMap::new();
890            for row in &of_kind {
891                for (key, value) in &row.meta {
892                    if let Some(number) = value.as_f64() {
893                        *sums.entry(key.as_str()).or_default() += number;
894                    }
895                }
896            }
897            for (key, sum) in sums {
898                push(format!("{kind}.meta.{key}"), date, sum);
899            }
900        }
901    }
902    series
903}
904
905/// The values of `class` in the `days` days ending on `end`, `end` included.
906fn window_values(series: &[DailyValue], class: DayClass, end: NaiveDate, days: u32) -> Vec<f64> {
907    let start = window_start(end, days);
908    series
909        .iter()
910        .filter(|point| {
911            point.date >= start && point.date <= end && DayClass::of(point.date) == class
912        })
913        .map(|point| point.value)
914        .collect()
915}
916
917/// The first day of the `days`-day window ending on `end`.
918fn window_start(end: NaiveDate, days: u32) -> NaiveDate {
919    end.checked_sub_days(Days::new(u64::from(days.saturating_sub(1)))).unwrap_or(NaiveDate::MIN)
920}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925
926    fn date(year: i32, month: u32, day: u32) -> NaiveDate {
927        NaiveDate::from_ymd_opt(year, month, day).unwrap()
928    }
929
930    /// Monday 2026-08-31.
931    fn start() -> NaiveDate {
932        date(2026, 8, 31)
933    }
934
935    fn day(offset: u64) -> NaiveDate {
936        start() + Days::new(offset)
937    }
938
939    /// One value per day for `days` days from [`start`], from `value(offset)`.
940    fn series(days: u64, value: impl Fn(u64) -> f64) -> Vec<DailyValue> {
941        (0..days).map(|offset| DailyValue::new(day(offset), value(offset))).collect()
942    }
943
944    #[test]
945    fn median_and_mad_of_odd_even_and_empty_inputs() {
946        assert_eq!(median(&[]), None);
947        assert_eq!(mad(&[]), None);
948        assert_eq!(median(&[7.0]), Some(7.0));
949        assert_eq!(mad(&[7.0]), Some(0.0));
950        assert_eq!(median(&[5.0, 1.0, 3.0]), Some(3.0));
951        assert_eq!(median(&[1.0, 4.0, 2.0, 3.0]), Some(2.5));
952        assert_eq!(mad(&[1.0, 2.0, 3.0, 4.0, 100.0]), Some(1.0));
953        assert_eq!(median(&[1.0, f64::NAN, 3.0, f64::INFINITY]), Some(2.0));
954    }
955
956    #[test]
957    fn day_classes_split_saturday_and_sunday_from_the_week() {
958        let classes: Vec<DayClass> = (0..7).map(|offset| DayClass::of(day(offset))).collect();
959        assert_eq!(
960            classes,
961            [
962                DayClass::Weekday,
963                DayClass::Weekday,
964                DayClass::Weekday,
965                DayClass::Weekday,
966                DayClass::Weekday,
967                DayClass::Weekend,
968                DayClass::Weekend,
969            ]
970        );
971    }
972
973    #[test]
974    fn the_baseline_window_ends_before_the_fourteen_day_window() {
975        let as_of = day(41);
976        assert_eq!(baseline_window_end(as_of), day(27));
977        // A drift confined to the comparison windows leaves the baseline untouched.
978        let points = series(42, |offset| if offset < 28 { 10.0 } else { 99.0 });
979        let weekdays = baseline(&points, DayClass::Weekday, baseline_window_end(as_of)).unwrap();
980        assert_eq!(
981            weekdays,
982            DimensionBaseline {
983                class: DayClass::Weekday,
984                window_end: day(27),
985                median: 10.0,
986                mad: 0.0,
987                samples: 20,
988            }
989        );
990    }
991
992    #[test]
993    fn warm_up_completes_on_the_fourteenth_baseline_day() {
994        // Values on days 0..n, then a shift over the whole comparison window that would
995        // deviate once the baseline is warm.
996        let as_of = |baseline_days: u64| day(baseline_days - 1 + 14);
997        let shifted = |baseline_days: u64| {
998            series(
999                baseline_days + 14,
1000                move |offset| if offset < baseline_days { 10.0 } else { 50.0 },
1001            )
1002        };
1003        let config = DeviationConfig::default();
1004
1005        let day13 = check_dimension("x", &shifted(13), as_of(13), &config);
1006        assert_eq!(day13.warm_up, WarmUp { observed_days: 13, required_days: 14 });
1007        assert!(!day13.deviating);
1008        assert!(day13.classes.iter().all(|class| !class.deviating));
1009
1010        let day14 = check_dimension("x", &shifted(14), as_of(14), &config);
1011        assert_eq!(day14.warm_up, WarmUp { observed_days: 14, required_days: 14 });
1012        assert!(day14.deviating);
1013    }
1014
1015    #[test]
1016    fn warm_up_counts_days_not_values_and_ignores_days_outside_the_window() {
1017        let mut points = series(14, |_| 1.0);
1018        points.push(DailyValue::new(day(3), 2.0));
1019        assert_eq!(warm_up(&points, day(13)).observed_days, 14);
1020        // 28 days later only the last of those days is still in the window.
1021        assert_eq!(warm_up(&points, day(13 + 27)).observed_days, 1);
1022    }
1023
1024    #[test]
1025    fn mad_zero_leaves_the_floor_to_decide() {
1026        let constant = series(28, |_| 100.0);
1027        let weekdays = baseline(&constant, DayClass::Weekday, day(27)).unwrap();
1028        assert_eq!(weekdays.mad, 0.0);
1029        assert!(weekdays.deviates(110.0, DEVIATION_K, 0.0));
1030        assert!(weekdays.deviates(110.0, DEVIATION_K, 9.99));
1031        // The test is strict: a difference equal to the floor is not a deviation.
1032        assert!(!weekdays.deviates(110.0, DEVIATION_K, 10.0));
1033        assert!(!weekdays.deviates(100.0, DEVIATION_K, 0.0));
1034    }
1035
1036    #[test]
1037    fn floors_raise_the_threshold_over_k_times_mad() {
1038        // MAD 1: k·MAD is 2.5, so a floor of 4 decides and a floor of 2 does not.
1039        let alternating = series(28, |offset| if offset % 2 == 0 { 99.0 } else { 101.0 });
1040        let weekdays = baseline(&alternating, DayClass::Weekday, day(27)).unwrap();
1041        assert_eq!(weekdays.mad, 1.0);
1042        assert_eq!(weekdays.threshold(DEVIATION_K, 2.0), 2.5);
1043        assert_eq!(weekdays.threshold(DEVIATION_K, 4.0), 4.0);
1044        assert!(weekdays.deviates(103.0, DEVIATION_K, 2.0));
1045        assert!(!weekdays.deviates(103.0, DEVIATION_K, 4.0));
1046    }
1047
1048    #[test]
1049    fn weekday_and_weekend_keep_separate_baselines() {
1050        // Weekdays at 100, weekends at 0: pooled, the weekend days would look like a drift.
1051        let weekly = |offset: u64| match DayClass::of(day(offset)) {
1052            DayClass::Weekday => 100.0,
1053            DayClass::Weekend => 0.0,
1054        };
1055        let steady = series(42, weekly);
1056        let test = check_dimension("x", &steady, day(41), &DeviationConfig::default());
1057        assert!(!test.deviating);
1058        assert_eq!(
1059            test.classes.iter().map(|class| class.baseline.unwrap().median).collect::<Vec<_>>(),
1060            [100.0, 0.0]
1061        );
1062
1063        // Only the weekends move: the weekend class deviates and the weekday class does not.
1064        let weekend_drift = series(42, |offset| match DayClass::of(day(offset)) {
1065            DayClass::Weekday => 100.0,
1066            DayClass::Weekend if offset >= 28 => 60.0,
1067            DayClass::Weekend => 0.0,
1068        });
1069        let test = check_dimension("x", &weekend_drift, day(41), &DeviationConfig::default());
1070        assert!(test.deviating);
1071        assert_eq!(
1072            test.classes.iter().map(|class| (class.class, class.deviating)).collect::<Vec<_>>(),
1073            [(DayClass::Weekday, false), (DayClass::Weekend, true)]
1074        );
1075    }
1076
1077    #[test]
1078    fn a_single_busy_week_does_not_deviate() {
1079        // The last 7 days move by 40; the 14-day window's median moves by 20, under the floor.
1080        let busy_week = series(42, |offset| if offset >= 35 { 50.0 } else { 10.0 });
1081        let config = DeviationConfig::default().with_floor("x", 25.0);
1082        let test = check_dimension("x", &busy_week, day(41), &config);
1083        let weekday = &test.classes[0];
1084        assert_eq!(
1085            weekday.windows.iter().map(|window| window.deviates).collect::<Vec<_>>(),
1086            [true, false]
1087        );
1088        assert!(!test.deviating);
1089    }
1090
1091    #[test]
1092    fn a_class_without_values_does_not_deviate() {
1093        // Weekday-only activity: the weekend class has no baseline and no window values.
1094        let weekdays_only: Vec<DailyValue> =
1095            series(42, |offset| if offset < 28 { 1.0 } else { 9.0 })
1096                .into_iter()
1097                .filter(|point| DayClass::of(point.date) == DayClass::Weekday)
1098                .collect();
1099        let test = check_dimension("x", &weekdays_only, day(41), &DeviationConfig::default());
1100        let weekend = &test.classes[1];
1101        assert_eq!(weekend.baseline, None);
1102        assert!(weekend.windows.iter().all(|window| window.recent_median.is_none()));
1103        assert!(!weekend.deviating);
1104        assert!(test.deviating);
1105    }
1106
1107    #[test]
1108    fn meaningful_needs_two_dimensions_or_ten_days() {
1109        assert!(!is_meaningful(&[]));
1110        assert!(!is_meaningful(&[1]));
1111        assert!(!is_meaningful(&[9]));
1112        assert!(is_meaningful(&[10]));
1113        assert!(is_meaningful(&[1, 2]));
1114    }
1115
1116    #[test]
1117    fn a_single_dimension_is_observed_on_its_tenth_day() {
1118        let mut state = DriftState::default();
1119        for offset in 0..9 {
1120            let step = state.advance(day(offset), &["x"]);
1121            assert!(step.observed.is_empty(), "day {}", offset + 1);
1122            state = step.state;
1123        }
1124        let tenth = state.advance(day(9), &["x"]);
1125        assert_eq!(tenth.observed, ["x"]);
1126        assert_eq!(
1127            tenth.runs,
1128            [DriftRun { dimension: "x".into(), since: day(0), days: 10, cooling_down: false }]
1129        );
1130    }
1131
1132    #[test]
1133    fn a_day_without_the_deviation_ends_the_run() {
1134        let step = DriftState::default().advance(day(0), &["x"]);
1135        let step = step.state.advance(day(1), &[]);
1136        assert!(step.state.deviating_since.is_empty());
1137        let step = step.state.advance(day(2), &["x"]);
1138        assert_eq!(step.runs[0].since, day(2));
1139        assert_eq!(step.runs[0].days, 1);
1140    }
1141
1142    #[test]
1143    fn the_cooldown_lasts_seven_days_per_dimension() {
1144        let observed = DriftState::default().advance(day(0), &["a", "b"]);
1145        assert_eq!(observed.observed, ["a", "b"]);
1146
1147        // Day 6: both cooling down; a new dimension alone is not meaningful.
1148        let day6 = observed.state.advance(day(6), &["a", "b", "c"]);
1149        assert!(day6.observed.is_empty());
1150        assert_eq!(
1151            day6.runs.iter().map(|run| run.cooling_down).collect::<Vec<_>>(),
1152            [true, true, false]
1153        );
1154
1155        // Day 7: the cooldown is over and all three are candidates.
1156        let day7 = day6.state.advance(day(7), &["a", "b", "c"]);
1157        assert_eq!(day7.observed, ["a", "b", "c"]);
1158        assert_eq!(day7.state.last_observed.get("a"), Some(&day(7)));
1159    }
1160
1161    #[test]
1162    fn advancing_twice_on_one_day_observes_once() {
1163        let first = DriftState::default().advance(day(0), &["a", "b"]);
1164        let second = first.state.advance(day(0), &["a", "b"]);
1165        assert_eq!(first.observed.len(), 2);
1166        assert!(second.observed.is_empty());
1167        assert_eq!(first.state, second.state);
1168    }
1169
1170    #[test]
1171    fn advance_leaves_the_state_it_was_called_on_unchanged() {
1172        let state = DriftState::default().advance(day(0), &["a"]).state;
1173        let before = state.clone();
1174        let _ = state.advance(day(1), &["a", "b"]);
1175        assert_eq!(state, before);
1176    }
1177
1178    #[test]
1179    fn assess_counts_runs_across_the_whole_ledger() {
1180        let drift = series(42, |offset| if offset < 28 { 10.0 } else { 50.0 });
1181        let dims = BTreeMap::from([("x".to_string(), drift)]);
1182        let assessment = assess(&dims, &DeviationConfig::default()).unwrap();
1183        assert_eq!((assessment.first_day, assessment.last_day), (day(0), day(41)));
1184        assert_eq!(assessment.report.as_of, day(41));
1185        assert_eq!(assessment.runs.len(), 1);
1186        let run = &assessment.runs[0];
1187        assert_eq!(run.days, u32::try_from((day(41) - run.since).num_days() + 1).unwrap());
1188        assert_eq!(assessment.meaningful, run.days >= MEANINGFUL_RUN_DAYS);
1189        assert_eq!(assess(&BTreeMap::new(), &DeviationConfig::default()), None);
1190    }
1191
1192    #[test]
1193    fn rows_parse_from_camel_case_and_ignore_unknown_fields() {
1194        let rows = parse_jsonl(
1195            r#"{"ts":"2026-10-22T19:20:04+03:00","partition":"work","agent":"assistant","kind":"tool_call","effect":"read_only","durationMs":182,"subjectHash":"hmac-sha256:5f2c","meta":{"attempt":1},"traceId":"4bf9","seq":7}"#,
1196        )
1197        .unwrap();
1198        assert_eq!(
1199            rows,
1200            [LedgerRow {
1201                ts: DateTime::parse_from_rfc3339("2026-10-22T19:20:04+03:00").unwrap(),
1202                partition: "work".into(),
1203                agent: "assistant".into(),
1204                kind: "tool_call".into(),
1205                effect: Some("read_only".into()),
1206                duration_ms: Some(182),
1207                subject_hash: Some("hmac-sha256:5f2c".into()),
1208                meta: serde_json::Map::from_iter([("attempt".to_string(), 1.into())]),
1209                trace_id: Some("4bf9".into()),
1210            }]
1211        );
1212        let json = serde_json::to_value(&rows[0]).unwrap();
1213        assert_eq!(json["durationMs"], 182);
1214        assert_eq!(json["subjectHash"], "hmac-sha256:5f2c");
1215        assert_eq!(json["traceId"], "4bf9");
1216    }
1217
1218    #[test]
1219    fn a_bad_line_reports_its_line_number() {
1220        let export = "\n{\"ts\":\"2026-10-22T09:00:00Z\",\"partition\":\"p\",\"agent\":\"a\",\"kind\":\"k\"}\n{\"ts\":\"2026-10-22T09:00:00\",\"partition\":\"p\",\"agent\":\"a\",\"kind\":\"k\"}\n";
1221        let error = parse_jsonl(export).unwrap_err();
1222        assert_eq!(error.line, 3);
1223        assert!(error.to_string().contains("RFC 3339 with an offset"), "{error}");
1224    }
1225
1226    #[test]
1227    fn daily_series_reads_days_and_times_in_the_row_offset() {
1228        let rows = parse_jsonl(
1229            r#"{"ts":"2026-10-22T23:30:00+03:00","partition":"p","agent":"a","kind":"wake"}
1230{"ts":"2026-10-22T08:15:00+03:00","partition":"p","agent":"a","kind":"tool_call","durationMs":100,"meta":{"inputTokens":10,"label":"x"}}
1231{"ts":"2026-10-22T09:00:00+03:00","partition":"p","agent":"a","kind":"tool_call","durationMs":300,"meta":{"inputTokens":5}}
1232{"ts":"2026-10-23T10:00:00+03:00","partition":"p","agent":"a","kind":"wake"}"#,
1233        )
1234        .unwrap();
1235        let series = daily_series(&rows);
1236        let values = |dimension: &str| -> Vec<(NaiveDate, f64)> {
1237            series[dimension].iter().map(|point| (point.date, point.value)).collect()
1238        };
1239        let (d22, d23) = (date(2026, 10, 22), date(2026, 10, 23));
1240        assert_eq!(
1241            series.keys().map(String::as_str).collect::<Vec<_>>(),
1242            [
1243                "activity.first_minute",
1244                "activity.last_minute",
1245                "tool_call.count",
1246                "tool_call.duration_ms",
1247                "tool_call.meta.inputTokens",
1248                "wake.count",
1249            ]
1250        );
1251        assert_eq!(values("activity.first_minute"), [(d22, 8.0 * 60.0 + 15.0), (d23, 600.0)]);
1252        // 23:30 in the row's own offset, which is 20:30 UTC.
1253        assert_eq!(values("activity.last_minute"), [(d22, 23.0 * 60.0 + 30.0), (d23, 600.0)]);
1254        assert_eq!(values("tool_call.count"), [(d22, 2.0), (d23, 0.0)]);
1255        assert_eq!(values("tool_call.duration_ms"), [(d22, 200.0)]);
1256        assert_eq!(values("tool_call.meta.inputTokens"), [(d22, 15.0)]);
1257        assert_eq!(values("wake.count"), [(d22, 1.0), (d23, 1.0)]);
1258    }
1259}