Skip to main content

adk_kernel/proc/
mod.rs

1//! `/proc`: the kernel's self-observation (spec 3.2 §7.10, §13 Q4; feature `proc`).
2//!
3//! The kernel keeps a content-free activity ledger and, behind `proc-baselines`, learns a
4//! per-partition baseline from it, in three tiers:
5//!
6//! | Tier | Where | What |
7//! |---|---|---|
8//! | Ledger and live aggregates | the kernel, feature `proc` | one append-only table of [`LedgerEntry`] rows; the live `ps`/`top` view and the OTel GenAI histograms are the process table's ([`ProcessView`](crate::ProcessView)) |
9//! | Statistics | `adk-eval`'s `ledger` module, pure functions | rolling 28-day median and MAD per dimension and day class, the 14-day warm-up, the windowed deviation test; `cargo adk eval --ledger <export.jsonl>` runs them in CI |
10//! | Baselines and observations | the kernel's `Maintenance` process, feature `proc-baselines` | the daily pass (`baselines`) calls the statistics, applies the "meaningful" rule and the seven-day cooldown, and offers each observation as a neutral question |
11//!
12//! # The ledger
13//!
14//! A row is `ts, partition, agent, kind, effect, duration_ms, subject_hash, meta, trace_id`
15//! ([`LedgerEntry`]): never a payload, a prompt, a file's content or a secret (K-I19). A
16//! writer submits an [`Activity`]; the [`Ledger`] checks that every field is a label, a
17//! count or a duration, stores what the activity was about only as an HMAC under the
18//! kernel's [`LedgerKey`], and stamps the user's local offset.
19//!
20//! | Writer | Through | Rows |
21//! |---|---|---|
22//! | The kernel | its event bus: every [`KernelEvent`](crate::KernelEvent) but `Health` ([`activity_for_event`]) | `process`, `wake`, `held`, `decided`, `rule_hit`, `spend`, `governance`, `observation` |
23//! | The harness | a [`LedgerSink`] the kernel hands its `ProgressSource` at start ([`ProgressSource::attach_ledger`](crate::ProgressSource::attach_ledger)) | `intent` and `tool_call` from its runs; `approval`, `rejection`, `denial`, `held`, `turn`, `loop_guard` and `audit` from its audit records ([`LedgerAuditTap`], [`activity_for_audit`]) |
24//!
25//! [`LedgerStore`] holds the rows, the observations and the pass state on every backend the
26//! [`ProcessStore`](crate::ProcessStore) has: in-memory, SQLite, PostgreSQL and Redis, with
27//! one conformance suite (`ledger_store_conformance_tests!`). The ledger never leaves the
28//! host unless its user exports it: `GET /api/kernel/proc/ledger?format=jsonl`, an operator
29//! route, writes the JSONL `cargo adk eval --ledger` reads.
30//!
31//! # Example
32//!
33//! ```rust
34//! use std::sync::Arc;
35//! use std::time::Duration;
36//! use adk_kernel::proc::{Activity, InMemoryLedgerStore, Ledger, LedgerKey, LedgerKind, LedgerQuery, LedgerSink};
37//!
38//! # #[tokio::main(flavor = "current_thread")]
39//! # async fn main() -> adk_kernel::Result<()> {
40//! let ledger = Ledger::new(Arc::new(InMemoryLedgerStore::new()), LedgerKey::from_bytes([9; 32]));
41//! ledger
42//!     .record(
43//!         Activity::new(LedgerKind::ToolCall, "urn:adk:agent:adk-rust/harness")
44//!             .with_effect("read_only")
45//!             .with_duration(Duration::from_millis(140))
46//!             .with_subject("read_file\u{1f}{\"path\":\"notes/salary.md\"}"),
47//!     )
48//!     .await?;
49//! let rows = ledger.store().list(&LedgerQuery::default().kind("tool_call")).await?;
50//! let line = rows[0].to_jsonl()?;
51//! assert!(line.contains("\"durationMs\":140") && !line.contains("salary"));
52//! # Ok(())
53//! # }
54//! ```
55
56use async_trait::async_trait;
57use chrono::{DateTime, NaiveDate, Utc};
58use serde::{Deserialize, Serialize};
59
60use crate::error::Result;
61use crate::partition::PartitionId;
62
63#[cfg(feature = "proc-baselines")]
64pub mod baselines;
65mod ledger;
66mod observation;
67mod sources;
68
69#[cfg(feature = "firestore")]
70pub use crate::stores::FirestoreLedgerStore;
71pub use crate::stores::InMemoryLedgerStore;
72#[cfg(feature = "mongodb")]
73pub use crate::stores::MongoLedgerStore;
74#[cfg(feature = "neo4j")]
75pub use crate::stores::Neo4jLedgerStore;
76#[cfg(feature = "postgres")]
77pub use crate::stores::PostgresLedgerStore;
78#[cfg(feature = "redis")]
79pub use crate::stores::RedisLedgerStore;
80#[cfg(feature = "sqlite")]
81pub use crate::stores::SqliteLedgerStore;
82pub use ledger::{
83    Activity, KERNEL_AGENT, LEDGER_INVALID_CODE, LateLedgerSink, Ledger, LedgerEntry, LedgerKey,
84    LedgerKind, LedgerOffset, LedgerSink, MAX_META_ENTRIES, label,
85};
86pub use observation::{
87    Direction, Observation, ObservedDimension, PassState, Phrasing, is_neutral_question,
88    template_question,
89};
90pub(crate) use sources::LedgerEventSink;
91pub use sources::{LedgerAuditTap, activity_for_audit, activity_for_event};
92
93/// The kernel's ledger, observations and baseline pass state (spec 3.2 §7.10, §13 Q8).
94///
95/// The ledger is append-only: rows are added and read, never changed. Observations are
96/// replaced by id, so two replicas recording one observation store one; the pass state is
97/// one record per partition.
98///
99/// # Example
100///
101/// ```rust
102/// use std::sync::Arc;
103/// use adk_kernel::proc::{Activity, InMemoryLedgerStore, Ledger, LedgerKey, LedgerKind, LedgerQuery, LedgerStore};
104///
105/// # #[tokio::main(flavor = "current_thread")]
106/// # async fn main() -> adk_kernel::Result<()> {
107/// let store = InMemoryLedgerStore::new();
108/// let ledger = Ledger::new(Arc::new(InMemoryLedgerStore::new()), LedgerKey::from_bytes([1; 32]));
109/// let first = store.append(ledger.entry(Activity::new(LedgerKind::Wake, "kernel"))?).await?;
110/// let second = store.append(ledger.entry(Activity::new(LedgerKind::Intent, "harness"))?).await?;
111/// assert!(second.seq > first.seq);
112/// let after = store.list(&LedgerQuery::default().after(first.seq)).await?;
113/// assert_eq!(after, [second]);
114/// # Ok(())
115/// # }
116/// ```
117#[async_trait]
118pub trait LedgerStore: Send + Sync {
119    /// Appends `entry` with the next sequence number and returns it as stored; `entry.seq`
120    /// is ignored.
121    ///
122    /// # Errors
123    ///
124    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
125    async fn append(&self, entry: LedgerEntry) -> Result<LedgerEntry>;
126
127    /// The rows `query` selects, in sequence order, at most `query.limit`.
128    ///
129    /// # Errors
130    ///
131    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
132    async fn list(&self, query: &LedgerQuery) -> Result<Vec<LedgerEntry>>;
133
134    /// Inserts `observation`, or replaces the one with the same id.
135    ///
136    /// # Errors
137    ///
138    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
139    async fn put_observation(&self, observation: Observation) -> Result<()>;
140
141    /// The observations `query` selects, newest day first, then by id.
142    ///
143    /// # Errors
144    ///
145    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
146    async fn observations(&self, query: &ObservationQuery) -> Result<Vec<Observation>>;
147
148    /// The pass state of `partition`, or `None` before its first pass.
149    ///
150    /// # Errors
151    ///
152    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
153    async fn pass_state(&self, partition: &PartitionId) -> Result<Option<PassState>>;
154
155    /// Every partition's pass state, by partition.
156    ///
157    /// # Errors
158    ///
159    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
160    async fn pass_states(&self) -> Result<Vec<PassState>>;
161
162    /// Stores `state` as its partition's pass state.
163    ///
164    /// # Errors
165    ///
166    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
167    async fn put_pass_state(&self, state: PassState) -> Result<()>;
168}
169
170/// Which ledger rows [`LedgerStore::list`] returns (spec 3.2 §7.10, §7.11
171/// `GET /kernel/proc/ledger`). An empty field matches every row.
172///
173/// # Example
174///
175/// ```rust
176/// use adk_kernel::proc::LedgerQuery;
177///
178/// let query = LedgerQuery::default().partition("work").kind("tool_call").after(41).limit(100);
179/// assert_eq!(query.kinds, ["tool_call"]);
180/// assert_eq!(query.after, Some(41));
181/// ```
182#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase")]
184#[non_exhaustive]
185pub struct LedgerQuery {
186    /// Only rows of this partition.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub partition: Option<PartitionId>,
189    /// Only rows of these kinds.
190    #[serde(default, skip_serializing_if = "Vec::is_empty")]
191    pub kinds: Vec<String>,
192    /// Only rows of this agent.
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub agent: Option<String>,
195    /// Only rows at or after this instant.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub from: Option<DateTime<Utc>>,
198    /// Only rows before this instant.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub to: Option<DateTime<Utc>>,
201    /// Only rows after this sequence number: the cursor of the previous page.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub after: Option<u64>,
204    /// At most this many rows.
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub limit: Option<usize>,
207}
208
209impl LedgerQuery {
210    /// Only rows of `partition`.
211    #[must_use]
212    pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
213        self.partition = Some(partition.into());
214        self
215    }
216
217    /// Also rows of `kind`.
218    #[must_use]
219    pub fn kind(mut self, kind: impl Into<String>) -> Self {
220        self.kinds.push(kind.into());
221        self
222    }
223
224    /// Only rows of `agent`.
225    #[must_use]
226    pub fn agent(mut self, agent: impl Into<String>) -> Self {
227        self.agent = Some(agent.into());
228        self
229    }
230
231    /// Only rows at or after `from`.
232    #[must_use]
233    pub fn from(mut self, from: DateTime<Utc>) -> Self {
234        self.from = Some(from);
235        self
236    }
237
238    /// Only rows before `to`.
239    #[must_use]
240    pub fn to(mut self, to: DateTime<Utc>) -> Self {
241        self.to = Some(to);
242        self
243    }
244
245    /// Only rows after sequence number `after`.
246    #[must_use]
247    pub fn after(mut self, after: u64) -> Self {
248        self.after = Some(after);
249        self
250    }
251
252    /// At most `limit` rows.
253    #[must_use]
254    pub fn limit(mut self, limit: usize) -> Self {
255        self.limit = Some(limit);
256        self
257    }
258
259    /// Whether `entry` passes every field but `limit`.
260    pub fn matches(&self, entry: &LedgerEntry) -> bool {
261        let at = entry.utc();
262        self.partition.as_ref().is_none_or(|partition| *partition == entry.partition)
263            && (self.kinds.is_empty() || self.kinds.contains(&entry.kind))
264            && self.agent.as_ref().is_none_or(|agent| *agent == entry.agent)
265            && self.from.is_none_or(|from| at >= from)
266            && self.to.is_none_or(|to| at < to)
267            && self.after.is_none_or(|after| entry.seq > after)
268    }
269}
270
271/// Which observations [`LedgerStore::observations`] returns (spec 3.2 §7.11
272/// `GET /kernel/proc/observations`).
273///
274/// # Example
275///
276/// ```rust
277/// use adk_kernel::proc::ObservationQuery;
278///
279/// let query = ObservationQuery::default().partition("work").limit(5);
280/// assert_eq!(query.limit, Some(5));
281/// ```
282#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284#[non_exhaustive]
285pub struct ObservationQuery {
286    /// Only observations of this partition.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub partition: Option<PartitionId>,
289    /// Only observations of this day or later.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub since: Option<NaiveDate>,
292    /// At most this many.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub limit: Option<usize>,
295}
296
297impl ObservationQuery {
298    /// Only observations of `partition`.
299    #[must_use]
300    pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
301        self.partition = Some(partition.into());
302        self
303    }
304
305    /// Only observations of `since` or later.
306    #[must_use]
307    pub fn since(mut self, since: NaiveDate) -> Self {
308        self.since = Some(since);
309        self
310    }
311
312    /// At most `limit` observations.
313    #[must_use]
314    pub fn limit(mut self, limit: usize) -> Self {
315        self.limit = Some(limit);
316        self
317    }
318
319    /// Whether `observation` passes every field but `limit`.
320    pub fn matches(&self, observation: &Observation) -> bool {
321        self.partition.as_ref().is_none_or(|partition| *partition == observation.partition)
322            && self.since.is_none_or(|since| observation.as_of >= since)
323    }
324}
325
326/// Orders observations newest day first, then by id, as every backend returns them.
327pub(crate) fn order_observations(observations: &mut [Observation]) {
328    observations.sort_by(|a, b| b.as_of.cmp(&a.as_of).then_with(|| a.id.cmp(&b.id)));
329}