1use std::fmt;
5use std::path::Path;
6use std::sync::{Arc, OnceLock};
7use std::time::Duration;
8
9use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, SystemClock};
10use async_trait::async_trait;
11use chrono::{DateTime, FixedOffset, NaiveDate, Offset as _, TimeZone as _, Utc};
12use hmac::Mac as _;
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16use super::LedgerStore;
17use crate::error::{KernelError, Result};
18use crate::partition::PartitionId;
19
20pub use crate::error::LEDGER_INVALID_CODE;
21
22pub const KERNEL_AGENT: &str = "kernel";
27
28pub const MAX_META_ENTRIES: usize = 8;
30
31#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
61#[serde(from = "String", into = "String")]
62#[non_exhaustive]
63pub enum LedgerKind {
64 Intent,
66 ToolCall,
68 Approval,
70 Rejection,
72 Denial,
74 Held,
76 Decided,
78 RuleHit,
80 Observation,
82 Wake,
84 Proposal,
86 Process,
88 Spend,
90 Turn,
92 LoopGuard,
94 Governance,
96 Audit,
98 Other(String),
100}
101
102impl LedgerKind {
103 pub fn as_str(&self) -> &str {
105 match self {
106 Self::Intent => "intent",
107 Self::ToolCall => "tool_call",
108 Self::Approval => "approval",
109 Self::Rejection => "rejection",
110 Self::Denial => "denial",
111 Self::Held => "held",
112 Self::Decided => "decided",
113 Self::RuleHit => "rule_hit",
114 Self::Observation => "observation",
115 Self::Wake => "wake",
116 Self::Proposal => "proposal",
117 Self::Process => "process",
118 Self::Spend => "spend",
119 Self::Turn => "turn",
120 Self::LoopGuard => "loop_guard",
121 Self::Governance => "governance",
122 Self::Audit => "audit",
123 Self::Other(name) => name,
124 }
125 }
126}
127
128impl From<String> for LedgerKind {
129 fn from(value: String) -> Self {
130 match value.as_str() {
131 "intent" => Self::Intent,
132 "tool_call" => Self::ToolCall,
133 "approval" => Self::Approval,
134 "rejection" => Self::Rejection,
135 "denial" => Self::Denial,
136 "held" => Self::Held,
137 "decided" => Self::Decided,
138 "rule_hit" => Self::RuleHit,
139 "observation" => Self::Observation,
140 "wake" => Self::Wake,
141 "proposal" => Self::Proposal,
142 "process" => Self::Process,
143 "spend" => Self::Spend,
144 "turn" => Self::Turn,
145 "loop_guard" => Self::LoopGuard,
146 "governance" => Self::Governance,
147 "audit" => Self::Audit,
148 _ => Self::Other(value),
149 }
150 }
151}
152
153impl From<LedgerKind> for String {
154 fn from(value: LedgerKind) -> Self {
155 match value {
156 LedgerKind::Other(name) => name,
157 known => known.as_str().to_string(),
158 }
159 }
160}
161
162impl fmt::Display for LedgerKind {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.write_str(self.as_str())
165 }
166}
167
168#[derive(Debug, Clone, PartialEq)]
190#[non_exhaustive]
191pub struct Activity {
192 pub kind: LedgerKind,
194 pub agent: String,
196 pub partition: PartitionId,
198 pub effect: Option<String>,
200 pub duration: Option<Duration>,
202 pub subject: Option<String>,
204 pub meta: Map<String, Value>,
206 pub trace_id: Option<String>,
208 pub at: Option<DateTime<Utc>>,
210}
211
212impl Activity {
213 pub fn new(kind: LedgerKind, agent: impl Into<String>) -> Self {
215 Self {
216 kind,
217 agent: agent.into(),
218 partition: PartitionId::default(),
219 effect: None,
220 duration: None,
221 subject: None,
222 meta: Map::new(),
223 trace_id: None,
224 at: None,
225 }
226 }
227
228 #[must_use]
230 pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
231 self.partition = partition.into();
232 self
233 }
234
235 #[must_use]
237 pub fn with_effect(mut self, effect: impl Into<String>) -> Self {
238 self.effect = Some(effect.into());
239 self
240 }
241
242 #[must_use]
244 pub fn with_duration(mut self, duration: Duration) -> Self {
245 self.duration = Some(duration);
246 self
247 }
248
249 #[must_use]
251 pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
252 self.subject = Some(subject.into());
253 self
254 }
255
256 #[must_use]
258 pub fn with_count(mut self, key: impl Into<String>, value: u64) -> Self {
259 self.meta.insert(key.into(), Value::from(value));
260 self
261 }
262
263 #[must_use]
265 pub fn with_number(mut self, key: impl Into<String>, value: f64) -> Self {
266 if let Some(number) = serde_json::Number::from_f64(value) {
267 self.meta.insert(key.into(), Value::Number(number));
268 }
269 self
270 }
271
272 #[must_use]
274 pub fn with_flag(mut self, key: impl Into<String>, value: bool) -> Self {
275 self.meta.insert(key.into(), Value::Bool(value));
276 self
277 }
278
279 #[must_use]
281 pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
282 self.trace_id = Some(trace_id.into());
283 self
284 }
285
286 #[must_use]
288 pub fn at(mut self, at: DateTime<Utc>) -> Self {
289 self.at = Some(at);
290 self
291 }
292}
293
294#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
314#[serde(rename_all = "camelCase")]
315#[non_exhaustive]
316pub struct LedgerEntry {
317 #[serde(default)]
319 pub seq: u64,
320 pub ts: DateTime<FixedOffset>,
322 pub partition: PartitionId,
324 pub agent: String,
326 pub kind: String,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub effect: Option<String>,
331 #[serde(default, skip_serializing_if = "Option::is_none")]
333 pub duration_ms: Option<u64>,
334 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub subject_hash: Option<String>,
337 #[serde(default, skip_serializing_if = "Map::is_empty")]
339 pub meta: Map<String, Value>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
342 pub trace_id: Option<String>,
343}
344
345impl LedgerEntry {
346 pub fn utc(&self) -> DateTime<Utc> {
348 self.ts.with_timezone(&Utc)
349 }
350
351 pub fn local_date(&self) -> NaiveDate {
353 self.ts.date_naive()
354 }
355
356 pub fn to_jsonl(&self) -> Result<String> {
363 Ok(serde_json::to_string(self)?)
364 }
365}
366
367#[derive(Clone)]
386pub struct LedgerKey([u8; 32]);
387
388impl fmt::Debug for LedgerKey {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 f.write_str("LedgerKey(..)")
391 }
392}
393
394impl LedgerKey {
395 pub const FILE: &'static str = "ledger.key";
397
398 pub fn from_bytes(bytes: [u8; 32]) -> Self {
400 Self(bytes)
401 }
402
403 pub fn generate() -> Result<Self> {
409 let mut bytes = [0u8; 32];
410 getrandom::fill(&mut bytes).map_err(|error| KernelError::Config {
411 reason: format!("the ledger key needs the operating system's random source: {error}"),
412 })?;
413 Ok(Self(bytes))
414 }
415
416 pub fn load_or_create(path: &Path) -> Result<Self> {
437 match std::fs::read_to_string(path) {
438 Ok(text) if text.trim().is_empty() => {
439 let key = Self::generate()?;
440 let mut file = std::fs::OpenOptions::new().write(true).truncate(true).open(path)?;
441 use std::io::Write as _;
442 writeln!(file, "{}", hex::encode(key.0))?;
443 file.sync_all()?;
444 return Ok(key);
445 }
446 Ok(text) => return Self::parse(path, &text),
447 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
448 Err(error) => return Err(error.into()),
449 }
450 let key = Self::generate()?;
451 if let Some(parent) = path.parent() {
452 std::fs::create_dir_all(parent)?;
453 }
454 let mut options = std::fs::OpenOptions::new();
455 options.write(true).create_new(true);
456 #[cfg(unix)]
457 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
458 match options.open(path) {
459 Ok(mut file) => {
460 use std::io::Write as _;
461 writeln!(file, "{}", hex::encode(key.0))?;
462 file.sync_all()?;
463 Ok(key)
464 }
465 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
467 Self::parse(path, &std::fs::read_to_string(path)?)
468 }
469 Err(error) => Err(error.into()),
470 }
471 }
472
473 fn parse(path: &Path, text: &str) -> Result<Self> {
474 let bytes =
475 hex::decode(text.trim()).ok().and_then(|bytes| <[u8; 32]>::try_from(bytes).ok());
476 bytes.map(Self).ok_or_else(|| KernelError::Config {
477 reason: format!(
478 "{} does not hold a ledger key (64 hex digits); move it aside to start a new \
479 key, which makes the existing subject hashes unrelatable to new ones",
480 path.display()
481 ),
482 })
483 }
484
485 pub fn hash(&self, subject: &str) -> String {
487 let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&self.0)
490 .unwrap_or_else(|_| unreachable!("HMAC-SHA256 takes a key of any length"));
491 mac.update(subject.as_bytes());
492 format!("hmac-sha256:{}", hex::encode(mac.finalize().into_bytes()))
493 }
494}
495
496#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
509#[non_exhaustive]
510pub enum LedgerOffset {
511 #[default]
513 Local,
514 Fixed(FixedOffset),
516}
517
518impl LedgerOffset {
519 pub fn offset_at(&self, at: DateTime<Utc>) -> FixedOffset {
521 match self {
522 Self::Local => chrono::Local.offset_from_utc_datetime(&at.naive_utc()).fix(),
523 Self::Fixed(offset) => *offset,
524 }
525 }
526
527 pub fn date_at(&self, at: DateTime<Utc>) -> NaiveDate {
529 at.with_timezone(&self.offset_at(at)).date_naive()
530 }
531}
532
533#[async_trait]
552pub trait LedgerSink: Send + Sync {
553 async fn record(&self, activity: Activity) -> Result<()>;
560}
561
562#[derive(Clone, Default)]
583pub struct LateLedgerSink {
584 sink: Arc<OnceLock<Arc<dyn LedgerSink>>>,
585}
586
587impl fmt::Debug for LateLedgerSink {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 f.debug_struct("LateLedgerSink").field("bound", &self.is_bound()).finish()
590 }
591}
592
593impl LateLedgerSink {
594 pub fn new() -> Self {
596 Self::default()
597 }
598
599 pub fn bind(&self, sink: Arc<dyn LedgerSink>) -> bool {
601 self.sink.set(sink).is_ok()
602 }
603
604 pub fn is_bound(&self) -> bool {
606 self.sink.get().is_some()
607 }
608}
609
610#[async_trait]
611impl LedgerSink for LateLedgerSink {
612 async fn record(&self, activity: Activity) -> Result<()> {
613 match self.sink.get() {
614 Some(sink) => sink.record(activity).await,
615 None => Ok(()),
616 }
617 }
618}
619
620#[derive(Clone)]
643pub struct Ledger {
644 store: Arc<dyn LedgerStore>,
645 key: Arc<LedgerKey>,
646 clock: Arc<dyn Clock>,
647 offset: LedgerOffset,
648}
649
650impl fmt::Debug for Ledger {
651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 f.debug_struct("Ledger").field("offset", &self.offset).finish_non_exhaustive()
653 }
654}
655
656impl Ledger {
657 pub fn new(store: Arc<dyn LedgerStore>, key: LedgerKey) -> Self {
659 Self {
660 store,
661 key: Arc::new(key),
662 clock: Arc::new(SystemClock),
663 offset: LedgerOffset::Local,
664 }
665 }
666
667 #[must_use]
669 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
670 self.clock = clock;
671 self
672 }
673
674 #[must_use]
676 pub fn with_offset(mut self, offset: LedgerOffset) -> Self {
677 self.offset = offset;
678 self
679 }
680
681 pub fn store(&self) -> &Arc<dyn LedgerStore> {
683 &self.store
684 }
685
686 pub fn offset(&self) -> LedgerOffset {
688 self.offset
689 }
690
691 pub fn clock(&self) -> &Arc<dyn Clock> {
693 &self.clock
694 }
695
696 pub fn hash(&self, subject: &str) -> String {
698 self.key.hash(subject)
699 }
700
701 pub fn entry(&self, activity: Activity) -> Result<LedgerEntry> {
709 let Activity { kind, agent, partition, effect, duration, subject, meta, trace_id, at } =
710 activity;
711 let kind = String::from(kind);
712 if !is_kind(&kind) {
713 return Err(invalid("kind", "a kind is 1 to 32 lowercase letters, digits and `_`"));
714 }
715 check_label("agent", &agent, MAX_LABEL)?;
716 check_label("partition", partition.as_str(), MAX_LABEL)?;
717 if let Some(effect) = &effect {
718 check_label("effect", effect, MAX_EFFECT)?;
719 }
720 if let Some(trace_id) = &trace_id
721 && !is_trace(trace_id)
722 {
723 return Err(invalid("trace id", "a trace id is 1 to 64 ASCII letters, digits and `-`"));
724 }
725 check_meta(&meta)?;
726 let at = at.unwrap_or_else(|| self.clock.now());
727 let at = DateTime::from_timestamp_millis(at.timestamp_millis()).unwrap_or(at);
728 Ok(LedgerEntry {
729 seq: 0,
730 ts: at.with_timezone(&self.offset.offset_at(at)),
731 partition,
732 agent,
733 kind,
734 effect,
735 duration_ms: duration
736 .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)),
737 subject_hash: subject.map(|subject| self.key.hash(&subject)),
738 meta,
739 trace_id,
740 })
741 }
742}
743
744#[async_trait]
745impl LedgerSink for Ledger {
746 async fn record(&self, activity: Activity) -> Result<()> {
747 let entry = self.entry(activity)?;
748 self.store.append(entry).await?;
749 Ok(())
750 }
751}
752
753const MAX_LABEL: usize = 128;
755const MAX_EFFECT: usize = 64;
757
758fn invalid(field: &str, rule: &str) -> KernelError {
760 KernelError::Core(AdkError::new(
761 ErrorComponent::Server,
762 ErrorCategory::InvalidInput,
763 LEDGER_INVALID_CODE,
764 format!(
765 "the ledger refuses this {field}: {rule}. A ledger row holds labels, counts, \
766 durations and hashes only, never content (spec 3.2 K-I19); pass what it is about \
767 as the activity's subject, which is stored as a hash"
768 ),
769 ))
770}
771
772pub(crate) fn is_kind(value: &str) -> bool {
774 let mut chars = value.chars();
775 value.len() <= 32
776 && chars.next().is_some_and(|first| first.is_ascii_lowercase())
777 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
778}
779
780pub(crate) fn is_label(value: &str, max: usize) -> bool {
782 !value.is_empty()
783 && value.chars().count() <= max
784 && value.chars().all(|c| c.is_alphanumeric() || "._:/@+-".contains(c))
785}
786
787pub fn label(value: &str, max: usize) -> String {
798 let cleaned: String = value
799 .chars()
800 .take(max)
801 .map(|c| if c.is_alphanumeric() || "._:/@+-".contains(c) { c } else { '_' })
802 .collect();
803 if cleaned.is_empty() { "_".to_string() } else { cleaned }
804}
805
806fn is_trace(value: &str) -> bool {
807 (1..=64).contains(&value.len()) && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
808}
809
810fn check_label(field: &str, value: &str, max: usize) -> Result<()> {
811 if is_label(value, max) {
812 return Ok(());
813 }
814 Err(invalid(
815 field,
816 &format!("a label is 1 to {max} letters, digits and `._:/@+-`, with no space"),
817 ))
818}
819
820fn check_meta(meta: &Map<String, Value>) -> Result<()> {
821 if meta.len() > MAX_META_ENTRIES {
822 return Err(invalid("meta", &format!("meta holds at most {MAX_META_ENTRIES} entries")));
823 }
824 for (key, value) in meta {
825 if !is_kind(key) {
826 return Err(invalid(
827 "meta key",
828 "a meta key is 1 to 32 lowercase letters, digits and `_`",
829 ));
830 }
831 if !matches!(value, Value::Number(_) | Value::Bool(_)) {
832 return Err(invalid("meta value", "a meta value is a number or a boolean"));
833 }
834 }
835 Ok(())
836}
837
838#[cfg(test)]
839mod tests {
840 use super::*;
841 use crate::error::KernelError;
842
843 fn ledger() -> Ledger {
844 Ledger::new(
845 Arc::new(super::super::InMemoryLedgerStore::new()),
846 LedgerKey::from_bytes([3; 32]),
847 )
848 .with_offset(LedgerOffset::Fixed(FixedOffset::east_opt(3 * 3600).unwrap()))
849 }
850
851 fn code(error: KernelError) -> String {
852 adk_core::AdkError::from(error).code.to_string()
853 }
854
855 #[test]
856 fn an_entry_hashes_its_subject_and_stamps_the_local_offset() {
857 let at = DateTime::parse_from_rfc3339("2026-10-22T16:20:04.123456Z").unwrap().to_utc();
858 let entry = ledger()
859 .entry(
860 Activity::new(LedgerKind::ToolCall, "urn:adk:agent:adk-rust/harness")
861 .with_subject("bash\u{1f}{\"command\":\"cat .env\"}")
862 .with_duration(Duration::from_millis(1500))
863 .with_count("attempt", 2)
864 .with_flag("retried", true)
865 .with_trace_id("4bf92f3577b34da6a3ce929d0e0e4736")
866 .at(at),
867 )
868 .unwrap();
869 assert_eq!(entry.ts.to_rfc3339(), "2026-10-22T19:20:04.123+03:00");
870 assert_eq!(entry.local_date(), NaiveDate::from_ymd_opt(2026, 10, 22).unwrap());
871 assert_eq!(entry.duration_ms, Some(1500));
872 let hash = entry.subject_hash.clone().unwrap();
873 assert_eq!(hash.len(), "hmac-sha256:".len() + 64);
874 let line = entry.to_jsonl().unwrap();
875 assert!(!line.contains("cat .env") && !line.contains("bash"), "{line}");
876 }
877
878 #[test]
879 fn content_in_a_label_or_meta_is_refused_without_quoting_it() {
880 let secret = "sk-live AKIA very secret";
881 let refused = [
882 Activity::new(LedgerKind::ToolCall, secret),
883 Activity::new(LedgerKind::ToolCall, "harness").with_effect(secret),
884 Activity::new(LedgerKind::ToolCall, "harness").with_partition(secret),
885 Activity::new(LedgerKind::Other(secret.into()), "harness"),
886 Activity::new(LedgerKind::ToolCall, "harness").with_trace_id(secret),
887 {
888 let mut activity = Activity::new(LedgerKind::ToolCall, "harness");
889 activity.meta.insert("path".into(), Value::String(secret.into()));
890 activity
891 },
892 {
893 let mut activity = Activity::new(LedgerKind::ToolCall, "harness");
894 activity.meta.insert("Bad Key".into(), Value::from(1));
895 activity
896 },
897 (0..=MAX_META_ENTRIES).fold(Activity::new(LedgerKind::ToolCall, "harness"), |a, n| {
898 a.with_count(format!("n{n}"), 1)
899 }),
900 ];
901 for activity in refused {
902 let error = ledger().entry(activity).unwrap_err();
903 assert!(!error.to_string().contains("secret"), "{error}");
904 assert_eq!(code(error), LEDGER_INVALID_CODE);
905 }
906 }
907
908 #[test]
909 fn labels_take_identifiers_of_any_script() {
910 assert!(is_label("urn:adk:agent:adk-rust/harness", MAX_LABEL));
911 assert!(is_label("ü-日本", MAX_LABEL));
912 assert!(!is_label("two words", MAX_LABEL));
913 assert!(!is_label("", MAX_LABEL));
914 assert_eq!(label("a b\nc", 8), "a_b_c");
915 assert_eq!(label("", 8), "_");
916 }
917
918 #[test]
919 fn a_key_round_trips_through_its_file() {
920 let home = tempfile::tempdir().unwrap();
921 let path = home.path().join("nested").join(LedgerKey::FILE);
922 let key = LedgerKey::load_or_create(&path).unwrap();
923 assert_eq!(key.hash("s"), LedgerKey::load_or_create(&path).unwrap().hash("s"));
924 #[cfg(unix)]
925 {
926 use std::os::unix::fs::PermissionsExt as _;
927 let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
928 assert_eq!(mode, 0o600, "the key is owner-only");
929 }
930 std::fs::write(&path, "not a key").unwrap();
931 assert!(matches!(LedgerKey::load_or_create(&path), Err(KernelError::Config { .. })));
932 std::fs::write(&path, "").unwrap();
934 let filled = LedgerKey::load_or_create(&path).unwrap();
935 assert_eq!(filled.hash("s"), LedgerKey::load_or_create(&path).unwrap().hash("s"));
936 assert_ne!(filled.hash("s"), key.hash("s"));
937 }
938
939 #[tokio::test]
940 async fn a_late_sink_drops_until_bound() {
941 let store = Arc::new(super::super::InMemoryLedgerStore::new());
942 let late = LateLedgerSink::new();
943 late.record(Activity::new(LedgerKind::Intent, "harness")).await.unwrap();
944 assert!(late.bind(Arc::new(Ledger::new(store.clone(), LedgerKey::from_bytes([1; 32])))));
945 assert!(!late.bind(Arc::new(Ledger::new(store.clone(), LedgerKey::from_bytes([2; 32])))));
946 late.clone().record(Activity::new(LedgerKind::Intent, "harness")).await.unwrap();
947 let rows = store.list(&super::super::LedgerQuery::default()).await.unwrap();
948 assert_eq!(rows.len(), 1);
949 }
950}