use std::fmt;
use std::path::Path;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, SystemClock};
use async_trait::async_trait;
use chrono::{DateTime, FixedOffset, NaiveDate, Offset as _, TimeZone as _, Utc};
use hmac::Mac as _;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::LedgerStore;
use crate::error::{KernelError, Result};
use crate::partition::PartitionId;
pub use crate::error::LEDGER_INVALID_CODE;
pub const KERNEL_AGENT: &str = "kernel";
pub const MAX_META_ENTRIES: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[non_exhaustive]
pub enum LedgerKind {
Intent,
ToolCall,
Approval,
Rejection,
Denial,
Held,
Decided,
RuleHit,
Observation,
Wake,
Proposal,
Process,
Spend,
Turn,
LoopGuard,
Governance,
Audit,
Other(String),
}
impl LedgerKind {
pub fn as_str(&self) -> &str {
match self {
Self::Intent => "intent",
Self::ToolCall => "tool_call",
Self::Approval => "approval",
Self::Rejection => "rejection",
Self::Denial => "denial",
Self::Held => "held",
Self::Decided => "decided",
Self::RuleHit => "rule_hit",
Self::Observation => "observation",
Self::Wake => "wake",
Self::Proposal => "proposal",
Self::Process => "process",
Self::Spend => "spend",
Self::Turn => "turn",
Self::LoopGuard => "loop_guard",
Self::Governance => "governance",
Self::Audit => "audit",
Self::Other(name) => name,
}
}
}
impl From<String> for LedgerKind {
fn from(value: String) -> Self {
match value.as_str() {
"intent" => Self::Intent,
"tool_call" => Self::ToolCall,
"approval" => Self::Approval,
"rejection" => Self::Rejection,
"denial" => Self::Denial,
"held" => Self::Held,
"decided" => Self::Decided,
"rule_hit" => Self::RuleHit,
"observation" => Self::Observation,
"wake" => Self::Wake,
"proposal" => Self::Proposal,
"process" => Self::Process,
"spend" => Self::Spend,
"turn" => Self::Turn,
"loop_guard" => Self::LoopGuard,
"governance" => Self::Governance,
"audit" => Self::Audit,
_ => Self::Other(value),
}
}
}
impl From<LedgerKind> for String {
fn from(value: LedgerKind) -> Self {
match value {
LedgerKind::Other(name) => name,
known => known.as_str().to_string(),
}
}
}
impl fmt::Display for LedgerKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Activity {
pub kind: LedgerKind,
pub agent: String,
pub partition: PartitionId,
pub effect: Option<String>,
pub duration: Option<Duration>,
pub subject: Option<String>,
pub meta: Map<String, Value>,
pub trace_id: Option<String>,
pub at: Option<DateTime<Utc>>,
}
impl Activity {
pub fn new(kind: LedgerKind, agent: impl Into<String>) -> Self {
Self {
kind,
agent: agent.into(),
partition: PartitionId::default(),
effect: None,
duration: None,
subject: None,
meta: Map::new(),
trace_id: None,
at: None,
}
}
#[must_use]
pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
self.partition = partition.into();
self
}
#[must_use]
pub fn with_effect(mut self, effect: impl Into<String>) -> Self {
self.effect = Some(effect.into());
self
}
#[must_use]
pub fn with_duration(mut self, duration: Duration) -> Self {
self.duration = Some(duration);
self
}
#[must_use]
pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
self.subject = Some(subject.into());
self
}
#[must_use]
pub fn with_count(mut self, key: impl Into<String>, value: u64) -> Self {
self.meta.insert(key.into(), Value::from(value));
self
}
#[must_use]
pub fn with_number(mut self, key: impl Into<String>, value: f64) -> Self {
if let Some(number) = serde_json::Number::from_f64(value) {
self.meta.insert(key.into(), Value::Number(number));
}
self
}
#[must_use]
pub fn with_flag(mut self, key: impl Into<String>, value: bool) -> Self {
self.meta.insert(key.into(), Value::Bool(value));
self
}
#[must_use]
pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
self.trace_id = Some(trace_id.into());
self
}
#[must_use]
pub fn at(mut self, at: DateTime<Utc>) -> Self {
self.at = Some(at);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LedgerEntry {
#[serde(default)]
pub seq: u64,
pub ts: DateTime<FixedOffset>,
pub partition: PartitionId,
pub agent: String,
pub kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effect: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject_hash: Option<String>,
#[serde(default, skip_serializing_if = "Map::is_empty")]
pub meta: Map<String, Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trace_id: Option<String>,
}
impl LedgerEntry {
pub fn utc(&self) -> DateTime<Utc> {
self.ts.with_timezone(&Utc)
}
pub fn local_date(&self) -> NaiveDate {
self.ts.date_naive()
}
pub fn to_jsonl(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
}
#[derive(Clone)]
pub struct LedgerKey([u8; 32]);
impl fmt::Debug for LedgerKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("LedgerKey(..)")
}
}
impl LedgerKey {
pub const FILE: &'static str = "ledger.key";
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
pub fn generate() -> Result<Self> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|error| KernelError::Config {
reason: format!("the ledger key needs the operating system's random source: {error}"),
})?;
Ok(Self(bytes))
}
pub fn load_or_create(path: &Path) -> Result<Self> {
match std::fs::read_to_string(path) {
Ok(text) if text.trim().is_empty() => {
let key = Self::generate()?;
let mut file = std::fs::OpenOptions::new().write(true).truncate(true).open(path)?;
use std::io::Write as _;
writeln!(file, "{}", hex::encode(key.0))?;
file.sync_all()?;
return Ok(key);
}
Ok(text) => return Self::parse(path, &text),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let key = Self::generate()?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
match options.open(path) {
Ok(mut file) => {
use std::io::Write as _;
writeln!(file, "{}", hex::encode(key.0))?;
file.sync_all()?;
Ok(key)
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
Self::parse(path, &std::fs::read_to_string(path)?)
}
Err(error) => Err(error.into()),
}
}
fn parse(path: &Path, text: &str) -> Result<Self> {
let bytes =
hex::decode(text.trim()).ok().and_then(|bytes| <[u8; 32]>::try_from(bytes).ok());
bytes.map(Self).ok_or_else(|| KernelError::Config {
reason: format!(
"{} does not hold a ledger key (64 hex digits); move it aside to start a new \
key, which makes the existing subject hashes unrelatable to new ones",
path.display()
),
})
}
pub fn hash(&self, subject: &str) -> String {
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&self.0)
.unwrap_or_else(|_| unreachable!("HMAC-SHA256 takes a key of any length"));
mac.update(subject.as_bytes());
format!("hmac-sha256:{}", hex::encode(mac.finalize().into_bytes()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum LedgerOffset {
#[default]
Local,
Fixed(FixedOffset),
}
impl LedgerOffset {
pub fn offset_at(&self, at: DateTime<Utc>) -> FixedOffset {
match self {
Self::Local => chrono::Local.offset_from_utc_datetime(&at.naive_utc()).fix(),
Self::Fixed(offset) => *offset,
}
}
pub fn date_at(&self, at: DateTime<Utc>) -> NaiveDate {
at.with_timezone(&self.offset_at(at)).date_naive()
}
}
#[async_trait]
pub trait LedgerSink: Send + Sync {
async fn record(&self, activity: Activity) -> Result<()>;
}
#[derive(Clone, Default)]
pub struct LateLedgerSink {
sink: Arc<OnceLock<Arc<dyn LedgerSink>>>,
}
impl fmt::Debug for LateLedgerSink {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LateLedgerSink").field("bound", &self.is_bound()).finish()
}
}
impl LateLedgerSink {
pub fn new() -> Self {
Self::default()
}
pub fn bind(&self, sink: Arc<dyn LedgerSink>) -> bool {
self.sink.set(sink).is_ok()
}
pub fn is_bound(&self) -> bool {
self.sink.get().is_some()
}
}
#[async_trait]
impl LedgerSink for LateLedgerSink {
async fn record(&self, activity: Activity) -> Result<()> {
match self.sink.get() {
Some(sink) => sink.record(activity).await,
None => Ok(()),
}
}
}
#[derive(Clone)]
pub struct Ledger {
store: Arc<dyn LedgerStore>,
key: Arc<LedgerKey>,
clock: Arc<dyn Clock>,
offset: LedgerOffset,
}
impl fmt::Debug for Ledger {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ledger").field("offset", &self.offset).finish_non_exhaustive()
}
}
impl Ledger {
pub fn new(store: Arc<dyn LedgerStore>, key: LedgerKey) -> Self {
Self {
store,
key: Arc::new(key),
clock: Arc::new(SystemClock),
offset: LedgerOffset::Local,
}
}
#[must_use]
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
#[must_use]
pub fn with_offset(mut self, offset: LedgerOffset) -> Self {
self.offset = offset;
self
}
pub fn store(&self) -> &Arc<dyn LedgerStore> {
&self.store
}
pub fn offset(&self) -> LedgerOffset {
self.offset
}
pub fn clock(&self) -> &Arc<dyn Clock> {
&self.clock
}
pub fn hash(&self, subject: &str) -> String {
self.key.hash(subject)
}
pub fn entry(&self, activity: Activity) -> Result<LedgerEntry> {
let Activity { kind, agent, partition, effect, duration, subject, meta, trace_id, at } =
activity;
let kind = String::from(kind);
if !is_kind(&kind) {
return Err(invalid("kind", "a kind is 1 to 32 lowercase letters, digits and `_`"));
}
check_label("agent", &agent, MAX_LABEL)?;
check_label("partition", partition.as_str(), MAX_LABEL)?;
if let Some(effect) = &effect {
check_label("effect", effect, MAX_EFFECT)?;
}
if let Some(trace_id) = &trace_id
&& !is_trace(trace_id)
{
return Err(invalid("trace id", "a trace id is 1 to 64 ASCII letters, digits and `-`"));
}
check_meta(&meta)?;
let at = at.unwrap_or_else(|| self.clock.now());
let at = DateTime::from_timestamp_millis(at.timestamp_millis()).unwrap_or(at);
Ok(LedgerEntry {
seq: 0,
ts: at.with_timezone(&self.offset.offset_at(at)),
partition,
agent,
kind,
effect,
duration_ms: duration
.map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)),
subject_hash: subject.map(|subject| self.key.hash(&subject)),
meta,
trace_id,
})
}
}
#[async_trait]
impl LedgerSink for Ledger {
async fn record(&self, activity: Activity) -> Result<()> {
let entry = self.entry(activity)?;
self.store.append(entry).await?;
Ok(())
}
}
const MAX_LABEL: usize = 128;
const MAX_EFFECT: usize = 64;
fn invalid(field: &str, rule: &str) -> KernelError {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::InvalidInput,
LEDGER_INVALID_CODE,
format!(
"the ledger refuses this {field}: {rule}. A ledger row holds labels, counts, \
durations and hashes only, never content (spec 3.2 K-I19); pass what it is about \
as the activity's subject, which is stored as a hash"
),
))
}
pub(crate) fn is_kind(value: &str) -> bool {
let mut chars = value.chars();
value.len() <= 32
&& chars.next().is_some_and(|first| first.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
pub(crate) fn is_label(value: &str, max: usize) -> bool {
!value.is_empty()
&& value.chars().count() <= max
&& value.chars().all(|c| c.is_alphanumeric() || "._:/@+-".contains(c))
}
pub fn label(value: &str, max: usize) -> String {
let cleaned: String = value
.chars()
.take(max)
.map(|c| if c.is_alphanumeric() || "._:/@+-".contains(c) { c } else { '_' })
.collect();
if cleaned.is_empty() { "_".to_string() } else { cleaned }
}
fn is_trace(value: &str) -> bool {
(1..=64).contains(&value.len()) && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
}
fn check_label(field: &str, value: &str, max: usize) -> Result<()> {
if is_label(value, max) {
return Ok(());
}
Err(invalid(
field,
&format!("a label is 1 to {max} letters, digits and `._:/@+-`, with no space"),
))
}
fn check_meta(meta: &Map<String, Value>) -> Result<()> {
if meta.len() > MAX_META_ENTRIES {
return Err(invalid("meta", &format!("meta holds at most {MAX_META_ENTRIES} entries")));
}
for (key, value) in meta {
if !is_kind(key) {
return Err(invalid(
"meta key",
"a meta key is 1 to 32 lowercase letters, digits and `_`",
));
}
if !matches!(value, Value::Number(_) | Value::Bool(_)) {
return Err(invalid("meta value", "a meta value is a number or a boolean"));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::KernelError;
fn ledger() -> Ledger {
Ledger::new(
Arc::new(super::super::InMemoryLedgerStore::new()),
LedgerKey::from_bytes([3; 32]),
)
.with_offset(LedgerOffset::Fixed(FixedOffset::east_opt(3 * 3600).unwrap()))
}
fn code(error: KernelError) -> String {
adk_core::AdkError::from(error).code.to_string()
}
#[test]
fn an_entry_hashes_its_subject_and_stamps_the_local_offset() {
let at = DateTime::parse_from_rfc3339("2026-10-22T16:20:04.123456Z").unwrap().to_utc();
let entry = ledger()
.entry(
Activity::new(LedgerKind::ToolCall, "urn:adk:agent:adk-rust/harness")
.with_subject("bash\u{1f}{\"command\":\"cat .env\"}")
.with_duration(Duration::from_millis(1500))
.with_count("attempt", 2)
.with_flag("retried", true)
.with_trace_id("4bf92f3577b34da6a3ce929d0e0e4736")
.at(at),
)
.unwrap();
assert_eq!(entry.ts.to_rfc3339(), "2026-10-22T19:20:04.123+03:00");
assert_eq!(entry.local_date(), NaiveDate::from_ymd_opt(2026, 10, 22).unwrap());
assert_eq!(entry.duration_ms, Some(1500));
let hash = entry.subject_hash.clone().unwrap();
assert_eq!(hash.len(), "hmac-sha256:".len() + 64);
let line = entry.to_jsonl().unwrap();
assert!(!line.contains("cat .env") && !line.contains("bash"), "{line}");
}
#[test]
fn content_in_a_label_or_meta_is_refused_without_quoting_it() {
let secret = "sk-live AKIA very secret";
let refused = [
Activity::new(LedgerKind::ToolCall, secret),
Activity::new(LedgerKind::ToolCall, "harness").with_effect(secret),
Activity::new(LedgerKind::ToolCall, "harness").with_partition(secret),
Activity::new(LedgerKind::Other(secret.into()), "harness"),
Activity::new(LedgerKind::ToolCall, "harness").with_trace_id(secret),
{
let mut activity = Activity::new(LedgerKind::ToolCall, "harness");
activity.meta.insert("path".into(), Value::String(secret.into()));
activity
},
{
let mut activity = Activity::new(LedgerKind::ToolCall, "harness");
activity.meta.insert("Bad Key".into(), Value::from(1));
activity
},
(0..=MAX_META_ENTRIES).fold(Activity::new(LedgerKind::ToolCall, "harness"), |a, n| {
a.with_count(format!("n{n}"), 1)
}),
];
for activity in refused {
let error = ledger().entry(activity).unwrap_err();
assert!(!error.to_string().contains("secret"), "{error}");
assert_eq!(code(error), LEDGER_INVALID_CODE);
}
}
#[test]
fn labels_take_identifiers_of_any_script() {
assert!(is_label("urn:adk:agent:adk-rust/harness", MAX_LABEL));
assert!(is_label("ü-日本", MAX_LABEL));
assert!(!is_label("two words", MAX_LABEL));
assert!(!is_label("", MAX_LABEL));
assert_eq!(label("a b\nc", 8), "a_b_c");
assert_eq!(label("", 8), "_");
}
#[test]
fn a_key_round_trips_through_its_file() {
let home = tempfile::tempdir().unwrap();
let path = home.path().join("nested").join(LedgerKey::FILE);
let key = LedgerKey::load_or_create(&path).unwrap();
assert_eq!(key.hash("s"), LedgerKey::load_or_create(&path).unwrap().hash("s"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "the key is owner-only");
}
std::fs::write(&path, "not a key").unwrap();
assert!(matches!(LedgerKey::load_or_create(&path), Err(KernelError::Config { .. })));
std::fs::write(&path, "").unwrap();
let filled = LedgerKey::load_or_create(&path).unwrap();
assert_eq!(filled.hash("s"), LedgerKey::load_or_create(&path).unwrap().hash("s"));
assert_ne!(filled.hash("s"), key.hash("s"));
}
#[tokio::test]
async fn a_late_sink_drops_until_bound() {
let store = Arc::new(super::super::InMemoryLedgerStore::new());
let late = LateLedgerSink::new();
late.record(Activity::new(LedgerKind::Intent, "harness")).await.unwrap();
assert!(late.bind(Arc::new(Ledger::new(store.clone(), LedgerKey::from_bytes([1; 32])))));
assert!(!late.bind(Arc::new(Ledger::new(store.clone(), LedgerKey::from_bytes([2; 32])))));
late.clone().record(Activity::new(LedgerKind::Intent, "harness")).await.unwrap();
let rows = store.list(&super::super::LedgerQuery::default()).await.unwrap();
assert_eq!(rows.len(), 1);
}
}