Skip to main content

adk_kernel/charter/
tracker.rs

1//! The KPI tracker, guardrails and job pauses (spec 3.5 §7.11, A-I14, A-I15).
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::sync::{Arc, RwLock};
5
6use adk_core::audit_log::{AuditActor, AuditTrail};
7use adk_core::principal::SubjectRef;
8use adk_core::{
9    Clock, NewRun, PolicyDecision, SystemClock, ToolPolicy, ToolPolicyRequest,
10    schedule::MissedFirePolicy,
11};
12use adk_server::background::{WorkflowExecutor, WorkflowState};
13use async_trait::async_trait;
14use awp_types::{Cadence, Charter, Direction, GuardrailAction, Kpi, Measurement};
15use chrono::{DateTime, Duration, NaiveDate, Utc};
16use serde::{Deserialize, Serialize};
17use serde_json::{Value, json};
18use tokio_util::sync::CancellationToken;
19use uuid::Uuid;
20
21use super::autonomy::{AutonomyLadder, OwnerDecision};
22use super::kpi::{GuardrailState, KpiPeriod, KpiSample, KpiState, KpiStore};
23use super::store::CharterStore;
24use super::{CharterEvent, CharterEventSink, WEBSITE_AUDIT_KIND, audit, emit, record};
25use crate::error::Result;
26use crate::sched::QueueClass;
27use crate::wake::{Trigger, Wake};
28
29/// The target of the tracker's maintenance run (spec 3.5 §7.11): a durable run that a
30/// [`KpiTrackerExecutor`] executes as one [`KpiTracker::tick`].
31pub const KPI_TRACKER_TARGET: &str = "kernel.kpi";
32
33/// A source of KPI measurements (spec 3.5 §7.11, §7.12): the edge beacon, host logs, an
34/// analytics driver, the commerce or spend ledger, the email driver. The product and the
35/// edge implement them; the tracker reads each KPI's source by its name, the KPI's
36/// `SourceRef`.
37///
38/// # Example
39///
40/// ```rust
41/// use adk_kernel::charter::KpiSource;
42/// use chrono::{DateTime, Utc};
43///
44/// struct Fixed(f64);
45///
46/// #[async_trait::async_trait]
47/// impl KpiSource for Fixed {
48///     fn name(&self) -> &str {
49///         "commerce"
50///     }
51///
52///     async fn read(&self, _: uuid::Uuid, _: &str, _: DateTime<Utc>, _: DateTime<Utc>) -> adk_kernel::Result<Option<f64>> {
53///         Ok(Some(self.0))
54///     }
55/// }
56/// ```
57#[async_trait]
58pub trait KpiSource: Send + Sync {
59    /// The source's name, as KPIs name it in their `source`.
60    fn name(&self) -> &str;
61
62    /// The value of `metric` on `site` over `[from, to)`; `None` when the source has nothing
63    /// for the window yet.
64    ///
65    /// # Errors
66    ///
67    /// Returns the error that kept the source from answering; the tracker records nothing
68    /// for the KPI and reads it again on the next tick.
69    async fn read(
70        &self,
71        site: Uuid,
72        metric: &str,
73        from: DateTime<Utc>,
74        to: DateTime<Utc>,
75    ) -> Result<Option<f64>>;
76}
77
78/// The hook a guardrail breach pauses a job through (spec 3.5 §7.11, A-I15): the harness
79/// stops the job's next action. [`JobPauses`] is an implementation that is also a
80/// `ToolPolicy`.
81#[async_trait]
82pub trait JobControl: Send + Sync {
83    /// Pauses `job` of `site` for `reason` before its next action. Pausing a paused job
84    /// keeps it paused.
85    ///
86    /// # Errors
87    ///
88    /// Returns the error that kept the pause from taking hold.
89    async fn pause(&self, site: Uuid, job: &str, reason: &str) -> Result<()>;
90
91    /// Lifts the pause of `job` by an owner's `decision`; `false` when it was not paused.
92    ///
93    /// # Errors
94    ///
95    /// Returns [`KernelError::Unauthorized`](crate::KernelError::Unauthorized) for a decision no person made.
96    async fn resume(&self, site: Uuid, job: &str, decision: &OwnerDecision) -> Result<bool>;
97
98    /// Why `job` is paused, or `None` when it is not.
99    ///
100    /// # Errors
101    ///
102    /// Returns the error that kept the answer from being read.
103    async fn paused(&self, site: Uuid, job: &str) -> Result<Option<String>>;
104}
105
106/// Paused jobs, enforced on the governed path (spec 3.5 §7.11, A-I15): as a `ToolPolicy`
107/// it denies every tool call of a paused job's agents until an owner resumes the job.
108///
109/// Add it to the job's harness policy (it composes through `StrictestPolicy` and never
110/// loosens it); the next call the job's agent makes after a pause is denied, whatever its
111/// standing rules say.
112///
113/// # Example
114///
115/// ```rust
116/// use adk_core::{PolicyDecision, ToolPolicy, ToolPolicyRequest};
117/// use adk_kernel::charter::{JobControl, JobPauses};
118///
119/// # #[tokio::main(flavor = "current_thread")]
120/// # async fn main() -> adk_kernel::Result<()> {
121/// let pauses = JobPauses::new().with_agent("nurture", "revenue");
122/// let mut call = ToolPolicyRequest::new("send_email", serde_json::json!({}));
123/// call.agent_name = "revenue".into();
124/// assert_eq!(pauses.evaluate(&call).await, PolicyDecision::Allow);
125/// pauses.pause(uuid::Uuid::nil(), "nurture", "unsubscribes above 2%").await?;
126/// assert!(matches!(pauses.evaluate(&call).await, PolicyDecision::Deny { .. }));
127/// # Ok(())
128/// # }
129/// ```
130#[derive(Debug, Default)]
131pub struct JobPauses {
132    agents: RwLock<BTreeMap<String, BTreeSet<String>>>,
133    paused: RwLock<BTreeMap<(Uuid, String), String>>,
134}
135
136impl JobPauses {
137    /// No paused jobs and no agents.
138    pub fn new() -> Self {
139        Self::default()
140    }
141
142    /// Names `agent` — an agent name or its `AgentId` — as one that acts for `job`.
143    #[must_use]
144    pub fn with_agent(self, job: impl Into<String>, agent: impl Into<String>) -> Self {
145        self.agents
146            .write()
147            .unwrap_or_else(|e| e.into_inner())
148            .entry(job.into())
149            .or_default()
150            .insert(agent.into());
151        self
152    }
153
154    /// The reason of the first paused job `agent` acts for.
155    fn blocking(&self, agent: &str, agent_id: Option<&str>) -> Option<(String, String)> {
156        let agents = self.agents.read().unwrap_or_else(|e| e.into_inner());
157        let paused = self.paused.read().unwrap_or_else(|e| e.into_inner());
158        paused.iter().find_map(|((_, job), reason)| {
159            let acts = agents.get(job).is_some_and(|names| {
160                names.contains(agent) || agent_id.is_some_and(|id| names.contains(id))
161            });
162            acts.then(|| (job.clone(), reason.clone()))
163        })
164    }
165}
166
167#[async_trait]
168impl JobControl for JobPauses {
169    async fn pause(&self, site: Uuid, job: &str, reason: &str) -> Result<()> {
170        self.paused
171            .write()
172            .unwrap_or_else(|e| e.into_inner())
173            .entry((site, job.to_string()))
174            .or_insert_with(|| reason.to_string());
175        Ok(())
176    }
177
178    async fn resume(&self, site: Uuid, job: &str, decision: &OwnerDecision) -> Result<bool> {
179        decision.check_person()?;
180        Ok(self
181            .paused
182            .write()
183            .unwrap_or_else(|e| e.into_inner())
184            .remove(&(site, job.to_string()))
185            .is_some())
186    }
187
188    async fn paused(&self, site: Uuid, job: &str) -> Result<Option<String>> {
189        Ok(self
190            .paused
191            .read()
192            .unwrap_or_else(|e| e.into_inner())
193            .get(&(site, job.to_string()))
194            .cloned())
195    }
196}
197
198#[async_trait]
199impl ToolPolicy for JobPauses {
200    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
201        let agent_id = request.acting.as_ref().map(|acting| acting.agent.id.as_str().to_string());
202        match self.blocking(&request.agent_name, agent_id.as_deref()) {
203            Some((job, reason)) => PolicyDecision::deny(format!(
204                "job {job} is paused by a guardrail breach ({reason}); an owner resumes it \
205                 (A-I15)"
206            )),
207            None => PolicyDecision::Allow,
208        }
209    }
210
211    fn policy_ref(&self) -> Option<String> {
212        Some("adk-kernel.charter:job-pauses".into())
213    }
214}
215
216/// Where a KPI stands (spec 3.5 §7.11, A-I14).
217///
218/// # Example
219///
220/// ```rust
221/// use adk_kernel::charter::KpiPhase;
222///
223/// assert_eq!(serde_json::to_value(KpiPhase::Tracking).unwrap()["phase"], "tracking");
224/// ```
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[serde(tag = "phase", rename_all = "camelCase", rename_all_fields = "camelCase")]
227#[non_exhaustive]
228pub enum KpiPhase {
229    /// No baseline yet: the KPI is measured and has no target (A-I14).
230    MeasureOnly {
231        /// When the measure-only period ends.
232        until: DateTime<Utc>,
233    },
234    /// It has a baseline; the owner may give it a target.
235    Tracking,
236}
237
238/// One KPI against its baseline and target after a tick (spec 3.5 §7.11).
239#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
240#[serde(rename_all = "camelCase")]
241#[non_exhaustive]
242pub struct KpiStatus {
243    /// The KPI.
244    pub kpi: String,
245    /// Its phase.
246    pub phase: KpiPhase,
247    /// Whether this tick read its source.
248    pub read: bool,
249    /// Its latest measurement.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub latest: Option<f64>,
252    /// Its baseline: the charter's, else the one the tracker locked.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub baseline: Option<f64>,
255    /// Its target: the charter's, and only once the charter gives it a baseline (A-I14).
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub target: Option<f64>,
258    /// The latest against the baseline, in the KPI's direction: positive is better.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub vs_baseline: Option<f64>,
261    /// Whether the latest meets the target, in the KPI's direction.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub meets_target: Option<bool>,
264}
265
266/// What one [`KpiTracker::tick`] did (spec 3.5 §7.11).
267#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
268#[serde(rename_all = "camelCase")]
269#[non_exhaustive]
270pub struct TrackerReport {
271    /// The charter version it tracked, `None` before the first commit.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub charter_version: Option<u32>,
274    /// Every KPI's status.
275    pub kpis: Vec<KpiStatus>,
276    /// The KPIs whose baseline it locked.
277    pub locked: Vec<String>,
278    /// The guardrails that began a breach.
279    pub breached: Vec<String>,
280    /// The guardrails whose breach ended.
281    pub recovered: Vec<String>,
282    /// The jobs it paused.
283    pub paused: Vec<String>,
284    /// The guardrails it could not measure: no KPI tracks their metric yet.
285    pub unmeasured: Vec<String>,
286}
287
288/// One KPI's week for the weekly review (spec 3.5 §7.11, §7.21).
289#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
290#[serde(rename_all = "camelCase")]
291#[non_exhaustive]
292pub struct KpiReview {
293    /// The KPI.
294    pub kpi: String,
295    /// Its name.
296    pub name: String,
297    /// Its phase.
298    pub phase: KpiPhase,
299    /// The week's mean.
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub week: Option<f64>,
302    /// The previous week's mean, for the trend.
303    #[serde(default, skip_serializing_if = "Option::is_none")]
304    pub previous_week: Option<f64>,
305    /// Its baseline.
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    pub baseline: Option<f64>,
308    /// Its target (A-I14).
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub target: Option<f64>,
311}
312
313/// The KPI tracker of one site (spec 3.5 §7.11): a kernel maintenance process that, on each
314/// [`tick`](Self::tick), reads every KPI of the charter in force whose cadence is due from
315/// its [`KpiSource`], records the measurement, compares it with the baseline and target,
316/// keeps the measure-only period, and checks the guardrails.
317///
318/// | Rule | What the tracker does |
319/// |---|---|
320/// | Measure-only (A-I14) | A KPI with no baseline is measured for `measure_only` (14 days) from the first tick that saw it and has no target; then the tracker locks a baseline, the mean of the period's samples, and the owner may set a target |
321/// | Targets (A-I14) | A charter target counts only beside a charter baseline |
322/// | Guardrails (A-I15) | When a guardrail's metric, the mean of the KPIs measuring it over its window, crosses its threshold, the tracker pauses each affected job through the [`JobControl`] first (`PauseJob`), then demotes it one level and raises a P2 [`CharterEvent`]; the breach acts once until the metric recovers |
323///
324/// Run it daily as a durable run with [`KpiTrackerExecutor`] and [`trigger`](Self::trigger),
325/// or call `tick` from the product's own loop.
326///
327/// # Example
328///
329/// ```rust,ignore
330/// let tracker = KpiTracker::new(site, charters, kpis)
331///     .with_source(Arc::new(beacon))
332///     .with_control(pauses.clone())
333///     .with_ladder(ladder);
334/// let report = tracker.tick().await?;
335/// ```
336#[derive(Clone)]
337pub struct KpiTracker {
338    site: Uuid,
339    charters: Arc<dyn CharterStore>,
340    kpis: Arc<dyn KpiStore>,
341    sources: BTreeMap<String, Arc<dyn KpiSource>>,
342    control: Option<Arc<dyn JobControl>>,
343    ladder: Option<AutonomyLadder>,
344    events: Option<Arc<dyn CharterEventSink>>,
345    audit: Option<AuditTrail>,
346    clock: Arc<dyn Clock>,
347    measure_only: Duration,
348}
349
350impl std::fmt::Debug for KpiTracker {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        f.debug_struct("KpiTracker")
353            .field("site", &self.site)
354            .field("sources", &self.sources.keys().collect::<Vec<_>>())
355            .field("measure_only", &self.measure_only)
356            .finish_non_exhaustive()
357    }
358}
359
360impl KpiTracker {
361    /// The default measure-only period, 14 days (A-I14).
362    pub const DEFAULT_MEASURE_ONLY: Duration = Duration::days(14);
363
364    /// A tracker of `site`'s charter in `charters`, recording in `kpis`, with no sources, no
365    /// job control, ladder, events or audit, on the system clock.
366    pub fn new(site: Uuid, charters: Arc<dyn CharterStore>, kpis: Arc<dyn KpiStore>) -> Self {
367        Self {
368            site,
369            charters,
370            kpis,
371            sources: BTreeMap::new(),
372            control: None,
373            ladder: None,
374            events: None,
375            audit: None,
376            clock: Arc::new(SystemClock),
377            measure_only: Self::DEFAULT_MEASURE_ONLY,
378        }
379    }
380
381    /// Reads KPIs whose source is `source.name()` from `source`.
382    #[must_use]
383    pub fn with_source(mut self, source: Arc<dyn KpiSource>) -> Self {
384        self.sources.insert(source.name().to_string(), source);
385        self
386    }
387
388    /// Pauses breaching jobs through `control` (A-I15).
389    #[must_use]
390    pub fn with_control(mut self, control: Arc<dyn JobControl>) -> Self {
391        self.control = Some(control);
392        self
393    }
394
395    /// Demotes breaching jobs on `ladder`.
396    #[must_use]
397    pub fn with_ladder(mut self, ladder: AutonomyLadder) -> Self {
398        self.ladder = Some(ladder);
399        self
400    }
401
402    /// Emits baselines, breaches and pauses on `sink`.
403    #[must_use]
404    pub fn with_events(mut self, sink: Arc<dyn CharterEventSink>) -> Self {
405        self.events = Some(sink);
406        self
407    }
408
409    /// Audits pauses on `trail`.
410    #[must_use]
411    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
412        self.audit = Some(trail);
413        self
414    }
415
416    /// Reads time from `clock`.
417    #[must_use]
418    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
419        self.clock = clock;
420        self
421    }
422
423    /// Sets the measure-only period.
424    #[must_use]
425    pub fn with_measure_only(mut self, period: Duration) -> Self {
426        self.measure_only = period;
427        self
428    }
429
430    /// The site.
431    pub fn site(&self) -> Uuid {
432        self.site
433    }
434
435    /// The standing trigger that starts the tracker's run on the cron expression `expr`
436    /// (six fields, UTC; `"0 0 3 * * *"` is daily at 03:00), on the maintenance queue of
437    /// app `app_name`. `KernelBuilder::kpi_tracker` registers it with the tracker's executor;
438    /// the kernel ticks the expression through a watermarked cron source of its own.
439    pub fn trigger(&self, app_name: &str, expr: &str) -> Trigger {
440        let run = NewRun::new(
441            QueueClass::MAINTENANCE,
442            app_name,
443            "kernel:kpi",
444            KPI_TRACKER_TARGET,
445            json!({ "site": self.site }),
446        );
447        Trigger::new(
448            format!("{KPI_TRACKER_TARGET}:{}", self.site),
449            Wake::Cron { expr: expr.to_string(), missed: MissedFirePolicy::FireOnce },
450            run,
451        )
452    }
453
454    /// Pauses the jobs of every guardrail whose breach the store still holds, as after a
455    /// restart, before the next tick (A-I15); returns the jobs paused.
456    ///
457    /// # Errors
458    ///
459    /// Returns a store or job-control error.
460    pub async fn restore_pauses(&self) -> Result<Vec<String>> {
461        let (Some(control), Some(current)) =
462            (&self.control, self.charters.current(self.site).await?)
463        else {
464            return Ok(Vec::new());
465        };
466        let mut paused = Vec::new();
467        for guardrail in &current.charter.guardrails {
468            let breached = self
469                .kpis
470                .guardrail(self.site, &guardrail.id)
471                .await?
472                .is_some_and(|state| state.breached_since.is_some());
473            if breached && guardrail.action == GuardrailAction::PauseJob {
474                for job in &guardrail.jobs {
475                    control
476                        .pause(
477                            self.site,
478                            job,
479                            &format!("the {} guardrail is breached", guardrail.id),
480                        )
481                        .await?;
482                    paused.push(job.clone());
483                }
484            }
485        }
486        Ok(paused)
487    }
488
489    /// One pass (spec 3.5 §7.11): reads the due KPIs, locks baselines, checks guardrails.
490    ///
491    /// # Errors
492    ///
493    /// Returns a store or job-control error; a failing source is logged and read again on
494    /// the next tick.
495    pub async fn tick(&self) -> Result<TrackerReport> {
496        let now = self.clock.now();
497        let Some(current) = self.charters.current(self.site).await? else {
498            return Ok(TrackerReport::default());
499        };
500        let charter = &current.charter;
501        let mut report =
502            TrackerReport { charter_version: Some(charter.version), ..TrackerReport::default() };
503        for kpi in &charter.kpis {
504            let status = self.track(kpi, now, &mut report).await?;
505            report.kpis.push(status);
506        }
507        self.guardrails(charter, now, &mut report).await?;
508        Ok(report)
509    }
510
511    /// Reads, records and assesses one KPI.
512    async fn track(
513        &self,
514        kpi: &Kpi,
515        now: DateTime<Utc>,
516        report: &mut TrackerReport,
517    ) -> Result<KpiStatus> {
518        let mut state = match self.kpis.state(self.site, &kpi.id).await? {
519            Some(state) => state,
520            None => KpiState::new(self.site, &kpi.id, now),
521        };
522        let every = cadence(kpi.cadence);
523        let due = state.last_read.is_none_or(|last| now - last >= every);
524        let mut read = false;
525        if due {
526            let source = kpi.source.to_string();
527            let source = source.as_str();
528            match self.sources.get(source) {
529                Some(reader) => {
530                    let from = state.last_read.unwrap_or(now - every);
531                    match reader.read(self.site, &kpi.metric.0, from, now).await {
532                        Ok(Some(value)) => {
533                            self.kpis
534                                .record(KpiSample::new(self.site, &kpi.id, now, value, source))
535                                .await?;
536                            read = true;
537                            state.last_read = Some(now);
538                        }
539                        Ok(None) => state.last_read = Some(now),
540                        Err(error) => {
541                            tracing::warn!(kpi = %kpi.id, source, error = %error, "a KPI source failed; the next tick reads it again");
542                        }
543                    }
544                }
545                None => {
546                    tracing::debug!(kpi = %kpi.id, source, "no KPI source registered under this name");
547                }
548            }
549        }
550        // A-I14: no baseline yet, so measure until the period ends, then lock one.
551        let ends = state.measuring_since + self.measure_only;
552        if kpi.baseline.is_none() && state.baseline.is_none() && now >= ends {
553            let samples = self.kpis.samples(self.site, &kpi.id, state.measuring_since, now).await?;
554            if !samples.is_empty() {
555                let mean =
556                    samples.iter().map(|sample| sample.value).sum::<f64>() / samples.len() as f64;
557                state.baseline = Some(Measurement {
558                    value: mean,
559                    window: self.measure_only.to_std().unwrap_or_default(),
560                    measured_at: now,
561                });
562                report.locked.push(kpi.id.clone());
563                tracing::info!(kpi = %kpi.id, baseline = mean, "KPI baseline locked");
564                emit(
565                    self.events.as_ref(),
566                    CharterEvent::BaselineLocked {
567                        site: self.site,
568                        kpi: kpi.id.clone(),
569                        value: mean,
570                        at: now,
571                    },
572                )
573                .await;
574            }
575        }
576        self.kpis.put_state(state.clone()).await?;
577        let latest = self
578            .kpis
579            .samples(
580                self.site,
581                &kpi.id,
582                now - every * 4 - Duration::days(1),
583                now + Duration::microseconds(1),
584            )
585            .await?
586            .last()
587            .map(|sample| sample.value);
588        let baseline =
589            kpi.baseline.as_ref().or(state.baseline.as_ref()).map(|measurement| measurement.value);
590        // A-I14: a target counts only beside the charter's own baseline.
591        let target = kpi.baseline.as_ref().and(kpi.target.as_ref()).map(|target| target.value);
592        let sign = match kpi.direction {
593            Direction::Down => -1.0,
594            _ => 1.0,
595        };
596        let phase = if baseline.is_some() {
597            KpiPhase::Tracking
598        } else {
599            KpiPhase::MeasureOnly { until: ends }
600        };
601        Ok(KpiStatus {
602            kpi: kpi.id.clone(),
603            phase,
604            read,
605            latest,
606            baseline,
607            target,
608            vs_baseline: latest.zip(baseline).map(|(latest, baseline)| sign * (latest - baseline)),
609            meets_target: latest
610                .zip(target)
611                .map(|(latest, target)| sign * (latest - target) >= 0.0),
612        })
613    }
614
615    /// Checks every guardrail; a new breach pauses its jobs first, then demotes them.
616    async fn guardrails(
617        &self,
618        charter: &Charter,
619        now: DateTime<Utc>,
620        report: &mut TrackerReport,
621    ) -> Result<()> {
622        for guardrail in &charter.guardrails {
623            let measuring: Vec<&Kpi> =
624                charter.kpis.iter().filter(|kpi| kpi.metric == guardrail.metric).collect();
625            let window = Duration::from_std(guardrail.window).unwrap_or(Duration::days(1));
626            let from = now - window.max(Duration::seconds(1));
627            let mut values = Vec::new();
628            for kpi in &measuring {
629                let samples = self
630                    .kpis
631                    .samples(self.site, &kpi.id, from, now + Duration::microseconds(1))
632                    .await?;
633                values.extend(samples.into_iter().map(|sample| sample.value));
634            }
635            if values.is_empty() {
636                report.unmeasured.push(guardrail.id.clone());
637                continue;
638            }
639            let value = values.iter().sum::<f64>() / values.len() as f64;
640            let breached = guardrail.is_breached_by(value);
641            let mut state = self
642                .kpis
643                .guardrail(self.site, &guardrail.id)
644                .await?
645                .unwrap_or_else(|| GuardrailState::new(self.site, &guardrail.id, now));
646            let began = breached && state.breached_since.is_none();
647            if !breached && state.breached_since.is_some() {
648                report.recovered.push(guardrail.id.clone());
649                state.breached_since = None;
650            }
651            if began {
652                let reason = format!(
653                    "the {} guardrail on {} is breached: {value} against its threshold {}",
654                    guardrail.id, guardrail.metric.0, guardrail.threshold
655                );
656                // A-I15: the pause takes hold before anything else the breach causes.
657                if guardrail.action == GuardrailAction::PauseJob {
658                    for job in &guardrail.jobs {
659                        if let Some(control) = &self.control {
660                            control.pause(self.site, job, &reason).await?;
661                        }
662                        report.paused.push(job.clone());
663                        record(
664                            self.audit.as_ref(),
665                            WEBSITE_AUDIT_KIND,
666                            audit::JOB_PAUSED,
667                            AuditActor::subject(SubjectRef::service("kernel:kpi")),
668                            json!({
669                                "site": self.site,
670                                "job": job,
671                                "guardrail": guardrail.id,
672                                "metric": guardrail.metric.0,
673                                "value": value,
674                                "threshold": guardrail.threshold,
675                                "charterVersion": charter.version,
676                            }),
677                        )
678                        .await;
679                        emit(
680                            self.events.as_ref(),
681                            CharterEvent::JobPaused {
682                                site: self.site,
683                                job: job.clone(),
684                                reason: reason.clone(),
685                                at: now,
686                            },
687                        )
688                        .await;
689                    }
690                }
691                state.breached_since = Some(now);
692                report.breached.push(guardrail.id.clone());
693                tracing::warn!(guardrail = %guardrail.id, value, threshold = guardrail.threshold, "guardrail breached");
694                emit(
695                    self.events.as_ref(),
696                    CharterEvent::GuardrailBreached {
697                        site: self.site,
698                        guardrail: guardrail.id.clone(),
699                        metric: guardrail.metric.0.clone(),
700                        value,
701                        threshold: guardrail.threshold,
702                        jobs: guardrail.jobs.clone(),
703                        at: now,
704                    },
705                )
706                .await;
707                if let Some(ladder) = &self.ladder {
708                    for job in &guardrail.jobs {
709                        if let Err(error) =
710                            ladder.guardrail_breach(self.site, job, &guardrail.id).await
711                        {
712                            tracing::warn!(job = %job, error = %error, "could not demote a job after its guardrail breach");
713                        }
714                    }
715                }
716            }
717            state.last_value = Some(value);
718            state.checked_at = now;
719            self.kpis.put_guardrail(state).await?;
720        }
721        Ok(())
722    }
723
724    /// Every KPI's week starting `week_start` (a Monday) against the week before, its
725    /// baseline and its target, for the weekly review (spec 3.5 §7.21).
726    ///
727    /// # Errors
728    ///
729    /// Returns a store error.
730    pub async fn review(&self, week_start: NaiveDate) -> Result<Vec<KpiReview>> {
731        let Some(current) = self.charters.current(self.site).await? else {
732            return Ok(Vec::new());
733        };
734        let mut reviews = Vec::new();
735        let previous = week_start - Duration::days(7);
736        for kpi in &current.charter.kpis {
737            let weeks = self
738                .kpis
739                .aggregates(self.site, &kpi.id, KpiPeriod::Week, previous, week_start)
740                .await?;
741            let state = self.kpis.state(self.site, &kpi.id).await?;
742            let baseline = kpi
743                .baseline
744                .as_ref()
745                .or(state.as_ref().and_then(|state| state.baseline.as_ref()))
746                .map(|measurement| measurement.value);
747            let phase = match (&baseline, &state) {
748                (Some(_), _) => KpiPhase::Tracking,
749                (None, Some(state)) => {
750                    KpiPhase::MeasureOnly { until: state.measuring_since + self.measure_only }
751                }
752                (None, None) => {
753                    KpiPhase::MeasureOnly { until: self.clock.now() + self.measure_only }
754                }
755            };
756            reviews.push(KpiReview {
757                kpi: kpi.id.clone(),
758                name: kpi.name.clone(),
759                phase,
760                week: weeks.last().and_then(super::kpi::KpiAggregate::mean),
761                previous_week: weeks
762                    .first()
763                    .filter(|_| weeks.len() > 1)
764                    .and_then(super::kpi::KpiAggregate::mean),
765                baseline,
766                target: kpi.baseline.as_ref().and(kpi.target.as_ref()).map(|target| target.value),
767            });
768        }
769        Ok(reviews)
770    }
771}
772
773/// How often a KPI of `cadence` is read.
774fn cadence(cadence: Cadence) -> Duration {
775    match cadence {
776        Cadence::Weekly => Duration::days(7),
777        Cadence::Monthly => Duration::days(30),
778        Cadence::Quarterly => Duration::days(91),
779        _ => Duration::days(1),
780    }
781}
782
783/// Runs the tracker's maintenance runs (spec 3.5 §7.11): target [`KPI_TRACKER_TARGET`],
784/// input `{"site": <uuid>}`, output the [`TrackerReport`]. `KernelBuilder::kpi_tracker`
785/// registers one over every tracker it is given, beside the tracker's
786/// [`KpiTracker::trigger`]; [`CharterKit`](super::CharterKit) calls it.
787#[derive(Debug, Clone)]
788pub struct KpiTrackerExecutor {
789    trackers: BTreeMap<Uuid, KpiTracker>,
790}
791
792impl KpiTrackerExecutor {
793    /// An executor of `trackers`, one per site.
794    pub fn new(trackers: impl IntoIterator<Item = KpiTracker>) -> Self {
795        Self { trackers: trackers.into_iter().map(|tracker| (tracker.site(), tracker)).collect() }
796    }
797}
798
799#[async_trait]
800impl WorkflowExecutor for KpiTrackerExecutor {
801    fn has_workflow(&self, workflow_id: &str) -> bool {
802        workflow_id == KPI_TRACKER_TARGET
803    }
804
805    async fn execute(
806        &self,
807        workflow_id: &str,
808        input: WorkflowState,
809        cancel_token: CancellationToken,
810    ) -> std::result::Result<Value, String> {
811        if workflow_id != KPI_TRACKER_TARGET {
812            return Err(format!("{workflow_id} is not the KPI tracker"));
813        }
814        let site = input
815            .get("site")
816            .and_then(Value::as_str)
817            .and_then(|site| site.parse::<Uuid>().ok())
818            .ok_or_else(|| {
819                "a `kernel.kpi` run names its site as `{\"site\": <uuid>}`".to_string()
820            })?;
821        let tracker = self
822            .trackers
823            .get(&site)
824            .ok_or_else(|| format!("no KPI tracker is registered for site {site}"))?;
825        tokio::select! {
826            () = cancel_token.cancelled() => Err("cancelled".to_string()),
827            report = tracker.tick() => {
828                let report = report.map_err(|error| error.to_string())?;
829                serde_json::to_value(report).map_err(|error| error.to_string())
830            }
831        }
832    }
833}