use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
use async_trait::async_trait;
use awp_types::{AutonomyLevel, Urgency};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
mod autonomy;
mod directory;
mod kit;
mod kpi;
mod signal;
mod site;
mod store;
mod tracker;
pub(crate) use autonomy::check_apply as check_autonomy_apply;
pub use autonomy::{
AutonomyChange, AutonomyLadder, AutonomyReason, AutonomyStore, DecisionOutcome, JobAutonomy,
JobDecision, OwnerDecision, PromotionEligibility, PromotionPolicy, ladder_rank,
};
pub use directory::{CharterDirectory, chain_policy, group_role, role_group};
pub use kit::CharterKit;
pub use kpi::{
GuardrailState, KpiAggregate, KpiPeriod, KpiSample, KpiState, KpiStore, aggregate, period_start,
};
pub use signal::{
SIGNAL_SOURCE_TOOL, SignalFilter, SignalKey, SignalOutcome, SignalRateLimit, SignalRecord,
SignalSink, SignalSourceTool, SignalStore, signal_key, signal_topic,
};
pub use site::{SITE_PROCESS_LABEL, SiteProcessKind};
pub use store::{
CHARTER_ACTION, ChainRefusal, CharterStore, CharterVersion, CommitDecision, RoleApproval,
check_chain, commit_audited, is_agent_principal,
};
pub use tracker::{
JobControl, JobPauses, KPI_TRACKER_TARGET, KpiPhase, KpiReview, KpiSource, KpiStatus,
KpiTracker, KpiTrackerExecutor, TrackerReport,
};
pub use crate::stores::charter_memory::{
InMemoryAutonomyStore, InMemoryCharterStore, InMemoryKpiStore, InMemorySignalStore,
};
#[cfg(feature = "redis")]
pub use crate::stores::charter_redis::{
RedisAutonomyStore, RedisCharterStore, RedisKpiStore, RedisSignalStore,
};
#[cfg(feature = "postgres")]
pub use crate::stores::charter_sql::{
PostgresAutonomyStore, PostgresCharterStore, PostgresKpiStore, PostgresSignalStore,
};
#[cfg(feature = "sqlite")]
pub use crate::stores::charter_sql::{
SqliteAutonomyStore, SqliteCharterStore, SqliteKpiStore, SqliteSignalStore,
};
#[derive(Clone)]
#[non_exhaustive]
pub struct CharterStores {
pub charters: std::sync::Arc<dyn CharterStore>,
pub kpis: std::sync::Arc<dyn KpiStore>,
pub autonomy: std::sync::Arc<dyn AutonomyStore>,
pub signals: std::sync::Arc<dyn SignalStore>,
}
impl std::fmt::Debug for CharterStores {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CharterStores").finish_non_exhaustive()
}
}
impl CharterStores {
pub fn in_memory() -> Self {
Self {
charters: std::sync::Arc::new(InMemoryCharterStore::new()),
kpis: std::sync::Arc::new(InMemoryKpiStore::new()),
autonomy: std::sync::Arc::new(InMemoryAutonomyStore::new()),
signals: std::sync::Arc::new(InMemorySignalStore::new()),
}
}
#[cfg(feature = "sqlite")]
pub async fn sqlite(pool: sqlx::SqlitePool) -> crate::Result<Self> {
let charters = SqliteCharterStore::new(pool.clone());
charters.migrate().await?;
Ok(Self {
charters: std::sync::Arc::new(charters),
kpis: std::sync::Arc::new(SqliteKpiStore::new(pool.clone())),
autonomy: std::sync::Arc::new(SqliteAutonomyStore::new(pool.clone())),
signals: std::sync::Arc::new(SqliteSignalStore::new(pool)),
})
}
#[cfg(feature = "postgres")]
pub async fn postgres(pool: sqlx::PgPool) -> crate::Result<Self> {
let charters = PostgresCharterStore::new(pool.clone());
charters.migrate().await?;
Ok(Self {
charters: std::sync::Arc::new(charters),
kpis: std::sync::Arc::new(PostgresKpiStore::new(pool.clone())),
autonomy: std::sync::Arc::new(PostgresAutonomyStore::new(pool.clone())),
signals: std::sync::Arc::new(PostgresSignalStore::new(pool)),
})
}
#[cfg(feature = "redis")]
pub async fn redis(client: fred::prelude::Client) -> crate::Result<Self> {
let charters = RedisCharterStore::from_client(client.clone());
charters.migrate().await?;
Ok(Self {
charters: std::sync::Arc::new(charters),
kpis: std::sync::Arc::new(RedisKpiStore::from_client(client.clone())),
autonomy: std::sync::Arc::new(RedisAutonomyStore::from_client(client.clone())),
signals: std::sync::Arc::new(RedisSignalStore::from_client(client)),
})
}
}
pub(crate) const RATE_HORIZON_MICROS: i64 = 24 * 60 * 60 * 1_000_000;
pub const WEBSITE_AUDIT_KIND: &str = "website";
pub mod audit {
pub const SIGNAL: &str = "kernel.signal";
pub const CHARTER_COMMITTED: &str = "website.charter.committed";
pub const APPROVAL_CHAIN_SATISFIED: &str = "website.approval_chain.satisfied";
pub const APPROVAL_CHAIN_REFUSED: &str = "website.approval_chain.refused";
pub const JOB_PROMOTED: &str = "website.job.promoted";
pub const JOB_DEMOTED: &str = "website.job.demoted";
pub const JOB_PAUSED: &str = "website.job.paused";
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum CharterEvent {
Committed {
site: Uuid,
version: u32,
decision: String,
at: DateTime<Utc>,
},
BaselineLocked {
site: Uuid,
kpi: String,
value: f64,
at: DateTime<Utc>,
},
GuardrailBreached {
site: Uuid,
guardrail: String,
metric: String,
value: f64,
threshold: f64,
jobs: Vec<String>,
at: DateTime<Utc>,
},
JobPaused {
site: Uuid,
job: String,
reason: String,
at: DateTime<Utc>,
},
AutonomyChanged {
site: Uuid,
job: String,
from: AutonomyLevel,
to: AutonomyLevel,
reason: String,
at: DateTime<Utc>,
},
PromotionOffered {
site: Uuid,
job: String,
to: AutonomyLevel,
streak: usize,
at: DateTime<Utc>,
},
}
impl CharterEvent {
pub fn urgency(&self) -> Urgency {
match self {
Self::GuardrailBreached { .. } | Self::JobPaused { .. } => Urgency::P2,
Self::Committed { .. }
| Self::BaselineLocked { .. }
| Self::AutonomyChanged { .. }
| Self::PromotionOffered { .. } => Urgency::P3,
}
}
}
#[async_trait]
pub trait CharterEventSink: Send + Sync {
async fn emit(&self, event: &CharterEvent);
}
pub(crate) async fn record(
trail: Option<&AuditTrail>,
kind: &str,
action: &str,
actor: AuditActor,
fields: Value,
) {
let Some(trail) = trail else { return };
let mut draft =
AuditRecordDraft::new(AuditRecordKind::Other(kind.to_string()), action).actor(actor);
if let Value::Object(fields) = fields {
for (key, value) in fields {
draft = draft.ext(key, value);
}
}
if let Err(error) = trail.record(draft).await {
tracing::warn!(audit.action = action, error = %error, "could not write a charter audit record");
}
}
pub(crate) async fn emit(sink: Option<&std::sync::Arc<dyn CharterEventSink>>, event: CharterEvent) {
if let Some(sink) = sink {
sink.emit(&event).await;
}
}