Skip to main content

adk_kernel/proc/
baselines.rs

1//! The daily baseline pass (spec 3.2 §7.10, §9.2 K-I20, §13 Q4; feature `proc-baselines`).
2//!
3//! Once a local day has ended, the kernel's maintenance tick enqueues one `Maintenance`
4//! process, the durable run `kernel.proc` ([`PROC_TARGET`]) keyed by the day, so replicas
5//! sharing a run store run it once. It calls `adk-eval`'s ledger statistics — no
6//! statistics live here — for each partition and each day since its last pass:
7//!
8//! | Step | Rule | Where |
9//! |---|---|---|
10//! | Series | one value per local day and dimension, from the partition's rows; the kernel's own rows ([`KERNEL_AGENT`]) and observations are left out | `adk_eval::ledger::daily_series` |
11//! | Baseline | median and MAD per dimension and day class over 28 days, after a 14-day warm-up | `adk_eval::ledger::check_series` |
12//! | Deviation | `\|recent − baseline\| > max(k·MAD, floor)`, k = 2.5, in both the 7- and the 14-day window | `adk_eval::ledger::check_series` |
13//! | Meaningful | two dimensions, or one for ten days | `adk_eval::ledger::DriftState::advance` |
14//! | Cooldown | seven days per dimension after an observation names it | `adk_eval::ledger::DriftState::advance` |
15//! | Wording | the model phrases what was detected, within the daily budget; a reply that is not a neutral question falls back to the kernel's template | [`ObservationPhraser`], [`is_neutral_question`], [`template_question`] |
16//!
17//! The model sees only the dimension names, their directions, run lengths and the
18//! comparison windows — never a ledger row — and is used only after the deterministic
19//! detection found something (K-I20). Each observation is stored, published as
20//! `KernelEvent::Observation` and audited as `kernel.observation`.
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::sync::{Arc, Mutex};
24
25use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
26use adk_core::{
27    Content, DurableRunStore, Enqueued, GenerateContentConfig, Llm, LlmRequest, NewRun, RunBudget,
28    SubjectRef,
29};
30use adk_eval::ledger::{
31    DeviationConfig, DeviationReport, DimensionDeviation, DriftState, DriftStep, LedgerRow,
32    RECENT_WINDOW_DAYS, check_series, daily_series,
33};
34use async_trait::async_trait;
35use chrono::{DateTime, Days, NaiveDate, Utc};
36use futures::StreamExt as _;
37use serde::{Deserialize, Serialize};
38use serde_json::{Value, json};
39
40use super::{
41    Direction, KERNEL_AGENT, Ledger, LedgerEntry, LedgerKind, LedgerQuery, Observation,
42    ObservedDimension, PassState, Phrasing, is_neutral_question, template_question,
43};
44use crate::agenda::AgendaHandle;
45use crate::bus::{EventBus, KernelEvent};
46use crate::error::Result;
47use crate::partition::PartitionId;
48use crate::sched::QueueClass;
49
50/// The workflow target of the daily pass's `Maintenance` process (spec 3.2 §7.10).
51///
52/// # Example
53///
54/// ```rust
55/// assert_eq!(adk_kernel::proc::baselines::PROC_TARGET, "kernel.proc");
56/// ```
57pub const PROC_TARGET: &str = "kernel.proc";
58
59/// Days of rows one day's test reads: the 28-day baseline window and the 14-day comparison
60/// window before it.
61const TEST_SPAN_DAYS: u64 = 28 + 14;
62
63/// Rows one read of the ledger fetches.
64const PAGE: usize = 5_000;
65
66/// How the kernel runs the daily baseline pass (spec 3.2 §7.10).
67///
68/// | Field | Default | Meaning |
69/// |---|---|---|
70/// | `enabled` | `true` | Whether the maintenance tick runs the pass |
71/// | `deviation` | k = 2.5, a 45-minute floor for the time-of-day dimensions | The deviation test's settings (`adk_eval::ledger::DeviationConfig`) |
72/// | `daily_budget` | 3 model calls, 2 000 tokens | What one day's pass may spend phrasing; past it the template words the rest |
73/// | `max_catch_up_days` | 42 | Most days a pass tests after the kernel was down |
74///
75/// # Example
76///
77/// ```rust
78/// use adk_kernel::proc::baselines::BaselinePolicy;
79///
80/// let policy = BaselinePolicy::default().with_floor("tool_call.count", 3.0);
81/// assert!(policy.enabled);
82/// assert_eq!(policy.daily_budget.max_model_calls, Some(3));
83/// assert_eq!(policy.deviation.floor("tool_call.count"), 3.0);
84/// ```
85#[derive(Debug, Clone, PartialEq)]
86#[non_exhaustive]
87pub struct BaselinePolicy {
88    /// Whether the maintenance tick runs the pass.
89    pub enabled: bool,
90    /// The deviation test's k and floors.
91    pub deviation: DeviationConfig,
92    /// What one day's pass may spend phrasing observations.
93    pub daily_budget: RunBudget,
94    /// Most days one pass tests, counting back from the day that ended.
95    pub max_catch_up_days: u32,
96}
97
98impl Default for BaselinePolicy {
99    fn default() -> Self {
100        Self {
101            enabled: true,
102            deviation: DeviationConfig::default(),
103            daily_budget: RunBudget::new().max_model_calls(3).max_total_tokens(2_000),
104            max_catch_up_days: 42,
105        }
106    }
107}
108
109impl BaselinePolicy {
110    /// A policy that runs no pass.
111    pub fn disabled() -> Self {
112        Self { enabled: false, ..Self::default() }
113    }
114
115    /// Sets the floor of one dimension.
116    #[must_use]
117    pub fn with_floor(mut self, dimension: impl Into<String>, floor: f64) -> Self {
118        self.deviation = self.deviation.with_floor(dimension, floor);
119        self
120    }
121
122    /// Sets the deviation test's settings.
123    #[must_use]
124    pub fn with_deviation(mut self, deviation: DeviationConfig) -> Self {
125        self.deviation = deviation;
126        self
127    }
128
129    /// Sets what one day's pass may spend phrasing.
130    #[must_use]
131    pub fn with_daily_budget(mut self, budget: RunBudget) -> Self {
132        self.daily_budget = budget;
133        self
134    }
135
136    /// Sets the most days one pass tests.
137    #[must_use]
138    pub fn with_max_catch_up_days(mut self, days: u32) -> Self {
139        self.max_catch_up_days = days.max(1);
140        self
141    }
142}
143
144/// What the deterministic detection found, as the phraser sees it (spec 3.2 §7.10): the
145/// dimensions, which way they moved and for how long, and the windows — no value, no row.
146///
147/// # Example
148///
149/// ```rust
150/// use adk_kernel::proc::baselines::Detection;
151/// use adk_kernel::proc::{Direction, ObservedDimension};
152/// use chrono::NaiveDate;
153///
154/// let day = NaiveDate::from_ymd_opt(2026, 10, 22).unwrap();
155/// let detection = Detection::new("default", day, vec![ObservedDimension::new("activity.last_minute", Direction::Higher, day, 10)], vec![7, 14]);
156/// assert!(detection.prompt().contains("activity.last_minute"));
157/// ```
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase")]
160#[non_exhaustive]
161pub struct Detection {
162    /// The partition.
163    pub partition: PartitionId,
164    /// The day the test ran on.
165    pub as_of: NaiveDate,
166    /// The dimensions that changed.
167    pub dimensions: Vec<ObservedDimension>,
168    /// The comparison windows, in days.
169    pub windows: Vec<u32>,
170}
171
172impl Detection {
173    /// A detection of `dimensions` in `partition` on `as_of`.
174    pub fn new(
175        partition: impl Into<PartitionId>,
176        as_of: NaiveDate,
177        dimensions: Vec<ObservedDimension>,
178        windows: Vec<u32>,
179    ) -> Self {
180        Self { partition: partition.into(), as_of, dimensions, windows }
181    }
182
183    /// The question the kernel's template words for it.
184    pub fn template(&self) -> String {
185        template_question(&self.dimensions, &self.windows)
186    }
187
188    /// The detection as the phraser's user message: the template's wording and the
189    /// dimensions as JSON.
190    pub fn prompt(&self) -> String {
191        let dimensions: Vec<Value> = self
192            .dimensions
193            .iter()
194            .map(|dimension| {
195                json!({
196                    "dimension": dimension.dimension,
197                    "direction": dimension.direction,
198                    "days": dimension.days,
199                })
200            })
201            .collect();
202        format!(
203            "Detected over the comparison windows of {:?} days: {}\nA plain wording: {}",
204            self.windows,
205            Value::Array(dimensions),
206            self.template()
207        )
208    }
209}
210
211/// The instruction a model phrases an observation under (spec 3.2 §7.10).
212pub const PHRASING_INSTRUCTION: &str = "You word one observation about a person's activity \
213pattern for them to read. The detection below was made by a deterministic statistical test; \
214do not add to it, explain it or guess its cause. Write one or two short sentences in neutral, \
215friendly language that say what changed and end with one question offering to review it, \
216such as \"Would you like to review what changed?\". Never diagnose, judge, warn or advise: \
217no words about health, stress, tiredness, problems or what the person should do. Answer \
218with the text only, on one line.";
219
220/// Words a detection as a question (spec 3.2 §7.10): a model, used only after the
221/// deterministic detection found something. The kernel keeps a reply only when it is a
222/// neutral question ([`is_neutral_question`]) and uses its template otherwise.
223///
224/// # Example
225///
226/// ```rust
227/// use adk_core::RunBudget;
228/// use adk_kernel::proc::baselines::{Detection, ObservationPhraser};
229/// use async_trait::async_trait;
230///
231/// struct Template;
232///
233/// #[async_trait]
234/// impl ObservationPhraser for Template {
235///     fn name(&self) -> &str {
236///         "template"
237///     }
238///
239///     async fn phrase(&self, detection: &Detection, _budget: &RunBudget) -> adk_kernel::Result<String> {
240///         Ok(detection.template())
241///     }
242/// }
243/// ```
244#[async_trait]
245pub trait ObservationPhraser: Send + Sync {
246    /// The model's name, recorded as the observation's [`Phrasing::Model`].
247    fn name(&self) -> &str;
248
249    /// The question for `detection`, within `budget`.
250    ///
251    /// # Errors
252    ///
253    /// Returns the model's error; the kernel then words the observation itself.
254    async fn phrase(&self, detection: &Detection, budget: &RunBudget) -> Result<String>;
255}
256
257/// An [`ObservationPhraser`] over any `adk_core::Llm` (spec 3.2 §7.10): one request with
258/// [`PHRASING_INSTRUCTION`] as its system message and the [`Detection::prompt`] as its
259/// user message, its output capped by the budget's token limit (at most 1 024) and no
260/// sampling parameters.
261///
262/// # Example
263///
264/// ```rust
265/// use std::sync::Arc;
266/// use adk_kernel::proc::baselines::{LlmPhraser, ObservationPhraser};
267/// use adk_model::{ScriptedLlm, ScriptedResponse};
268///
269/// let model = Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("…")]));
270/// assert_eq!(LlmPhraser::new(model).name(), "scripted");
271/// ```
272pub struct LlmPhraser {
273    model: Arc<dyn Llm>,
274}
275
276impl std::fmt::Debug for LlmPhraser {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("LlmPhraser").field("model", &self.model.name()).finish()
279    }
280}
281
282impl LlmPhraser {
283    /// A phraser over `model`.
284    pub fn new(model: Arc<dyn Llm>) -> Self {
285        Self { model }
286    }
287}
288
289#[async_trait]
290impl ObservationPhraser for LlmPhraser {
291    fn name(&self) -> &str {
292        self.model.name()
293    }
294
295    async fn phrase(&self, detection: &Detection, budget: &RunBudget) -> Result<String> {
296        // No sampling parameters: models with adaptive thinking reject them.
297        let max_output_tokens = budget
298            .max_total_tokens
299            .map(|tokens| i32::try_from(tokens.min(1_024)).unwrap_or(1_024))
300            .unwrap_or(1_024);
301        let request = LlmRequest::new(
302            self.model.name(),
303            vec![
304                Content::new("system").with_text(PHRASING_INSTRUCTION),
305                Content::new("user").with_text(detection.prompt()),
306            ],
307        )
308        .with_config(GenerateContentConfig {
309            max_output_tokens: Some(max_output_tokens),
310            ..GenerateContentConfig::default()
311        });
312        let mut responses = self.model.generate_content(request, false).await?;
313        let mut whole = String::new();
314        let mut last = None;
315        while let Some(response) = responses.next().await {
316            let response = response?;
317            let text: String = response
318                .content
319                .iter()
320                .flat_map(|content| content.parts.iter())
321                .filter_map(|part| part.text())
322                .collect();
323            whole.push_str(&text);
324            if !response.partial {
325                last = Some(text);
326            }
327        }
328        Ok(last.filter(|text| !text.trim().is_empty()).unwrap_or(whole).trim().to_string())
329    }
330}
331
332/// A partition's baselines on the day its last pass tested (spec 3.2 §7.10): the deviation
333/// test of every dimension, with its baseline per day class, warm-up and windows. Stored as
334/// [`PassState::baselines`] and served at `GET /api/kernel/proc/baselines`.
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337#[non_exhaustive]
338pub struct BaselineSnapshot {
339    /// The partition.
340    pub partition: PartitionId,
341    /// The day tested.
342    pub as_of: NaiveDate,
343    /// Every dimension's test.
344    pub dimensions: Vec<DimensionDeviation>,
345}
346
347/// What one pass did (spec 3.2 §7.10).
348#[derive(Debug, Clone, Default, PartialEq)]
349#[non_exhaustive]
350pub struct PassOutcome {
351    /// The observations it recorded, oldest first.
352    pub observations: Vec<Observation>,
353    /// The partitions it tested.
354    pub partitions: Vec<PartitionId>,
355    /// The days it tested, per partition.
356    pub days: usize,
357    /// The model calls it made phrasing.
358    pub model_calls: u64,
359}
360
361/// The daily baseline pass over a [`Ledger`] (spec 3.2 §7.10): what the kernel's
362/// `kernel.proc` process runs, and what a test or a tool runs directly.
363///
364/// # Example
365///
366/// ```rust
367/// use std::sync::Arc;
368/// use adk_kernel::proc::baselines::{BaselinePass, BaselinePolicy};
369/// use adk_kernel::proc::{InMemoryLedgerStore, Ledger, LedgerKey};
370/// use chrono::NaiveDate;
371///
372/// # #[tokio::main(flavor = "current_thread")]
373/// # async fn main() -> adk_kernel::Result<()> {
374/// let ledger = Ledger::new(Arc::new(InMemoryLedgerStore::new()), LedgerKey::from_bytes([1; 32]));
375/// let outcome = BaselinePass::new(ledger, BaselinePolicy::default())
376///     .run(NaiveDate::from_ymd_opt(2026, 10, 22).unwrap())
377///     .await?;
378/// assert!(outcome.observations.is_empty(), "an empty ledger has no baseline");
379/// # Ok(())
380/// # }
381/// ```
382#[derive(Clone)]
383pub struct BaselinePass {
384    ledger: Ledger,
385    policy: BaselinePolicy,
386    phraser: Option<Arc<dyn ObservationPhraser>>,
387}
388
389impl std::fmt::Debug for BaselinePass {
390    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391        f.debug_struct("BaselinePass")
392            .field("policy", &self.policy)
393            .field("phraser", &self.phraser.as_ref().map(|phraser| phraser.name().to_string()))
394            .finish_non_exhaustive()
395    }
396}
397
398impl BaselinePass {
399    /// A pass over `ledger` under `policy`, worded by the template.
400    pub fn new(ledger: Ledger, policy: BaselinePolicy) -> Self {
401        Self { ledger, policy, phraser: None }
402    }
403
404    /// Words observations with `phraser`, within the policy's daily budget.
405    #[must_use]
406    pub fn with_phraser(mut self, phraser: Arc<dyn ObservationPhraser>) -> Self {
407        self.phraser = Some(phraser);
408        self
409    }
410
411    /// The ledger the pass reads.
412    pub fn ledger(&self) -> &Ledger {
413        &self.ledger
414    }
415
416    /// The policy it runs under.
417    pub fn policy(&self) -> &BaselinePolicy {
418        &self.policy
419    }
420
421    /// Tests every day from each partition's last pass through `as_of` (at most
422    /// `max_catch_up_days`), records the observations the drift state yields, and stores
423    /// each partition's new pass state. A day already tested is not tested again, so a
424    /// repeated pass records nothing new.
425    ///
426    /// # Errors
427    ///
428    /// Returns the ledger store's error. A phrasing failure is not an error: the template
429    /// words that observation.
430    pub async fn run(&self, as_of: NaiveDate) -> Result<PassOutcome> {
431        let store = self.ledger.store();
432        let mut states: BTreeMap<PartitionId, PassState> = store
433            .pass_states()
434            .await?
435            .into_iter()
436            .map(|state| (state.partition.clone(), state))
437            .collect();
438        let floor = as_of
439            .checked_sub_days(Days::new(u64::from(self.policy.max_catch_up_days) - 1))
440            .unwrap_or(as_of);
441        let start = |state: Option<&PassState>| {
442            state.and_then(|state| state.last_day.succ_opt()).map_or(floor, |next| next.max(floor))
443        };
444        let first_day =
445            states.values().map(|state| start(Some(state))).min().unwrap_or(floor).min(floor);
446        let rows = self.rows(first_day, as_of).await?;
447        let partitions: BTreeSet<PartitionId> =
448            rows.keys().cloned().chain(states.keys().cloned()).collect();
449
450        let mut outcome = PassOutcome::default();
451        let mut detections: Vec<Detection> = Vec::new();
452        let mut updated = Vec::new();
453        for partition in partitions {
454            let previous = states.remove(&partition);
455            let from = start(previous.as_ref());
456            if from > as_of {
457                continue;
458            }
459            let series = daily_series(rows.get(&partition).map_or(&[][..], Vec::as_slice));
460            let mut drift: DriftState = previous
461                .as_ref()
462                .and_then(|state| serde_json::from_value(state.drift.clone()).ok())
463                .unwrap_or_default();
464            let mut report = check_series(&series, from, &self.policy.deviation);
465            for day in from.iter_days().take_while(|day| *day <= as_of) {
466                report = check_series(&series, day, &self.policy.deviation);
467                let step = drift.advance(day, &report.deviating());
468                if !step.observed.is_empty() {
469                    detections.push(detection(&partition, day, &step, &report));
470                }
471                drift = step.state;
472                outcome.days += 1;
473            }
474            let snapshot = BaselineSnapshot {
475                partition: partition.clone(),
476                as_of,
477                dimensions: report.dimensions,
478            };
479            let mut state = PassState::new(partition.clone(), as_of, self.ledger.clock().now());
480            state.drift = serde_json::to_value(&drift)?;
481            state.baselines = serde_json::to_value(&snapshot)?;
482            updated.push(state);
483            outcome.partitions.push(partition);
484        }
485
486        let calls = self.policy.daily_budget.max_model_calls.unwrap_or(u64::MAX);
487        for detection in detections {
488            let (question, phrasing) = match &self.phraser {
489                Some(phraser) if outcome.model_calls < calls => {
490                    outcome.model_calls += 1;
491                    match phraser.phrase(&detection, &self.policy.daily_budget).await {
492                        Ok(text) if is_neutral_question(&text) => {
493                            (text, Phrasing::Model { model: phraser.name().to_string() })
494                        }
495                        Ok(_) => {
496                            tracing::warn!(
497                                observation.partition = %detection.partition,
498                                "the model's wording is not a neutral question; using the template"
499                            );
500                            (detection.template(), Phrasing::Template)
501                        }
502                        Err(error) => {
503                            tracing::warn!(error = %error, "the model could not word an observation; using the template");
504                            (detection.template(), Phrasing::Template)
505                        }
506                    }
507                }
508                _ => (detection.template(), Phrasing::Template),
509            };
510            let observation = Observation {
511                id: Observation::id_for(&detection.partition, detection.as_of),
512                partition: detection.partition,
513                as_of: detection.as_of,
514                dimensions: detection.dimensions,
515                windows: detection.windows,
516                question,
517                phrasing,
518                created_at: self.ledger.clock().now(),
519            };
520            store.put_observation(observation.clone()).await?;
521            outcome.observations.push(observation);
522        }
523        // Stored after the observations, so a pass cut short repeats its days.
524        for state in updated {
525            store.put_pass_state(state).await?;
526        }
527        Ok(outcome)
528    }
529
530    /// The activity rows that feed the tests of `first_day` through `as_of`, by partition,
531    /// in `adk-eval`'s row form: the kernel's own work and observations left out.
532    async fn rows(
533        &self,
534        first_day: NaiveDate,
535        as_of: NaiveDate,
536    ) -> Result<BTreeMap<PartitionId, Vec<LedgerRow>>> {
537        let span_start = first_day.checked_sub_days(Days::new(TEST_SPAN_DAYS)).unwrap_or(first_day);
538        // A day either side, so every row whose local day is in the span is read whatever
539        // its offset.
540        let from = local_midnight(span_start.pred_opt().unwrap_or(span_start));
541        let to = local_midnight(as_of.succ_opt().and_then(|day| day.succ_opt()).unwrap_or(as_of));
542        let mut rows: BTreeMap<PartitionId, Vec<LedgerRow>> = BTreeMap::new();
543        let mut query = LedgerQuery::default().from(from).to(to).limit(PAGE);
544        loop {
545            let page = self.ledger.store().list(&query).await?;
546            let Some(last) = page.last().map(|entry| entry.seq) else { break };
547            for entry in page.iter().filter(|entry| is_activity(entry)) {
548                rows.entry(entry.partition.clone()).or_default().push(row(entry));
549            }
550            if page.len() < PAGE {
551                break;
552            }
553            query = query.after(last);
554        }
555        Ok(rows)
556    }
557}
558
559/// UTC midnight of `day`; the read window has a day's margin either side, so the offset
560/// of the rows does not matter here.
561fn local_midnight(day: NaiveDate) -> DateTime<Utc> {
562    day.and_time(chrono::NaiveTime::MIN).and_utc()
563}
564
565/// Whether a row is the user's activity: not the kernel's own work, not an observation.
566fn is_activity(entry: &LedgerEntry) -> bool {
567    entry.agent != KERNEL_AGENT && entry.kind != LedgerKind::Observation.as_str()
568}
569
570/// A kernel row in `adk-eval`'s form.
571fn row(entry: &LedgerEntry) -> LedgerRow {
572    LedgerRow {
573        ts: entry.ts,
574        partition: entry.partition.as_str().to_string(),
575        agent: entry.agent.clone(),
576        kind: entry.kind.clone(),
577        effect: entry.effect.clone(),
578        duration_ms: entry.duration_ms,
579        subject_hash: entry.subject_hash.clone(),
580        meta: entry.meta.clone(),
581        trace_id: entry.trace_id.clone(),
582    }
583}
584
585/// The detection of `step`'s observed dimensions on `day`, with the direction each moved
586/// in the class that deviated, read over the longest window.
587fn detection(
588    partition: &PartitionId,
589    day: NaiveDate,
590    step: &DriftStep,
591    report: &DeviationReport,
592) -> Detection {
593    let dimensions = step
594        .observed
595        .iter()
596        .map(|name| {
597            let run = step.runs.iter().find(|run| &run.dimension == name);
598            let direction = report
599                .dimensions
600                .iter()
601                .find(|test| &test.dimension == name)
602                .and_then(|test| test.classes.iter().find(|class| class.deviating))
603                .and_then(|class| {
604                    let baseline = class.baseline?;
605                    let recent =
606                        class.windows.iter().max_by_key(|window| window.days)?.recent_median?;
607                    Some(if recent >= baseline.median {
608                        Direction::Higher
609                    } else {
610                        Direction::Lower
611                    })
612                })
613                .unwrap_or(Direction::Higher);
614            ObservedDimension::new(
615                name.clone(),
616                direction,
617                run.map_or(day, |run| run.since),
618                run.map_or(1, |run| run.days),
619            )
620        })
621        .collect();
622    Detection::new(partition.clone(), day, dimensions, RECENT_WINDOW_DAYS.to_vec())
623}
624
625/// The kernel's side of the pass: the tick that enqueues it, and the `kernel.proc`
626/// workflow that runs it and publishes what it found.
627pub(crate) struct ProcRuntime {
628    pub(crate) pass: BaselinePass,
629    pub(crate) bus: EventBus,
630    pub(crate) audit: Option<AuditTrail>,
631    pub(crate) kernel_id: String,
632    pub(crate) app_name: String,
633    /// Where observations are filed as questions.
634    agenda: AgendaHandle,
635    /// The last day this replica enqueued a pass for.
636    enqueued: Mutex<Option<NaiveDate>>,
637}
638
639impl ProcRuntime {
640    pub(crate) fn new(
641        pass: BaselinePass,
642        bus: EventBus,
643        audit: Option<AuditTrail>,
644        kernel_id: String,
645        app_name: String,
646        agenda: AgendaHandle,
647    ) -> Self {
648        Self { pass, bus, audit, kernel_id, app_name, agenda, enqueued: Mutex::new(None) }
649    }
650
651    /// On the maintenance tick: enqueues the pass of the local day that ended before `now`,
652    /// once per day; `true` when it created the run. The key `kernel:proc:<day>` makes one
653    /// run per day across replicas.
654    pub(crate) async fn tick(
655        &self,
656        runs: &Arc<dyn DurableRunStore>,
657        queues: &[QueueClass],
658        now: DateTime<Utc>,
659    ) -> bool {
660        if !self.pass.policy.enabled
661            || !queues.iter().any(|queue| queue.as_str() == QueueClass::MAINTENANCE)
662        {
663            return false;
664        }
665        let Some(as_of) = self.pass.ledger.offset().date_at(now).pred_opt() else {
666            return false;
667        };
668        if self.enqueued.lock().unwrap_or_else(|e| e.into_inner()).is_some_and(|day| day >= as_of) {
669            return false;
670        }
671        let run = NewRun::new(
672            QueueClass::MAINTENANCE,
673            self.app_name.clone(),
674            KERNEL_AGENT,
675            PROC_TARGET,
676            json!({ "asOf": as_of }),
677        )
678        .with_idempotency_key(format!("kernel:proc:{as_of}"))
679        .with_service_subject();
680        match runs.enqueue(run).await {
681            Ok(enqueued) => {
682                *self.enqueued.lock().unwrap_or_else(|e| e.into_inner()) = Some(as_of);
683                matches!(enqueued, Enqueued::Created(_))
684            }
685            Err(error) => {
686                tracing::warn!(error = %error, "could not enqueue the baseline pass");
687                false
688            }
689        }
690    }
691
692    /// The `kernel.proc` workflow: runs the pass for the run's day, then publishes and
693    /// audits each observation and files it as a question for its partition's audience.
694    pub(crate) async fn execute(&self, input: Value) -> std::result::Result<Value, String> {
695        let as_of: NaiveDate = input
696            .get("asOf")
697            .cloned()
698            .and_then(|day| serde_json::from_value(day).ok())
699            .ok_or_else(|| {
700                format!(
701                    "a `{PROC_TARGET}` run's input names its day as {{\"asOf\": \"YYYY-MM-DD\"}}"
702                )
703            })?;
704        let outcome = self.pass.run(as_of).await.map_err(|error| error.to_string())?;
705        for observation in &outcome.observations {
706            self.bus.publish(KernelEvent::Observation {
707                id: observation.id.clone(),
708                partition: observation.partition.clone(),
709            });
710            if let Some(trail) = &self.audit {
711                let dimensions: Vec<&str> =
712                    observation.dimensions.iter().map(|d| d.dimension.as_str()).collect();
713                let mut actor = AuditActor::subject(SubjectRef::service(KERNEL_AGENT));
714                actor.instance = Some(self.kernel_id.clone());
715                let draft = AuditRecordDraft::new(
716                    AuditRecordKind::Other(crate::audit::KERNEL_AUDIT_KIND.to_string()),
717                    crate::audit::OBSERVATION,
718                )
719                .actor(actor)
720                .ext("id", json!(observation.id))
721                .ext("partition", json!(observation.partition))
722                .ext("dimensions", json!(dimensions))
723                .ext("windows", json!(observation.windows));
724                if let Err(error) = trail.record(draft).await {
725                    tracing::warn!(error = %error, "could not write a kernel.observation record");
726                }
727            }
728            if let Some(agenda) = self.agenda.get()
729                && let Err(error) = agenda.offer(observation).await
730            {
731                tracing::warn!(observation.id = %observation.id, error = %error, "could not put an observation to its partition's audience");
732            }
733        }
734        Ok(json!({
735            "asOf": as_of,
736            "partitions": outcome.partitions.len(),
737            "days": outcome.days,
738            "observations": outcome.observations.iter().map(|o| o.id.clone()).collect::<Vec<_>>(),
739        }))
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use std::sync::atomic::{AtomicUsize, Ordering};
746
747    use chrono::{FixedOffset, TimeZone as _};
748
749    use super::*;
750    use crate::proc::{Activity, InMemoryLedgerStore, LedgerKey, LedgerOffset, LedgerSink};
751
752    fn offset() -> FixedOffset {
753        FixedOffset::east_opt(3 * 3600).unwrap()
754    }
755
756    fn ledger() -> Ledger {
757        Ledger::new(Arc::new(InMemoryLedgerStore::new()), LedgerKey::from_bytes([5; 32]))
758            .with_offset(LedgerOffset::Fixed(offset()))
759    }
760
761    /// Monday 2026-08-31.
762    fn start() -> NaiveDate {
763        NaiveDate::from_ymd_opt(2026, 8, 31).unwrap()
764    }
765
766    fn day(offset: u64) -> NaiveDate {
767        start() + Days::new(offset)
768    }
769
770    fn local(day: NaiveDate, minute_of_day: u32) -> DateTime<Utc> {
771        let time = day.and_hms_opt(minute_of_day / 60, minute_of_day % 60, 0).unwrap();
772        offset().from_local_datetime(&time).unwrap().to_utc()
773    }
774
775    /// A day starting at 09:00 with a request, `calls` tool calls spread to the last
776    /// activity at `last` (minutes after midnight, local), and a closing request.
777    async fn workday(ledger: &Ledger, day: NaiveDate, calls: u32, last: u32) {
778        let first = 9 * 60;
779        ledger
780            .record(Activity::new(LedgerKind::Intent, "harness").at(local(day, first)))
781            .await
782            .unwrap();
783        for n in 1..=calls {
784            let at = first + (last - first) * n / (calls + 1);
785            ledger
786                .record(Activity::new(LedgerKind::ToolCall, "harness").at(local(day, at)))
787                .await
788                .unwrap();
789        }
790        ledger
791            .record(Activity::new(LedgerKind::Intent, "harness").at(local(day, last)))
792            .await
793            .unwrap();
794    }
795
796    fn weekend(day: NaiveDate) -> bool {
797        matches!(chrono::Datelike::weekday(&day), chrono::Weekday::Sat | chrono::Weekday::Sun)
798    }
799
800    /// `days` days: four weeks ending at 17:30 with 12 tool calls, then weekdays ending at
801    /// 20:30 with `late_calls`; weekends short and unchanged.
802    async fn routine(ledger: &Ledger, days: u64, late_calls: u32) {
803        for offset in 0..days {
804            let day = day(offset);
805            if weekend(day) {
806                workday(ledger, day, 2, 11 * 60 + 30).await;
807            } else if offset < 28 {
808                workday(ledger, day, 12, 17 * 60 + 30).await;
809            } else {
810                workday(ledger, day, late_calls, 20 * 60 + 30).await;
811            }
812        }
813    }
814
815    /// The days the pass observed, one pass per day as the kernel runs it.
816    async fn observed_days(pass: &BaselinePass, days: u64) -> Vec<u64> {
817        let mut observed = Vec::new();
818        for offset in 0..days {
819            let outcome = pass.run(day(offset)).await.unwrap();
820            for observation in outcome.observations {
821                assert!(is_neutral_question(&observation.question), "{}", observation.question);
822                observed.push((observation.as_of - start()).num_days() as u64);
823            }
824        }
825        observed
826    }
827
828    #[tokio::test]
829    async fn one_late_dimension_is_observed_on_its_tenth_day_and_then_cools_down() {
830        let ledger = ledger();
831        routine(&ledger, 49, 12).await;
832        let pass = BaselinePass::new(ledger, BaselinePolicy::default());
833        // Both windows deviate from Friday day 32; ten days later the drift is meaningful;
834        // seven days after that the cooldown ends.
835        assert_eq!(observed_days(&pass, 49).await, [41, 48]);
836        let observation =
837            &pass.ledger().store().observations(&Default::default()).await.unwrap()[1];
838        assert_eq!(observation.dimensions.len(), 1);
839        assert_eq!(observation.dimensions[0].dimension, "activity.last_minute");
840        assert_eq!(observation.dimensions[0].direction, Direction::Higher);
841        assert_eq!(observation.dimensions[0].since, day(32));
842        assert_eq!(observation.dimensions[0].days, 10);
843        assert_eq!(observation.phrasing, Phrasing::Template);
844        assert_eq!(
845            observation.question,
846            "Your routine has changed over the last two weeks: the day's last activity has been \
847             later than usual. Would you like to review what changed?"
848        );
849    }
850
851    #[tokio::test]
852    async fn two_dimensions_are_observed_at_once_and_repeat_after_the_cooldown() {
853        let ledger = ledger();
854        routine(&ledger, 42, 24).await;
855        let pass = BaselinePass::new(ledger, BaselinePolicy::default());
856        assert_eq!(observed_days(&pass, 42).await, [32, 39]);
857    }
858
859    #[tokio::test]
860    async fn one_catch_up_pass_finds_what_daily_passes_find() {
861        let ledger = ledger();
862        routine(&ledger, 42, 24).await;
863        let pass = BaselinePass::new(ledger, BaselinePolicy::default());
864        let outcome = pass.run(day(41)).await.unwrap();
865        assert_eq!(outcome.days, 42);
866        let days: Vec<NaiveDate> = outcome.observations.iter().map(|o| o.as_of).collect();
867        assert_eq!(days, [day(32), day(39)]);
868        let again = pass.run(day(41)).await.unwrap();
869        assert!(again.observations.is_empty() && again.days == 0, "a day is tested once");
870    }
871
872    #[tokio::test]
873    async fn a_steady_routine_and_the_kernels_own_rows_are_never_observed() {
874        let ledger = ledger();
875        for offset in 0..42u64 {
876            let day = day(offset);
877            workday(&ledger, day, 12, 17 * 60 + 30).await;
878            if offset >= 28 {
879                // The kernel's own work late at night moves nothing.
880                for minute in [23 * 60 + 50, 23 * 60 + 55] {
881                    ledger
882                        .record(
883                            Activity::new(LedgerKind::Process, KERNEL_AGENT).at(local(day, minute)),
884                        )
885                        .await
886                        .unwrap();
887                }
888            }
889        }
890        let pass = BaselinePass::new(ledger, BaselinePolicy::default());
891        assert!(observed_days(&pass, 42).await.is_empty());
892    }
893
894    /// The export `GET /kernel/proc/ledger?format=jsonl` writes is the input
895    /// `cargo adk eval --ledger` reads, and its gate finds the same drift.
896    #[tokio::test]
897    async fn the_export_is_what_cargo_adk_eval_reads() {
898        let ledger = ledger();
899        routine(&ledger, 42, 24).await;
900        let rows = ledger.store().list(&LedgerQuery::default()).await.unwrap();
901        let export: String =
902            rows.iter().map(|row| format!("{}\n", row.to_jsonl().unwrap())).collect();
903        let parsed = adk_eval::ledger::parse_jsonl(&export).unwrap();
904        assert_eq!(parsed.len(), rows.len());
905        assert_eq!(parsed[0], row(&rows[0]), "every column reads back");
906        let assessment = adk_eval::ledger::assess(
907            &adk_eval::ledger::daily_series(&parsed),
908            &DeviationConfig::default(),
909        )
910        .unwrap();
911        assert!(assessment.meaningful, "the gate fails on the late finishes");
912        assert!(assessment.report.deviating().contains(&"activity.last_minute"));
913    }
914
915    struct Scripted {
916        reply: &'static str,
917        calls: AtomicUsize,
918    }
919
920    #[async_trait]
921    impl ObservationPhraser for Scripted {
922        fn name(&self) -> &str {
923            "scripted"
924        }
925
926        async fn phrase(&self, detection: &Detection, budget: &RunBudget) -> Result<String> {
927            assert!(!detection.prompt().contains("hmac"), "the model sees no row");
928            assert_eq!(budget.max_model_calls, Some(1));
929            self.calls.fetch_add(1, Ordering::SeqCst);
930            Ok(self.reply.to_string())
931        }
932    }
933
934    #[tokio::test]
935    async fn the_model_words_within_the_budget_and_a_diagnosis_falls_back_to_the_template() {
936        for (reply, expected) in [
937            (
938                "Your evenings have been running later these past two weeks. Would you like to \
939                 review what changed?",
940                Phrasing::Model { model: "scripted".into() },
941            ),
942            ("You are burning out from working late.", Phrasing::Template),
943        ] {
944            let ledger = ledger();
945            routine(&ledger, 42, 24).await;
946            let phraser = Arc::new(Scripted { reply, calls: AtomicUsize::new(0) });
947            let pass = BaselinePass::new(
948                ledger,
949                BaselinePolicy::default().with_daily_budget(RunBudget::new().max_model_calls(1)),
950            )
951            .with_phraser(phraser.clone());
952            // One catch-up pass finds two observations; the budget words one of them.
953            let outcome = pass.run(day(41)).await.unwrap();
954            assert_eq!(outcome.observations.len(), 2);
955            assert_eq!(outcome.observations[0].phrasing, expected);
956            assert_eq!(outcome.observations[1].phrasing, Phrasing::Template);
957            assert!(outcome.observations.iter().all(|o| is_neutral_question(&o.question)));
958            assert_eq!(phraser.calls.load(Ordering::SeqCst), 1);
959        }
960    }
961}