1use 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
50pub const PROC_TARGET: &str = "kernel.proc";
58
59const TEST_SPAN_DAYS: u64 = 28 + 14;
62
63const PAGE: usize = 5_000;
65
66#[derive(Debug, Clone, PartialEq)]
86#[non_exhaustive]
87pub struct BaselinePolicy {
88 pub enabled: bool,
90 pub deviation: DeviationConfig,
92 pub daily_budget: RunBudget,
94 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 pub fn disabled() -> Self {
112 Self { enabled: false, ..Self::default() }
113 }
114
115 #[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 #[must_use]
124 pub fn with_deviation(mut self, deviation: DeviationConfig) -> Self {
125 self.deviation = deviation;
126 self
127 }
128
129 #[must_use]
131 pub fn with_daily_budget(mut self, budget: RunBudget) -> Self {
132 self.daily_budget = budget;
133 self
134 }
135
136 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase")]
160#[non_exhaustive]
161pub struct Detection {
162 pub partition: PartitionId,
164 pub as_of: NaiveDate,
166 pub dimensions: Vec<ObservedDimension>,
168 pub windows: Vec<u32>,
170}
171
172impl Detection {
173 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 pub fn template(&self) -> String {
185 template_question(&self.dimensions, &self.windows)
186 }
187
188 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
211pub 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#[async_trait]
245pub trait ObservationPhraser: Send + Sync {
246 fn name(&self) -> &str;
248
249 async fn phrase(&self, detection: &Detection, budget: &RunBudget) -> Result<String>;
255}
256
257pub 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 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337#[non_exhaustive]
338pub struct BaselineSnapshot {
339 pub partition: PartitionId,
341 pub as_of: NaiveDate,
343 pub dimensions: Vec<DimensionDeviation>,
345}
346
347#[derive(Debug, Clone, Default, PartialEq)]
349#[non_exhaustive]
350pub struct PassOutcome {
351 pub observations: Vec<Observation>,
353 pub partitions: Vec<PartitionId>,
355 pub days: usize,
357 pub model_calls: u64,
359}
360
361#[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 pub fn new(ledger: Ledger, policy: BaselinePolicy) -> Self {
401 Self { ledger, policy, phraser: None }
402 }
403
404 #[must_use]
406 pub fn with_phraser(mut self, phraser: Arc<dyn ObservationPhraser>) -> Self {
407 self.phraser = Some(phraser);
408 self
409 }
410
411 pub fn ledger(&self) -> &Ledger {
413 &self.ledger
414 }
415
416 pub fn policy(&self) -> &BaselinePolicy {
418 &self.policy
419 }
420
421 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 for state in updated {
525 store.put_pass_state(state).await?;
526 }
527 Ok(outcome)
528 }
529
530 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 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
559fn local_midnight(day: NaiveDate) -> DateTime<Utc> {
562 day.and_time(chrono::NaiveTime::MIN).and_utc()
563}
564
565fn is_activity(entry: &LedgerEntry) -> bool {
567 entry.agent != KERNEL_AGENT && entry.kind != LedgerKind::Observation.as_str()
568}
569
570fn 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
585fn 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
625pub(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 agenda: AgendaHandle,
635 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 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 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 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 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 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 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 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 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 #[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 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}