Skip to main content

adk_kernel/charter/
mod.rs

1//! The site's charter, its KPIs, its jobs' earned autonomy and the signals the public
2//! partition sends the back office (spec 3.5 §7.6, §7.10, §7.11, §7.21; feature `charter`).
3//!
4//! The charter format is AWP 2.0's (`awp_types::Charter`); this module keeps it, measures
5//! against it and enforces what it says:
6//!
7//! | Item | What it does | Spec |
8//! |---|---|---|
9//! | [`CharterStore`], [`CharterVersion`], [`CommitDecision`], [`RoleApproval`], [`check_chain`], [`commit_audited`] | Every charter version with the decision that committed it; a commit refuses a draft that fails `Charter::validate()` and a decision whose approval chain distinct people did not satisfy | §7.6, §7.11, A-I23 |
10//! | [`CharterDirectory`], [`chain_policy`], [`role_group`], [`group_role`] | The charter in force as the approval service's directory: a chain becomes an `ApprovalPolicy` with one `role:{role}` slot per role, and only the people the charter names fill them | §7.6, A-I23 |
11//! | [`KpiStore`], [`KpiSample`], [`KpiAggregate`], [`KpiPeriod`], [`KpiState`], [`GuardrailState`] | Measurements per KPI with daily and weekly aggregates, and the tracker's state | §7.11 |
12//! | [`KpiSource`], [`KpiTracker`], [`KpiTrackerExecutor`], [`JobControl`], [`JobPauses`] | The KPI tracker: reads each KPI's source on its cadence, keeps the measure-only period, checks guardrails and pauses a breaching job before its next action | §7.11, A-I14, A-I15 |
13//! | [`AutonomyStore`], [`AutonomyLadder`], [`JobAutonomy`], [`AutonomyChange`], [`JobDecision`], [`OwnerDecision`], [`PromotionPolicy`] | Each job's autonomy level and history: promotion only by an owner's decision, demotion one level on a breach, two rejections in a row or an incident | §7.11, A-I13 |
14//! | [`SignalStore`], [`SignalSink`], [`SignalRecord`], [`SignalSourceTool`] | Typed signals filed in the back office's agenda as [`AgendaOrigin::Signal`](crate::AgendaOrigin::Signal) items, counted by kind and topic, rate-limited per source, waking [`Wake::Signal`](crate::Wake::Signal) sleepers; never a crossing | §7.10, A-I3 |
15//! | [`SiteProcessKind`] | The site's process kinds, `site.probe` to `site.digest` | §7.11, §7.19 |
16//! | [`CharterKit`] | Installs a site's jobs, KPI tracker and signals on a kernel: each kind bound to the product's target, the tracker as the `kernel.kpi` process, the unbound kinds in the kernel's inventory | §7.10, §7.11, §7.20 |
17//! | [`CharterEvent`], [`CharterEventSink`] | Commits, baselines, breaches, pauses and autonomy changes, each with its urgency | §7.21 |
18//!
19//! Every store has in-memory, SQLite, PostgreSQL and Redis backends that pass one
20//! conformance suite each (`conformance::charter`, feature `conformance`):
21//!
22//! | Store | In-memory | SQLite (`sqlite`) | PostgreSQL (`postgres`) | Redis (`redis`) |
23//! |---|---|---|---|---|
24//! | [`CharterStore`] | [`InMemoryCharterStore`] | `SqliteCharterStore` | `PostgresCharterStore` | `RedisCharterStore` |
25//! | [`KpiStore`] | [`InMemoryKpiStore`] | `SqliteKpiStore` | `PostgresKpiStore` | `RedisKpiStore` |
26//! | [`AutonomyStore`] | [`InMemoryAutonomyStore`] | `SqliteAutonomyStore` | `PostgresAutonomyStore` | `RedisAutonomyStore` |
27//! | [`SignalStore`] | [`InMemorySignalStore`] | `SqliteSignalStore` | `PostgresSignalStore` | `RedisSignalStore` |
28//!
29//! # Example
30//!
31//! ```rust
32//! use adk_kernel::charter::{SiteProcessKind, SITE_PROCESS_LABEL};
33//!
34//! assert_eq!(SiteProcessKind::Probe.as_str(), "site.probe");
35//! assert_eq!(SITE_PROCESS_LABEL, "site.process");
36//! ```
37
38use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
39use async_trait::async_trait;
40use awp_types::{AutonomyLevel, Urgency};
41use chrono::{DateTime, Utc};
42use serde::{Deserialize, Serialize};
43use serde_json::Value;
44use uuid::Uuid;
45
46mod autonomy;
47mod directory;
48mod kit;
49mod kpi;
50mod signal;
51mod site;
52mod store;
53mod tracker;
54
55pub(crate) use autonomy::check_apply as check_autonomy_apply;
56pub use autonomy::{
57    AutonomyChange, AutonomyLadder, AutonomyReason, AutonomyStore, DecisionOutcome, JobAutonomy,
58    JobDecision, OwnerDecision, PromotionEligibility, PromotionPolicy, ladder_rank,
59};
60pub use directory::{CharterDirectory, chain_policy, group_role, role_group};
61pub use kit::CharterKit;
62pub use kpi::{
63    GuardrailState, KpiAggregate, KpiPeriod, KpiSample, KpiState, KpiStore, aggregate, period_start,
64};
65pub use signal::{
66    SIGNAL_SOURCE_TOOL, SignalFilter, SignalKey, SignalOutcome, SignalRateLimit, SignalRecord,
67    SignalSink, SignalSourceTool, SignalStore, signal_key, signal_topic,
68};
69pub use site::{SITE_PROCESS_LABEL, SiteProcessKind};
70pub use store::{
71    CHARTER_ACTION, ChainRefusal, CharterStore, CharterVersion, CommitDecision, RoleApproval,
72    check_chain, commit_audited, is_agent_principal,
73};
74pub use tracker::{
75    JobControl, JobPauses, KPI_TRACKER_TARGET, KpiPhase, KpiReview, KpiSource, KpiStatus,
76    KpiTracker, KpiTrackerExecutor, TrackerReport,
77};
78
79pub use crate::stores::charter_memory::{
80    InMemoryAutonomyStore, InMemoryCharterStore, InMemoryKpiStore, InMemorySignalStore,
81};
82#[cfg(feature = "redis")]
83pub use crate::stores::charter_redis::{
84    RedisAutonomyStore, RedisCharterStore, RedisKpiStore, RedisSignalStore,
85};
86#[cfg(feature = "postgres")]
87pub use crate::stores::charter_sql::{
88    PostgresAutonomyStore, PostgresCharterStore, PostgresKpiStore, PostgresSignalStore,
89};
90#[cfg(feature = "sqlite")]
91pub use crate::stores::charter_sql::{
92    SqliteAutonomyStore, SqliteCharterStore, SqliteKpiStore, SqliteSignalStore,
93};
94/// The four charter stores of one backend (spec 3.5 §7.6, §7.10, §7.11): the `charter`
95/// field of [`KernelStores`](crate::stores::KernelStores), so a site's charter, KPIs,
96/// autonomy and signals sit beside the kernel's other stores.
97///
98/// # Example
99///
100/// ```rust
101/// use adk_kernel::charter::CharterStores;
102///
103/// let stores = CharterStores::in_memory();
104/// let _ = (&stores.charters, &stores.kpis, &stores.autonomy, &stores.signals);
105/// ```
106#[derive(Clone)]
107#[non_exhaustive]
108pub struct CharterStores {
109    /// Charter versions with the decisions that committed them.
110    pub charters: std::sync::Arc<dyn CharterStore>,
111    /// KPI readings, aggregates and the tracker's state.
112    pub kpis: std::sync::Arc<dyn KpiStore>,
113    /// Each job's autonomy level and history.
114    pub autonomy: std::sync::Arc<dyn AutonomyStore>,
115    /// Signals filed in the back office.
116    pub signals: std::sync::Arc<dyn SignalStore>,
117}
118
119impl std::fmt::Debug for CharterStores {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("CharterStores").finish_non_exhaustive()
122    }
123}
124
125impl CharterStores {
126    /// The four stores in memory.
127    pub fn in_memory() -> Self {
128        Self {
129            charters: std::sync::Arc::new(InMemoryCharterStore::new()),
130            kpis: std::sync::Arc::new(InMemoryKpiStore::new()),
131            autonomy: std::sync::Arc::new(InMemoryAutonomyStore::new()),
132            signals: std::sync::Arc::new(InMemorySignalStore::new()),
133        }
134    }
135
136    /// The four stores on `pool`, migrated.
137    ///
138    /// # Errors
139    ///
140    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the migration fails.
141    #[cfg(feature = "sqlite")]
142    pub async fn sqlite(pool: sqlx::SqlitePool) -> crate::Result<Self> {
143        let charters = SqliteCharterStore::new(pool.clone());
144        charters.migrate().await?;
145        Ok(Self {
146            charters: std::sync::Arc::new(charters),
147            kpis: std::sync::Arc::new(SqliteKpiStore::new(pool.clone())),
148            autonomy: std::sync::Arc::new(SqliteAutonomyStore::new(pool.clone())),
149            signals: std::sync::Arc::new(SqliteSignalStore::new(pool)),
150        })
151    }
152
153    /// The four stores on `pool`, migrated.
154    ///
155    /// # Errors
156    ///
157    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the migration fails.
158    #[cfg(feature = "postgres")]
159    pub async fn postgres(pool: sqlx::PgPool) -> crate::Result<Self> {
160        let charters = PostgresCharterStore::new(pool.clone());
161        charters.migrate().await?;
162        Ok(Self {
163            charters: std::sync::Arc::new(charters),
164            kpis: std::sync::Arc::new(PostgresKpiStore::new(pool.clone())),
165            autonomy: std::sync::Arc::new(PostgresAutonomyStore::new(pool.clone())),
166            signals: std::sync::Arc::new(PostgresSignalStore::new(pool)),
167        })
168    }
169
170    /// The four stores on `client`, an initialised Redis client, migrated.
171    ///
172    /// # Errors
173    ///
174    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the migration fails.
175    #[cfg(feature = "redis")]
176    pub async fn redis(client: fred::prelude::Client) -> crate::Result<Self> {
177        let charters = RedisCharterStore::from_client(client.clone());
178        charters.migrate().await?;
179        Ok(Self {
180            charters: std::sync::Arc::new(charters),
181            kpis: std::sync::Arc::new(RedisKpiStore::from_client(client.clone())),
182            autonomy: std::sync::Arc::new(RedisAutonomyStore::from_client(client.clone())),
183            signals: std::sync::Arc::new(RedisSignalStore::from_client(client)),
184        })
185    }
186}
187
188/// How far back a store keeps signal rate windows: a day, in microseconds.
189pub(crate) const RATE_HORIZON_MICROS: i64 = 24 * 60 * 60 * 1_000_000;
190
191/// The kind of the charter's `website.*` audit records, as
192/// `AuditRecordKind::Other(WEBSITE_AUDIT_KIND.into())` (spec 3.5 §9.3); `kernel.signal` is
193/// a kernel record of kind [`KERNEL_AUDIT_KIND`](crate::audit::KERNEL_AUDIT_KIND).
194pub const WEBSITE_AUDIT_KIND: &str = "website";
195
196/// Audit actions of the charter module (spec 3.5 §9.3).
197///
198/// | Action | Fields |
199/// |---|---|
200/// | [`SIGNAL`](audit::SIGNAL) | `partition`, `kind`, `topic`, `item`, `count`, `source`, `outcome` — no field text |
201/// | [`CHARTER_COMMITTED`](audit::CHARTER_COMMITTED) | `site`, `charterVersion`, `decision`, `approvers`, `signedNote` |
202/// | [`APPROVAL_CHAIN_SATISFIED`](audit::APPROVAL_CHAIN_SATISFIED), [`APPROVAL_CHAIN_REFUSED`](audit::APPROVAL_CHAIN_REFUSED) | `site`, `action`, `decision`, `approvers`, `reason` |
203/// | [`JOB_PROMOTED`](audit::JOB_PROMOTED), [`JOB_DEMOTED`](audit::JOB_DEMOTED) | `site`, `job`, `from`, `to`, `reason`, `decision`, `charterVersion` |
204/// | [`JOB_PAUSED`](audit::JOB_PAUSED) | `site`, `job`, `guardrail`, `metric`, `value`, `threshold`, `charterVersion` |
205///
206/// # Example
207///
208/// ```rust
209/// assert_eq!(adk_kernel::charter::audit::SIGNAL, "kernel.signal");
210/// ```
211pub mod audit {
212    /// A signal was filed, counted or refused by the rate limit (spec 3.5 §7.10).
213    pub const SIGNAL: &str = "kernel.signal";
214    /// A charter version took effect (spec 3.5 §7.6).
215    pub const CHARTER_COMMITTED: &str = "website.charter.committed";
216    /// An approval chain was satisfied by distinct people (A-I23).
217    pub const APPROVAL_CHAIN_SATISFIED: &str = "website.approval_chain.satisfied";
218    /// An approval chain was not satisfied, so the action was refused (A-I23).
219    pub const APPROVAL_CHAIN_REFUSED: &str = "website.approval_chain.refused";
220    /// An owner raised a job's autonomy (A-I13).
221    pub const JOB_PROMOTED: &str = "website.job.promoted";
222    /// A job's autonomy was lowered (spec 3.5 §7.11).
223    pub const JOB_DEMOTED: &str = "website.job.demoted";
224    /// A guardrail breach paused a job (A-I15).
225    pub const JOB_PAUSED: &str = "website.job.paused";
226}
227
228/// Something the charter machinery did that the owner hears about (spec 3.5 §7.11, §7.21):
229/// the weekly review, alarms and the site view read these.
230///
231/// # Example
232///
233/// ```rust
234/// use adk_kernel::charter::CharterEvent;
235/// use awp_types::Urgency;
236///
237/// let event = CharterEvent::JobPaused {
238///     site: uuid::Uuid::nil(),
239///     job: "nurture".into(),
240///     reason: "unsubscribes above 2%".into(),
241///     at: chrono::Utc::now(),
242/// };
243/// assert_eq!(event.urgency(), Urgency::P2);
244/// assert_eq!(serde_json::to_value(&event).unwrap()["event"], "jobPaused");
245/// ```
246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
247#[serde(tag = "event", rename_all = "camelCase", rename_all_fields = "camelCase")]
248#[non_exhaustive]
249pub enum CharterEvent {
250    /// A charter version took effect.
251    Committed {
252        /// The site.
253        site: Uuid,
254        /// The version.
255        version: u32,
256        /// The committing decision.
257        decision: String,
258        /// When.
259        at: DateTime<Utc>,
260    },
261    /// A KPI's measure-only period ended and its baseline was locked (A-I14): the owner may
262    /// now set a target.
263    BaselineLocked {
264        /// The site.
265        site: Uuid,
266        /// The KPI.
267        kpi: String,
268        /// The baseline's value.
269        value: f64,
270        /// When.
271        at: DateTime<Utc>,
272    },
273    /// A guardrail's metric crossed its threshold (A-I15).
274    GuardrailBreached {
275        /// The site.
276        site: Uuid,
277        /// The guardrail.
278        guardrail: String,
279        /// The metric it watches.
280        metric: String,
281        /// The metric's value over the guardrail's window.
282        value: f64,
283        /// The threshold it crossed.
284        threshold: f64,
285        /// The jobs it affects.
286        jobs: Vec<String>,
287        /// When.
288        at: DateTime<Utc>,
289    },
290    /// A job was paused before its next action (A-I15).
291    JobPaused {
292        /// The site.
293        site: Uuid,
294        /// The job.
295        job: String,
296        /// Why.
297        reason: String,
298        /// When.
299        at: DateTime<Utc>,
300    },
301    /// A job's autonomy level changed (A-I13).
302    AutonomyChanged {
303        /// The site.
304        site: Uuid,
305        /// The job.
306        job: String,
307        /// The level it left.
308        from: AutonomyLevel,
309        /// The level it entered.
310        to: AutonomyLevel,
311        /// Why, in words the weekly review shows.
312        reason: String,
313        /// When.
314        at: DateTime<Utc>,
315    },
316    /// A job's record earned it a promotion the weekly review offers (spec 3.5 §7.11).
317    PromotionOffered {
318        /// The site.
319        site: Uuid,
320        /// The job.
321        job: String,
322        /// The level it would enter.
323        to: AutonomyLevel,
324        /// The unchanged approvals in a row behind the offer.
325        streak: usize,
326        /// When.
327        at: DateTime<Utc>,
328    },
329}
330
331impl CharterEvent {
332    /// How soon the owner hears of it (spec 3.5 §7.21): a guardrail breach and the pause it
333    /// causes are P2; everything else waits for the weekly review, P3.
334    pub fn urgency(&self) -> Urgency {
335        match self {
336            Self::GuardrailBreached { .. } | Self::JobPaused { .. } => Urgency::P2,
337            Self::Committed { .. }
338            | Self::BaselineLocked { .. }
339            | Self::AutonomyChanged { .. }
340            | Self::PromotionOffered { .. } => Urgency::P3,
341        }
342    }
343}
344
345/// Where [`CharterEvent`]s go: the product's alarms and weekly review (spec 3.5 §7.21).
346///
347/// # Example
348///
349/// ```rust
350/// use std::sync::Mutex;
351/// use adk_kernel::charter::{CharterEvent, CharterEventSink};
352///
353/// #[derive(Default)]
354/// struct Collect(Mutex<Vec<CharterEvent>>);
355///
356/// #[async_trait::async_trait]
357/// impl CharterEventSink for Collect {
358///     async fn emit(&self, event: &CharterEvent) {
359///         self.0.lock().unwrap().push(event.clone());
360///     }
361/// }
362/// ```
363#[async_trait]
364pub trait CharterEventSink: Send + Sync {
365    /// Receives `event`; a sink that fails logs and drops it, so it never blocks a pause.
366    async fn emit(&self, event: &CharterEvent);
367}
368
369/// Writes one audit record of `kind` when `trail` is set, logging a failure: an audit write
370/// never undoes the act it records.
371pub(crate) async fn record(
372    trail: Option<&AuditTrail>,
373    kind: &str,
374    action: &str,
375    actor: AuditActor,
376    fields: Value,
377) {
378    let Some(trail) = trail else { return };
379    let mut draft =
380        AuditRecordDraft::new(AuditRecordKind::Other(kind.to_string()), action).actor(actor);
381    if let Value::Object(fields) = fields {
382        for (key, value) in fields {
383            draft = draft.ext(key, value);
384        }
385    }
386    if let Err(error) = trail.record(draft).await {
387        tracing::warn!(audit.action = action, error = %error, "could not write a charter audit record");
388    }
389}
390
391/// Emits `event` on `sink` when one is set.
392pub(crate) async fn emit(sink: Option<&std::sync::Arc<dyn CharterEventSink>>, event: CharterEvent) {
393    if let Some(sink) = sink {
394        sink.emit(&event).await;
395    }
396}