Skip to main content

adk_kernel/proc/
ledger.rs

1//! The content-free activity ledger: what writers submit, what is stored, the subject key
2//! and the writer (spec 3.2 §7.10, §9.2 K-I19).
3
4use 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
22/// The agent label of the rows the kernel writes about its own work (spec 3.2 §7.10).
23///
24/// The baselines leave these rows out, so the kernel's maintenance does not move the
25/// user's activity.
26pub const KERNEL_AGENT: &str = "kernel";
27
28/// Most entries a row's `meta` holds (spec 3.2 §7.10: small, schema-checked).
29pub const MAX_META_ENTRIES: usize = 8;
30
31/// What a ledger row records (spec 3.2 §7.10).
32///
33/// Serialized as a snake_case string; a name this enum does not know round-trips through
34/// [`Other`](Self::Other).
35///
36/// | Kind | Written by | When |
37/// |---|---|---|
38/// | `intent` | the harness | a run starts on a person's message |
39/// | `tool_call` | the harness | a tool call returned, with its duration |
40/// | `approval`, `rejection` | the harness's audit records | an approver granted or refused a held call |
41/// | `denial`, `held` | the harness's audit records | the policy denied a call, or held it for approval |
42/// | `turn` | the harness's `harness.spend` record | a harness run ended, with its counts and cost |
43/// | `loop_guard` | the harness's `harness.loop.detected` record | the loop guard ended a turn |
44/// | `audit` | the harness's other audit records | a mode change, a rule, a goal step |
45/// | `process` | the kernel, from `KernelEvent::Process` | a process changed state |
46/// | `wake`, `spend`, `rule_hit`, `governance` | the kernel, from its events | a wake was routed, spend committed, a rule hit, the kill switch changed |
47/// | `held`, `decided` | the kernel, from `KernelEvent::Held` and `Decided` | a process held a call, a held call was decided |
48/// | `observation` | the kernel | a baseline pass recorded an observation |
49/// | `proposal` | the kernel, from `KernelEvent::Agenda` | an agenda item changed state (spec 3.2 §7.5) |
50///
51/// # Example
52///
53/// ```rust
54/// use adk_kernel::proc::LedgerKind;
55///
56/// assert_eq!(LedgerKind::ToolCall.as_str(), "tool_call");
57/// assert_eq!(LedgerKind::from("tool_call".to_string()), LedgerKind::ToolCall);
58/// assert_eq!(LedgerKind::from("review".to_string()), LedgerKind::Other("review".into()));
59/// ```
60#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
61#[serde(from = "String", into = "String")]
62#[non_exhaustive]
63pub enum LedgerKind {
64    /// A run started on a person's message.
65    Intent,
66    /// A tool call returned.
67    ToolCall,
68    /// An approver granted a held call.
69    Approval,
70    /// An approver refused a held call.
71    Rejection,
72    /// The policy denied a call.
73    Denial,
74    /// A call was held for approval.
75    Held,
76    /// A held call was decided.
77    Decided,
78    /// A standing rule allowed a call.
79    RuleHit,
80    /// A baseline pass recorded an observation.
81    Observation,
82    /// A wake event was routed.
83    Wake,
84    /// An agent proposed a follow-up.
85    Proposal,
86    /// A process changed state.
87    Process,
88    /// Spend was committed to a process.
89    Spend,
90    /// A harness run ended.
91    Turn,
92    /// The loop guard ended a turn.
93    LoopGuard,
94    /// The kill switch changed.
95    Governance,
96    /// Another audit record.
97    Audit,
98    /// A kind this enum does not name.
99    Other(String),
100}
101
102impl LedgerKind {
103    /// The wire name.
104    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/// What a writer tells the ledger happened (spec 3.2 §7.10).
169///
170/// An activity may name its `subject` — what it was about, such as a tool call's
171/// fingerprint or a process id — in the clear: the [`Ledger`] stores only its HMAC under
172/// the kernel's key, never the subject itself. Everything else is stored as given, so it
173/// must be a label, a count or a duration; [`Ledger::entry`] refuses anything else.
174///
175/// # Example
176///
177/// ```rust
178/// use std::time::Duration;
179/// use adk_kernel::proc::{Activity, LedgerKind};
180///
181/// let activity = Activity::new(LedgerKind::ToolCall, "urn:adk:agent:adk-rust/harness")
182///     .with_effect("read_only")
183///     .with_duration(Duration::from_millis(182))
184///     .with_subject("read_file\u{1f}{\"path\":\"src/main.rs\"}")
185///     .with_count("attempt", 1);
186/// assert_eq!(activity.kind, LedgerKind::ToolCall);
187/// assert_eq!(activity.meta["attempt"], 1);
188/// ```
189#[derive(Debug, Clone, PartialEq)]
190#[non_exhaustive]
191pub struct Activity {
192    /// What happened.
193    pub kind: LedgerKind,
194    /// The agent that acted: its id, or [`KERNEL_AGENT`] for the kernel's own work.
195    pub agent: String,
196    /// The partition the activity belongs to.
197    pub partition: PartitionId,
198    /// The effect class of the action, such as `read_only`.
199    pub effect: Option<String>,
200    /// How long it took.
201    pub duration: Option<Duration>,
202    /// What it was about, in the clear; stored only as its HMAC.
203    pub subject: Option<String>,
204    /// Counts and flags; numbers feed the baselines.
205    pub meta: Map<String, Value>,
206    /// The trace or invocation the activity belongs to.
207    pub trace_id: Option<String>,
208    /// When it happened; the ledger's clock when unset.
209    pub at: Option<DateTime<Utc>>,
210}
211
212impl Activity {
213    /// An activity of `kind` by `agent`, in the default partition.
214    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    /// Sets the partition.
229    #[must_use]
230    pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
231        self.partition = partition.into();
232        self
233    }
234
235    /// Sets the effect class.
236    #[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    /// Sets how long it took.
243    #[must_use]
244    pub fn with_duration(mut self, duration: Duration) -> Self {
245        self.duration = Some(duration);
246        self
247    }
248
249    /// Sets what it was about; the ledger stores only its HMAC.
250    #[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    /// Adds a count to `meta`.
257    #[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    /// Adds a number to `meta`; a value that is not finite is left out.
264    #[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    /// Adds a flag to `meta`.
273    #[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    /// Sets the trace or invocation it belongs to.
280    #[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    /// Sets when it happened.
287    #[must_use]
288    pub fn at(mut self, at: DateTime<Utc>) -> Self {
289        self.at = Some(at);
290        self
291    }
292}
293
294/// One row of the ledger as stored and exported (spec 3.2 §7.10): `ts, partition, agent,
295/// kind, effect, duration_ms, subject_hash, meta, trace_id`, plus the store's `seq`.
296///
297/// It serializes as one camelCase JSON object, the line format `cargo adk eval --ledger`
298/// reads (`adk_eval::ledger::LedgerRow`, which ignores `seq`). `ts` carries the offset of
299/// the user's local time when it was written, so a day and a time of day read in it are the
300/// user's.
301///
302/// # Example
303///
304/// ```rust
305/// use adk_kernel::proc::LedgerEntry;
306///
307/// let line = r#"{"seq":7,"ts":"2026-10-22T19:20:04+03:00","partition":"default","agent":"kernel","kind":"wake","subjectHash":"hmac-sha256:00"}"#;
308/// let entry: LedgerEntry = serde_json::from_str(line).unwrap();
309/// assert_eq!(entry.kind, "wake");
310/// assert_eq!(entry.ts.offset().local_minus_utc(), 3 * 3600);
311/// assert_eq!(serde_json::to_string(&entry).unwrap(), line);
312/// ```
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
314#[serde(rename_all = "camelCase")]
315#[non_exhaustive]
316pub struct LedgerEntry {
317    /// The store's sequence number: increasing in append order, the paging cursor.
318    #[serde(default)]
319    pub seq: u64,
320    /// When it happened, in the user's local offset, to the millisecond.
321    pub ts: DateTime<FixedOffset>,
322    /// The partition.
323    pub partition: PartitionId,
324    /// The agent that acted.
325    pub agent: String,
326    /// What happened ([`LedgerKind`]'s wire name).
327    pub kind: String,
328    /// The effect class.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub effect: Option<String>,
331    /// How long it took.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub duration_ms: Option<u64>,
334    /// `hmac-sha256:<hex>` of the subject under the kernel's key.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub subject_hash: Option<String>,
337    /// Counts and flags.
338    #[serde(default, skip_serializing_if = "Map::is_empty")]
339    pub meta: Map<String, Value>,
340    /// The trace or invocation.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub trace_id: Option<String>,
343}
344
345impl LedgerEntry {
346    /// `ts` in UTC.
347    pub fn utc(&self) -> DateTime<Utc> {
348        self.ts.with_timezone(&Utc)
349    }
350
351    /// The day of `ts` in its own offset: the user's local day.
352    pub fn local_date(&self) -> NaiveDate {
353        self.ts.date_naive()
354    }
355
356    /// The row as one line of an export, without a newline.
357    ///
358    /// # Errors
359    ///
360    /// Returns [`KernelError::Serde`] when the row does not serialize, which a row the
361    /// ledger accepted always does.
362    pub fn to_jsonl(&self) -> Result<String> {
363        Ok(serde_json::to_string(self)?)
364    }
365}
366
367/// The per-kernel key the subject hashes are HMACs under (spec 3.2 §7.10).
368///
369/// It is held in the kernel home ([`FILE`](Self::FILE)), never in the ledger, so an export
370/// cannot be joined to the subjects it hashes by anyone without the home. Its `Debug` shows
371/// no bytes.
372///
373/// # Example
374///
375/// ```rust
376/// use adk_kernel::proc::LedgerKey;
377///
378/// let key = LedgerKey::from_bytes([7; 32]);
379/// let hash = key.hash("read_file");
380/// assert!(hash.starts_with("hmac-sha256:"));
381/// assert_eq!(hash, key.hash("read_file"));
382/// assert_ne!(hash, LedgerKey::from_bytes([8; 32]).hash("read_file"));
383/// assert_eq!(format!("{key:?}"), "LedgerKey(..)");
384/// ```
385#[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    /// The key's file name in the kernel home.
396    pub const FILE: &'static str = "ledger.key";
397
398    /// A key of these bytes.
399    pub fn from_bytes(bytes: [u8; 32]) -> Self {
400        Self(bytes)
401    }
402
403    /// A new random key from the operating system's generator.
404    ///
405    /// # Errors
406    ///
407    /// Returns [`KernelError::Config`] when the generator is unavailable.
408    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    /// The key in the file at `path`, or a new one written there, readable only by its
417    /// owner on Unix (mode `0600`). The file holds 64 hex digits. An empty file gets a new
418    /// key and keeps its permissions, so a caller can create it owner-only first, as
419    /// `adk-rust up` does with a protected DACL on Windows.
420    ///
421    /// # Errors
422    ///
423    /// Returns [`KernelError::Io`] when the file cannot be read or created, or
424    /// [`KernelError::Config`] when it does not hold a key.
425    ///
426    /// # Example
427    ///
428    /// ```rust
429    /// use adk_kernel::proc::LedgerKey;
430    ///
431    /// let home = tempfile::tempdir().unwrap();
432    /// let path = home.path().join(LedgerKey::FILE);
433    /// let key = LedgerKey::load_or_create(&path).unwrap();
434    /// assert_eq!(key.hash("x"), LedgerKey::load_or_create(&path).unwrap().hash("x"));
435    /// ```
436    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            // Another kernel created it first: use that one.
466            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    /// `hmac-sha256:<hex>` of `subject`.
486    pub fn hash(&self, subject: &str) -> String {
487        // A 32-byte key is a valid HMAC key; `new_from_slice` fails only on lengths a block
488        // cipher MAC would refuse.
489        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/// How the ledger stamps a row's local offset (spec 3.2 §7.10): the day and time of day
497/// the baselines read are the user's.
498///
499/// # Example
500///
501/// ```rust
502/// use adk_kernel::proc::LedgerOffset;
503/// use chrono::{FixedOffset, Utc};
504///
505/// let nairobi = FixedOffset::east_opt(3 * 3600).unwrap();
506/// assert_eq!(LedgerOffset::Fixed(nairobi).offset_at(Utc::now()), nairobi);
507/// ```
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
509#[non_exhaustive]
510pub enum LedgerOffset {
511    /// The operating system's local time zone at each write, daylight saving included.
512    #[default]
513    Local,
514    /// One fixed offset.
515    Fixed(FixedOffset),
516}
517
518impl LedgerOffset {
519    /// The offset in force at `at`.
520    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    /// The local day `at` falls on.
528    pub fn date_at(&self, at: DateTime<Utc>) -> NaiveDate {
529        at.with_timezone(&self.offset_at(at)).date_naive()
530    }
531}
532
533/// Where activity goes (spec 3.2 §7.10): the [`Ledger`], or a [`LateLedgerSink`] a runtime
534/// the kernel hosts writes through before the kernel exists. The harness writes its tool
535/// events and audit records through one.
536///
537/// # Example
538///
539/// ```rust
540/// use std::sync::Arc;
541/// use adk_kernel::proc::{Activity, InMemoryLedgerStore, Ledger, LedgerKey, LedgerKind, LedgerSink};
542///
543/// # #[tokio::main(flavor = "current_thread")]
544/// # async fn main() -> adk_kernel::Result<()> {
545/// let ledger = Ledger::new(Arc::new(InMemoryLedgerStore::new()), LedgerKey::from_bytes([1; 32]));
546/// let sink: Arc<dyn LedgerSink> = Arc::new(ledger.clone());
547/// sink.record(Activity::new(LedgerKind::Intent, "harness")).await?;
548/// # Ok(())
549/// # }
550/// ```
551#[async_trait]
552pub trait LedgerSink: Send + Sync {
553    /// Records `activity`.
554    ///
555    /// # Errors
556    ///
557    /// Returns an error with code [`LEDGER_INVALID_CODE`] when the activity carries
558    /// something other than labels, counts and durations, or the store's error.
559    async fn record(&self, activity: Activity) -> Result<()>;
560}
561
562/// A [`LedgerSink`] bound later (spec 3.2 §7.10): what a hosted runtime writes through
563/// before the kernel that owns the ledger has started. Until [`bind`](Self::bind) it drops
564/// activity; clones share the binding.
565///
566/// # Example
567///
568/// ```rust
569/// use std::sync::Arc;
570/// use adk_kernel::proc::{Activity, InMemoryLedgerStore, LateLedgerSink, Ledger, LedgerKey, LedgerKind, LedgerSink};
571///
572/// # #[tokio::main(flavor = "current_thread")]
573/// # async fn main() -> adk_kernel::Result<()> {
574/// let late = LateLedgerSink::new();
575/// late.record(Activity::new(LedgerKind::Intent, "harness")).await?; // dropped
576/// let store = Arc::new(InMemoryLedgerStore::new());
577/// assert!(late.bind(Arc::new(Ledger::new(store.clone(), LedgerKey::from_bytes([1; 32])))));
578/// late.record(Activity::new(LedgerKind::Intent, "harness")).await?;
579/// # Ok(())
580/// # }
581/// ```
582#[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    /// An unbound sink.
595    pub fn new() -> Self {
596        Self::default()
597    }
598
599    /// Binds `sink`; `false` when one is bound already, which stays.
600    pub fn bind(&self, sink: Arc<dyn LedgerSink>) -> bool {
601        self.sink.set(sink).is_ok()
602    }
603
604    /// Whether a sink is bound.
605    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/// The ledger writer (spec 3.2 §7.10): checks, hashes and stamps each [`Activity`] and
621/// appends the [`LedgerEntry`] to its [`LedgerStore`]. Cloning shares it.
622///
623/// A `Kernel` built with `KernelBuilder::ledger` writes its events through it and reads
624/// time from its own clock.
625///
626/// # Example
627///
628/// ```rust
629/// use std::sync::Arc;
630/// use adk_kernel::proc::{Activity, InMemoryLedgerStore, Ledger, LedgerKey, LedgerKind, LedgerQuery, LedgerSink};
631///
632/// # #[tokio::main(flavor = "current_thread")]
633/// # async fn main() -> adk_kernel::Result<()> {
634/// let ledger = Ledger::new(Arc::new(InMemoryLedgerStore::new()), LedgerKey::from_bytes([1; 32]));
635/// ledger.record(Activity::new(LedgerKind::ToolCall, "harness").with_subject("read_file")).await?;
636/// let rows = ledger.store().list(&LedgerQuery::default()).await?;
637/// assert_eq!(rows[0].kind, "tool_call");
638/// assert!(!rows[0].to_jsonl()?.contains("read_file"));
639/// # Ok(())
640/// # }
641/// ```
642#[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    /// A ledger over `store` hashing under `key`, on the system clock and local offset.
658    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    /// Reads time from `clock`.
668    #[must_use]
669    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
670        self.clock = clock;
671        self
672    }
673
674    /// Stamps rows with `offset`.
675    #[must_use]
676    pub fn with_offset(mut self, offset: LedgerOffset) -> Self {
677        self.offset = offset;
678        self
679    }
680
681    /// The store rows are appended to.
682    pub fn store(&self) -> &Arc<dyn LedgerStore> {
683        &self.store
684    }
685
686    /// How rows are stamped.
687    pub fn offset(&self) -> LedgerOffset {
688        self.offset
689    }
690
691    /// The clock rows are stamped from.
692    pub fn clock(&self) -> &Arc<dyn Clock> {
693        &self.clock
694    }
695
696    /// `hmac-sha256:<hex>` of `subject` under the ledger's key.
697    pub fn hash(&self, subject: &str) -> String {
698        self.key.hash(subject)
699    }
700
701    /// The row `activity` becomes, unstored (`seq` 0): checked, its subject hashed, stamped
702    /// to the millisecond in the local offset.
703    ///
704    /// # Errors
705    ///
706    /// Returns an error with code [`LEDGER_INVALID_CODE`] when a field is not a label, a
707    /// count or a duration (spec 3.2 K-I19). The message names the field, never its value.
708    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
753/// Longest agent and partition label.
754const MAX_LABEL: usize = 128;
755/// Longest effect label.
756const MAX_EFFECT: usize = 64;
757
758/// The error refusing `field`, which never quotes the value.
759fn 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
772/// A kind: 1 to 32 of `[a-z0-9_]`, starting with a letter.
773pub(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
780/// A label: letters and digits of any script and `._:/@+-`, no space or control character.
781pub(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
787/// An identifier as a label the ledger accepts (spec 3.2 §7.10): every character a label
788/// may not hold replaced with `_`, shortened to `max` characters. For identifiers a writer
789/// copies into a row, such as an agent's id or a run's target — never for content, which
790/// belongs in an activity's subject.
791///
792/// # Example
793///
794/// ```rust
795/// assert_eq!(adk_kernel::proc::label("urn:adk:agent:my app/coder", 128), "urn:adk:agent:my_app/coder");
796/// ```
797pub 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        // An empty file a caller created with its own permissions gets a key in place.
933        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}