Skip to main content

adk_kernel/control/
record.rs

1//! The record of what the agents did, and its check (spec 3.3 §10 K5, §5.1 "What your
2//! agents did", §11).
3//!
4//! The kernel writes its records to a signed audit log it cannot read back or verify
5//! itself: the log's store and its checkpoint keys belong to whoever opened it. A
6//! [`RecordBook`] is what that host gives the kernel; `adk-rust up` builds one over the
7//! kernel's signed audit log that checks it with the verifier `adk-rust audit verify` runs,
8//! so the home's "Every action is on record" and the command give the same answer.
9//!
10//! | Route (under `/api`) | Caller | Does |
11//! |---|---|---|
12//! | `GET /kernel/record` | operator, or a device with `read` | The latest actions as structured lines ([`RecordResponse`], [`RecordQuery`]) |
13//! | `GET /kernel/record/check` | operator, or a device with `read` | Whether every action is on record and nothing was changed or deleted ([`RecordCheck`]) |
14
15use std::sync::Arc;
16
17use async_trait::async_trait;
18use axum::Json;
19use axum::Router;
20use axum::extract::{Query, State};
21use axum::routing::get;
22use chrono::{DateTime, Utc};
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25
26use super::paths;
27use super::routes::{Caller, ControlBackend};
28use crate::error::{KernelError, Result};
29
30/// One action on record, as structured fields a surface words as a sentence ("You let
31/// Finance send one email, from Telegram", spec 3.3 §5.1, §11).
32///
33/// # Example
34///
35/// ```rust
36/// use adk_kernel::control::RecordLine;
37///
38/// let line = RecordLine::new(1284, chrono::Utc::now(), "approval")
39///     .with_subject("ana")
40///     .with_agent("finance")
41///     .with_how("chat", Some("telegram"));
42/// assert_eq!(serde_json::to_value(&line).unwrap()["channel"], "telegram");
43///
44/// let device = RecordLine::new(1285, chrono::Utc::now(), "kernel.control")
45///     .with_kernel_action("approvals.decide")
46///     .with_decision("approved")
47///     .with_channel("Ana's phone");
48/// assert_eq!(serde_json::to_value(&device).unwrap()["kernelAction"], "approvals.decide");
49/// ```
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52#[non_exhaustive]
53pub struct RecordLine {
54    /// The entry's place in the log.
55    pub seq: u64,
56    /// When it was recorded.
57    pub at: DateTime<Utc>,
58    /// The record's action, such as `approval` or `kernel.control`.
59    pub action: String,
60    /// What a kernel record (`kernel.control`, `kernel.channel`) did: `approvals.decide`,
61    /// `pairing.issue`, `freeze`, `settings.quiet_time`, a chat answer's `decide`.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub kernel_action: Option<String>,
64    /// The person or service that acted.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub subject: Option<String>,
67    /// The agent that acted, or whose call was decided.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub agent: Option<String>,
70    /// The tool, for a call.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub tool: Option<String>,
73    /// The decision: `approved`, `rejected`, `denied`, `allowed`.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub decision: Option<String>,
76    /// How it ended: `succeeded`, `failed`.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub outcome: Option<String>,
79    /// How the answer was given: `keyboard`, `touch`, `voice`, `chat`.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub how: Option<String>,
82    /// The chat channel or device it was given from.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub channel: Option<String>,
85    /// The surface it was given on, as the record names it: `web`, `tray`, `phone`,
86    /// `terminal`, `voice`, `chat`, or `device` for a paired device on the kernel's own routes
87    /// (spec 3.3 §11).
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub surface: Option<String>,
90    /// What it acted on: a process, a fact, an area.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub target: Option<String>,
93    /// The item it acted on, as the person knows it — "News digest" — where the record names
94    /// one, such as the answer to an agent's screen action (spec 3.3 §8, §11).
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub title: Option<String>,
97    /// Who publishes the tool, for a call: `verbs:adk-rust` for a screen action, so a surface
98    /// tells a feature's calls apart by their publisher, never by the tool's name (spec 3.3
99    /// §7.1).
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub tool_source: Option<String>,
102    /// What decided a call: `confirmation` for a person's answer, `tool_policy:<name>`,
103    /// `governance`, `guardrail` (spec 3.3 §11).
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub policy_ref: Option<String>,
106}
107
108impl RecordLine {
109    /// Entry `seq`, recorded at `at`, of `action`.
110    pub fn new(seq: u64, at: DateTime<Utc>, action: impl Into<String>) -> Self {
111        Self {
112            seq,
113            at,
114            action: action.into(),
115            kernel_action: None,
116            subject: None,
117            agent: None,
118            tool: None,
119            decision: None,
120            outcome: None,
121            how: None,
122            channel: None,
123            surface: None,
124            target: None,
125            title: None,
126            tool_source: None,
127            policy_ref: None,
128        }
129    }
130
131    /// Sets who acted.
132    #[must_use]
133    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
134        self.subject = Some(subject.into());
135        self
136    }
137
138    /// Sets the agent.
139    #[must_use]
140    pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
141        self.agent = Some(agent.into());
142        self
143    }
144
145    /// Sets the tool.
146    #[must_use]
147    pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
148        self.tool = Some(tool.into());
149        self
150    }
151
152    /// Sets the decision.
153    #[must_use]
154    pub fn with_decision(mut self, decision: impl Into<String>) -> Self {
155        self.decision = Some(decision.into());
156        self
157    }
158
159    /// Sets the outcome.
160    #[must_use]
161    pub fn with_outcome(mut self, outcome: impl Into<String>) -> Self {
162        self.outcome = Some(outcome.into());
163        self
164    }
165
166    /// Sets how the answer was given, and from which channel or device.
167    #[must_use]
168    pub fn with_how(mut self, how: impl Into<String>, channel: Option<&str>) -> Self {
169        self.how = Some(how.into());
170        self.channel = channel.map(str::to_string);
171        self
172    }
173
174    /// Sets the chat channel or device it was given from, when how is not known.
175    #[must_use]
176    pub fn with_channel(mut self, channel: impl Into<String>) -> Self {
177        self.channel = Some(channel.into());
178        self
179    }
180
181    /// Sets the surface it was given on, such as `tray` for an answer from the desktop tray
182    /// (spec 3.3 §11).
183    #[must_use]
184    pub fn with_surface(mut self, surface: impl Into<String>) -> Self {
185        self.surface = Some(surface.into());
186        self
187    }
188
189    /// Sets what a kernel record did.
190    #[must_use]
191    pub fn with_kernel_action(mut self, action: impl Into<String>) -> Self {
192        self.kernel_action = Some(action.into());
193        self
194    }
195
196    /// Sets what it acted on.
197    #[must_use]
198    pub fn with_target(mut self, target: impl Into<String>) -> Self {
199        self.target = Some(target.into());
200        self
201    }
202
203    /// Sets the item it acted on, as the person knows it (spec 3.3 §8).
204    ///
205    /// # Example
206    ///
207    /// ```rust
208    /// use adk_kernel::control::RecordLine;
209    ///
210    /// let denied = RecordLine::new(7, chrono::Utc::now(), "surface.decide")
211    ///     .with_tool("verb_snooze")
212    ///     .with_decision("rejected")
213    ///     .with_title("News digest");
214    /// assert_eq!(serde_json::to_value(&denied).unwrap()["title"], "News digest");
215    /// ```
216    #[must_use]
217    pub fn with_title(mut self, title: impl Into<String>) -> Self {
218        self.title = Some(title.into());
219        self
220    }
221
222    /// Sets who publishes the called tool, and what decided the call (spec 3.3 §7.1, §11).
223    ///
224    /// # Example
225    ///
226    /// ```rust
227    /// use adk_kernel::control::RecordLine;
228    ///
229    /// let refused = RecordLine::new(8, chrono::Utc::now(), "verb_snooze")
230    ///     .with_tool("verb_snooze")
231    ///     .with_decision("denied")
232    ///     .with_call("verbs:adk-rust", Some("confirmation"));
233    /// let wire = serde_json::to_value(&refused).unwrap();
234    /// assert_eq!(wire["toolSource"], "verbs:adk-rust");
235    /// assert_eq!(wire["policyRef"], "confirmation");
236    /// ```
237    #[must_use]
238    pub fn with_call(mut self, tool_source: impl Into<String>, policy_ref: Option<&str>) -> Self {
239        self.tool_source = Some(tool_source.into());
240        self.policy_ref = policy_ref.map(str::to_string);
241        self
242    }
243}
244
245/// The answer of the record check (spec 3.3 §5.1 "Every action is on record"): whether the
246/// log verifies against its signed checkpoints, how many entries it holds, and the
247/// verifier's own report.
248///
249/// # Example
250///
251/// ```rust
252/// use adk_kernel::control::RecordCheck;
253///
254/// let check = RecordCheck::new(true, 1284, chrono::Utc::now());
255/// assert_eq!(serde_json::to_value(&check).unwrap()["entries"], 1284);
256/// ```
257#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258#[serde(rename_all = "camelCase")]
259#[non_exhaustive]
260pub struct RecordCheck {
261    /// Every entry is covered by a signed checkpoint and nothing was changed or deleted.
262    pub valid: bool,
263    /// How many entries the log holds.
264    pub entries: u64,
265    /// When the check ran.
266    pub checked_at: DateTime<Utc>,
267    /// Why the check failed, in the verifier's words.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub problem: Option<String>,
270    /// The verifier's report, as `adk-rust audit verify --json` prints it.
271    #[serde(default, skip_serializing_if = "Value::is_null")]
272    pub report: Value,
273}
274
275impl RecordCheck {
276    /// A check that found the log `valid` with `entries` entries at `checked_at`.
277    pub fn new(valid: bool, entries: u64, checked_at: DateTime<Utc>) -> Self {
278        Self { valid, entries, checked_at, problem: None, report: Value::Null }
279    }
280
281    /// Sets why it failed.
282    #[must_use]
283    pub fn with_problem(mut self, problem: impl Into<String>) -> Self {
284        self.problem = Some(problem.into());
285        self
286    }
287
288    /// Sets the verifier's report.
289    #[must_use]
290    pub fn with_report(mut self, report: Value) -> Self {
291        self.report = report;
292        self
293    }
294}
295
296/// What the host of the kernel's audit log gives the control plane to read and check it
297/// (spec 3.3 §10 K5).
298///
299/// # Example
300///
301/// ```rust
302/// use adk_kernel::control::{RecordBook, RecordCheck, RecordLine};
303///
304/// struct Empty;
305///
306/// #[async_trait::async_trait]
307/// impl RecordBook for Empty {
308///     async fn recent(&self, _limit: usize) -> adk_kernel::Result<Vec<RecordLine>> { Ok(vec![]) }
309///     async fn check(&self) -> adk_kernel::Result<RecordCheck> { Ok(RecordCheck::new(true, 0, chrono::Utc::now())) }
310/// }
311/// ```
312#[async_trait]
313pub trait RecordBook: Send + Sync {
314    /// The latest `limit` actions, newest first.
315    ///
316    /// # Errors
317    ///
318    /// The log store's error.
319    async fn recent(&self, limit: usize) -> Result<Vec<RecordLine>>;
320
321    /// Verifies the whole log against its signed checkpoints.
322    ///
323    /// # Errors
324    ///
325    /// The log store's error; a log that does not verify is a [`RecordCheck`] with `valid`
326    /// unset, not an error.
327    async fn check(&self) -> Result<RecordCheck>;
328}
329
330/// `GET /kernel/record` query (spec 3.3 §10 K5).
331#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
332#[serde(rename_all = "camelCase")]
333pub struct RecordQuery {
334    /// At most this many lines; 20 when absent, at most 500.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub limit: Option<usize>,
337}
338
339/// `GET /kernel/record` answer (spec 3.3 §10 K5).
340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
341#[serde(rename_all = "camelCase")]
342pub struct RecordResponse {
343    /// The latest actions, newest first.
344    pub lines: Vec<RecordLine>,
345}
346
347type Backend = State<Arc<dyn ControlBackend>>;
348
349/// The routes, relative to `/api`, over the backend in their state.
350pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
351    Router::new().route(paths::RECORD, get(recent)).route(paths::RECORD_CHECK, get(check))
352}
353
354/// The record book of `backend`, or a `Config` error naming why there is none.
355fn book_of(backend: &dyn ControlBackend) -> Result<Arc<dyn RecordBook>> {
356    backend.kernel().and_then(|kernel| kernel.config().control.record.clone()).ok_or_else(|| {
357        KernelError::Config {
358            reason: "this kernel shows no record: set ControlPlaneConfig::with_record, as \
359                     `adk-rust up` does over its signed audit log"
360                .into(),
361        }
362    })
363}
364
365async fn recent(
366    State(backend): Backend,
367    caller: Caller,
368    Query(query): Query<RecordQuery>,
369) -> Result<Json<RecordResponse>> {
370    caller.require_operator("read the record")?;
371    let limit = query.limit.unwrap_or(20).clamp(1, 500);
372    Ok(Json(RecordResponse { lines: book_of(backend.as_ref())?.recent(limit).await? }))
373}
374
375async fn check(State(backend): Backend, caller: Caller) -> Result<Json<RecordCheck>> {
376    caller.require_operator("check the record")?;
377    Ok(Json(book_of(backend.as_ref())?.check().await?))
378}