Skip to main content

adk_kernel/
bus.rs

1//! The event bus (spec 3.2 §7.6).
2//!
3//! Every state change in the kernel is a [`KernelEvent`]: process transitions from the
4//! worker's S1 hooks (never polled), wakes, holds and decisions, rule hits, spend,
5//! governance and health. [`EventBus`] numbers each one with a cursor and delivers it to
6//! subscribers and [`EventSink`]s. The bus is bounded per sink; a slow sink drops `Health`
7//! first and never blocks a process. A reconnecting surface catches up by cursor
8//! ([`EventBus::subscribe_after`]) rather than by holding a subscription open.
9//!
10//! The receivers are the control plane's SSE stream (`GET /kernel/events`, a subscriber),
11//! the signed audit log ([`AuditSink`]) for the events that are audit records (§9.3), and
12//! outbound webhooks (`WebhookSink`, feature `webhooks`): each event an [`EventFilter`]
13//! selects, signed with Standard Webhooks signatures as the webhook ingress verifies them.
14//! `Driver` events come from the MCP manager's status channel (spec 3.2 §10 T1), never
15//! polled. With a ledger (feature `proc`), the kernel's ledger sink writes a content-free
16//! row for every event but `Health` (spec 3.2 §7.10).
17
18use std::collections::{BTreeSet, VecDeque};
19use std::fmt;
20use std::str::FromStr;
21use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
22use std::sync::{Arc, Mutex, PoisonError};
23
24use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
25use adk_core::{RunState, SpendKey, SubjectRef, ToolConfirmationDecision, ToolConfirmationRequest};
26use async_trait::async_trait;
27use chrono::{DateTime, Utc};
28use futures::stream::{self, BoxStream, StreamExt};
29use serde::{Deserialize, Serialize};
30use serde_json::json;
31use tokio::sync::{Notify, broadcast};
32
33use crate::agenda::AgendaState;
34use crate::error::{KernelError, Result};
35use crate::kernel::KernelHealth;
36use crate::partition::PartitionId;
37use crate::review::ReviewReport;
38use crate::wake::WakeOutcome;
39
40#[cfg(feature = "webhooks")]
41mod webhook;
42#[cfg(feature = "webhooks")]
43pub use webhook::WebhookSink;
44
45/// How many events a subscriber may fall behind before it skips ahead.
46pub const DEFAULT_EVENT_CAPACITY: usize = 1024;
47
48/// A change in the kernel (spec 3.2 §7.6).
49///
50/// # Example
51///
52/// ```rust
53/// use adk_core::RunState;
54/// use adk_kernel::KernelEvent;
55///
56/// let event = KernelEvent::Process {
57///     pid: "run-1".into(),
58///     from: RunState::Running,
59///     to: RunState::Waiting,
60///     reason: Some("suspended".into()),
61/// };
62/// let json = serde_json::to_value(&event).unwrap();
63/// assert_eq!(json["type"], "process");
64/// assert_eq!(json["to"], "waiting");
65/// assert_eq!(event.name(), "process");
66/// ```
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
69#[non_exhaustive]
70pub enum KernelEvent {
71    /// A process changed state.
72    Process {
73        /// The process.
74        pid: String,
75        /// The state it left.
76        from: RunState,
77        /// The state it entered.
78        to: RunState,
79        /// Why, such as a park reason.
80        #[serde(default, skip_serializing_if = "Option::is_none")]
81        reason: Option<String>,
82    },
83    /// A wake event was routed; one per process it concerned.
84    Wake {
85        /// The process it woke or started, `outcome`'s process; `None` when it matched
86        /// nothing.
87        #[serde(default, skip_serializing_if = "Option::is_none")]
88        pid: Option<String>,
89        /// The wake source.
90        source: String,
91        /// The event's idempotency key.
92        key: String,
93        /// What the wake did to `pid`: woke it, spawned it, found its key already used, or
94        /// expired its wake set; `None` when it matched nothing.
95        #[serde(default, skip_serializing_if = "Option::is_none")]
96        outcome: Option<WakeOutcome>,
97    },
98    /// A process holds a tool call for approval.
99    Held {
100        /// The process.
101        pid: String,
102        /// The held call.
103        request: ToolConfirmationRequest,
104    },
105    /// A held call was decided.
106    Decided {
107        /// The process.
108        pid: String,
109        /// The call's fingerprint.
110        fingerprint: String,
111        /// The decision.
112        decision: ToolConfirmationDecision,
113        /// Who decided.
114        by: SubjectRef,
115    },
116    /// A standing rule allowed a call.
117    RuleHit {
118        /// The process.
119        pid: String,
120        /// The rule.
121        rule_id: String,
122    },
123    /// Spend was committed.
124    Spend {
125        /// The partition charged.
126        partition: PartitionId,
127        /// The spend key.
128        key: SpendKey,
129        /// How much.
130        delta: SpendDelta,
131    },
132    /// An agenda item changed state (spec 3.2 §7.5); a proposal the policy refused is
133    /// published `proposed` → `rejected` with the reason, though it was never stored.
134    Agenda {
135        /// The item.
136        item: String,
137        /// The state it left.
138        from: AgendaState,
139        /// The state it entered.
140        to: AgendaState,
141        /// Why, such as the limit a refused proposal would exceed.
142        #[serde(default, skip_serializing_if = "Option::is_none")]
143        reason: Option<String>,
144    },
145    /// The maintenance tick's daily review: what is older than the partition's review
146    /// period (spec 3.2 §7.4, §9.1).
147    Review(ReviewReport),
148    /// A driver's state changed: a status of its MCP server, or `needsReapproval` once a
149    /// tool's declaration differs from the approved one (spec 3.2 §7.6, §7.7).
150    Driver {
151        /// The driver.
152        id: String,
153        /// The state it entered.
154        state: crate::drivers::DriverState,
155        /// Why, such as the tools that changed.
156        #[serde(default, skip_serializing_if = "Option::is_none")]
157        reason: Option<String>,
158    },
159    /// A baseline pass recorded an observation (spec 3.2 §7.10, feature `proc-baselines`).
160    Observation {
161        /// The observation.
162        id: String,
163        /// Its partition.
164        partition: PartitionId,
165    },
166    /// An agent a person adds was suggested, added, changed, paused, resumed, removed,
167    /// refused, built or could not be built (spec 3.3 §5.7, §10 K7).
168    Agent {
169        /// The agent's id.
170        id: String,
171        /// What happened.
172        change: crate::agents::AgentChange,
173        /// Why, such as the fields a change touched or the reason it cannot start.
174        #[serde(default, skip_serializing_if = "Option::is_none")]
175        reason: Option<String>,
176    },
177    /// A background sub-agent's status changed: it started, ran, waits for a person's
178    /// decision, finished, failed or was cancelled. Subscribe a `WebhookSink` to
179    /// [`EventKind::Subagent`] for a signed webhook per change.
180    Subagent {
181        /// The run the change concerns: the sub-agent's latest.
182        pid: String,
183        /// The sub-agent's id.
184        id: String,
185        /// The name its parent knows it by.
186        name: String,
187        /// The run of the parent that started it, when the parent's turn was a process.
188        #[serde(default, skip_serializing_if = "Option::is_none")]
189        parent: Option<String>,
190        /// Its status.
191        status: adk_core::SubagentStatus,
192    },
193    /// The kill switch changed.
194    Governance {
195        /// Whether execution is frozen.
196        frozen: bool,
197        /// The freeze reason.
198        #[serde(default, skip_serializing_if = "Option::is_none")]
199        reason: Option<String>,
200    },
201    /// A health report; the first event a slow sink drops.
202    Health(KernelHealth),
203}
204
205impl KernelEvent {
206    /// The event's type, as its `type` field serializes it.
207    pub fn name(&self) -> &'static str {
208        self.kind().as_str()
209    }
210
211    /// The event's kind, which an [`EventFilter`] selects on.
212    ///
213    /// # Example
214    ///
215    /// ```rust
216    /// use adk_kernel::{EventKind, KernelEvent};
217    ///
218    /// let event = KernelEvent::Governance { frozen: true, reason: None };
219    /// assert_eq!(event.kind(), EventKind::Governance);
220    /// ```
221    pub fn kind(&self) -> EventKind {
222        match self {
223            Self::Process { .. } => EventKind::Process,
224            Self::Wake { .. } => EventKind::Wake,
225            Self::Held { .. } => EventKind::Held,
226            Self::Decided { .. } => EventKind::Decided,
227            Self::RuleHit { .. } => EventKind::RuleHit,
228            Self::Spend { .. } => EventKind::Spend,
229            Self::Agenda { .. } => EventKind::Agenda,
230            Self::Review(_) => EventKind::Review,
231            Self::Driver { .. } => EventKind::Driver,
232            Self::Observation { .. } => EventKind::Observation,
233            Self::Agent { .. } => EventKind::Agent,
234            Self::Subagent { .. } => EventKind::Subagent,
235            Self::Governance { .. } => EventKind::Governance,
236            Self::Health(_) => EventKind::Health,
237        }
238    }
239}
240
241/// The kind of a [`KernelEvent`], named as its `type` field serializes it (spec 3.2 §7.6).
242///
243/// # Example
244///
245/// ```rust
246/// use adk_kernel::EventKind;
247///
248/// let kind: EventKind = "ruleHit".parse().unwrap();
249/// assert_eq!(kind, EventKind::RuleHit);
250/// assert_eq!(kind.to_string(), "ruleHit");
251/// assert!("rule_hit".parse::<EventKind>().is_err());
252/// ```
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255#[non_exhaustive]
256pub enum EventKind {
257    /// [`KernelEvent::Process`].
258    Process,
259    /// [`KernelEvent::Wake`].
260    Wake,
261    /// [`KernelEvent::Held`].
262    Held,
263    /// [`KernelEvent::Decided`].
264    Decided,
265    /// [`KernelEvent::RuleHit`].
266    RuleHit,
267    /// [`KernelEvent::Spend`].
268    Spend,
269    /// [`KernelEvent::Agenda`].
270    Agenda,
271    /// [`KernelEvent::Review`].
272    Review,
273    /// [`KernelEvent::Driver`].
274    Driver,
275    /// [`KernelEvent::Observation`].
276    Observation,
277    /// [`KernelEvent::Agent`].
278    Agent,
279    /// [`KernelEvent::Subagent`].
280    Subagent,
281    /// [`KernelEvent::Governance`].
282    Governance,
283    /// [`KernelEvent::Health`].
284    Health,
285}
286
287impl EventKind {
288    /// Every kind, in declaration order.
289    pub const ALL: [EventKind; 14] = [
290        Self::Process,
291        Self::Wake,
292        Self::Held,
293        Self::Decided,
294        Self::RuleHit,
295        Self::Spend,
296        Self::Agenda,
297        Self::Review,
298        Self::Driver,
299        Self::Observation,
300        Self::Agent,
301        Self::Subagent,
302        Self::Governance,
303        Self::Health,
304    ];
305
306    /// The kind's name, as a [`KernelEvent`]'s `type` field serializes it.
307    pub fn as_str(self) -> &'static str {
308        match self {
309            Self::Process => "process",
310            Self::Wake => "wake",
311            Self::Held => "held",
312            Self::Decided => "decided",
313            Self::RuleHit => "ruleHit",
314            Self::Spend => "spend",
315            Self::Agenda => "agenda",
316            Self::Review => "review",
317            Self::Driver => "driver",
318            Self::Observation => "observation",
319            Self::Agent => "agent",
320            Self::Subagent => "subagent",
321            Self::Governance => "governance",
322            Self::Health => "health",
323        }
324    }
325}
326
327impl fmt::Display for EventKind {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.write_str(self.as_str())
330    }
331}
332
333impl FromStr for EventKind {
334    type Err = KernelError;
335
336    fn from_str(text: &str) -> Result<Self> {
337        Self::ALL.into_iter().find(|kind| kind.as_str() == text.trim()).ok_or_else(|| {
338            KernelError::Config {
339                reason: format!(
340                    "unknown kernel event type `{text}`; use one of {}",
341                    Self::ALL.map(Self::as_str).join(", ")
342                ),
343            }
344        })
345    }
346}
347
348/// Which [`KernelEvent`]s a sink delivers, by kind (spec 3.2 §7.6).
349///
350/// The default selects every kind but [`EventKind::Health`], the periodic report a
351/// receiver outside the kernel rarely needs and the first event a slow sink drops.
352///
353/// # Example
354///
355/// ```rust
356/// use adk_kernel::{EventFilter, EventKind, KernelEvent};
357///
358/// let frozen = KernelEvent::Governance { frozen: true, reason: None };
359/// assert!(EventFilter::default().matches(&frozen));
360/// assert!(!EventFilter::default().selects(EventKind::Health));
361/// assert!(EventFilter::all().selects(EventKind::Health));
362///
363/// let decisions = EventFilter::only([EventKind::Held, EventKind::Decided]);
364/// assert!(!decisions.matches(&frozen));
365/// assert_eq!(EventFilter::parse(["held", "decided"]).unwrap(), decisions);
366/// ```
367#[derive(Debug, Clone, PartialEq, Eq)]
368pub struct EventFilter {
369    kinds: BTreeSet<EventKind>,
370}
371
372impl Default for EventFilter {
373    fn default() -> Self {
374        Self::all().without(EventKind::Health)
375    }
376}
377
378impl EventFilter {
379    /// Every kind, `Health` included.
380    pub fn all() -> Self {
381        Self::only(EventKind::ALL)
382    }
383
384    /// Only `kinds`.
385    pub fn only(kinds: impl IntoIterator<Item = EventKind>) -> Self {
386        Self { kinds: kinds.into_iter().collect() }
387    }
388
389    /// Only the kinds named in `names`, as [`EventKind`] parses them.
390    ///
391    /// # Errors
392    ///
393    /// Returns [`KernelError::Config`] naming the first unknown type, so a misspelt name
394    /// is refused rather than silently selecting nothing.
395    pub fn parse<S: AsRef<str>>(names: impl IntoIterator<Item = S>) -> Result<Self> {
396        names
397            .into_iter()
398            .map(|name| name.as_ref().parse())
399            .collect::<Result<Vec<EventKind>>>()
400            .map(Self::only)
401    }
402
403    /// These kinds without `kind`.
404    #[must_use]
405    pub fn without(mut self, kind: EventKind) -> Self {
406        self.kinds.remove(&kind);
407        self
408    }
409
410    /// Whether the filter selects `kind`.
411    pub fn selects(&self, kind: EventKind) -> bool {
412        self.kinds.contains(&kind)
413    }
414
415    /// Whether the filter selects `event`.
416    pub fn matches(&self, event: &KernelEvent) -> bool {
417        self.selects(event.kind())
418    }
419
420    /// The selected kinds, in declaration order.
421    pub fn kinds(&self) -> impl Iterator<Item = EventKind> + '_ {
422        self.kinds.iter().copied()
423    }
424}
425
426/// Usage a process committed (spec 3.2 §7.6): the cost in micro-USD as `SpendLedger`
427/// counts it, the model calls and tokens a run budget counts, and the usage per
428/// [`UsageUnit`](adk_core::UsageUnit).
429///
430/// The kernel adds deltas to its daily totals ([`ProcessStore::add_spend`](crate::ProcessStore::add_spend)),
431/// which admission reads against [`Quotas`](crate::Quotas) and the daily proactive budget.
432///
433/// # Example
434///
435/// ```rust
436/// use adk_core::{UsageUnit, UsageVector};
437/// use adk_kernel::SpendDelta;
438///
439/// let delta = SpendDelta::new(12_500)
440///     .with_model_calls(2)
441///     .with_total_tokens(1_800)
442///     .with_units(UsageVector::new().with(UsageUnit::Images, 1));
443/// assert_eq!(delta.micro_usd, 12_500);
444/// assert_eq!(delta.units.get(UsageUnit::Images), 1);
445/// assert!(!delta.is_empty());
446/// assert!(SpendDelta::default().is_empty());
447/// ```
448#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "camelCase")]
450#[non_exhaustive]
451pub struct SpendDelta {
452    /// The cost, in micro-USD.
453    pub micro_usd: u64,
454    /// Model calls started.
455    #[serde(default, skip_serializing_if = "is_zero")]
456    pub model_calls: u64,
457    /// Input plus output tokens, as a run budget counts them.
458    #[serde(default, skip_serializing_if = "is_zero")]
459    pub total_tokens: u64,
460    /// Usage per unit.
461    #[serde(default, skip_serializing_if = "adk_core::UsageVector::is_empty")]
462    pub units: adk_core::UsageVector,
463}
464
465fn is_zero(value: &u64) -> bool {
466    *value == 0
467}
468
469impl SpendDelta {
470    /// A delta of `micro_usd`.
471    pub fn new(micro_usd: u64) -> Self {
472        Self { micro_usd, ..Self::default() }
473    }
474
475    /// Sets the model calls.
476    #[must_use]
477    pub fn with_model_calls(mut self, model_calls: u64) -> Self {
478        self.model_calls = model_calls;
479        self
480    }
481
482    /// Sets the total tokens.
483    #[must_use]
484    pub fn with_total_tokens(mut self, total_tokens: u64) -> Self {
485        self.total_tokens = total_tokens;
486        self
487    }
488
489    /// Sets the usage per unit.
490    #[must_use]
491    pub fn with_units(mut self, units: adk_core::UsageVector) -> Self {
492        self.units = units;
493        self
494    }
495
496    /// Returns `true` when the delta adds nothing.
497    pub fn is_empty(&self) -> bool {
498        self.micro_usd == 0
499            && self.model_calls == 0
500            && self.total_tokens == 0
501            && self.units.is_empty()
502    }
503}
504
505/// A numbered [`KernelEvent`] as the bus delivers it (spec 3.2 §7.6).
506///
507/// `cursor` increases by one per event on one kernel; a surface reconnects with the last
508/// cursor it saw.
509#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
510#[serde(rename_all = "camelCase")]
511#[non_exhaustive]
512pub struct EventRecord {
513    /// The event's position on the bus.
514    pub cursor: u64,
515    /// When the bus published it.
516    pub at: DateTime<Utc>,
517    /// The event.
518    pub event: KernelEvent,
519}
520
521/// A destination for kernel events (spec 3.2 §7.6): the SSE stream, a channel notifier,
522/// an outbound webhook, the audit log.
523///
524/// # Example
525///
526/// ```rust
527/// use adk_kernel::{EventSink, KernelEvent};
528/// use async_trait::async_trait;
529///
530/// struct Log;
531///
532/// #[async_trait]
533/// impl EventSink for Log {
534///     async fn emit(&self, event: &KernelEvent) -> adk_kernel::Result<()> {
535///         tracing::info!(event.kind = event.name(), "kernel event");
536///         Ok(())
537///     }
538/// }
539/// ```
540#[async_trait]
541pub trait EventSink: Send + Sync {
542    /// Delivers `event`.
543    ///
544    /// # Errors
545    ///
546    /// Returns the sink's delivery error; the bus logs it and carries on.
547    async fn emit(&self, event: &KernelEvent) -> Result<()>;
548
549    /// Delivers `record`, the event with its cursor and time; the bus calls this. The
550    /// default delivers the event alone through [`emit`](Self::emit); a sink whose receiver
551    /// orders or deduplicates by cursor, such as an outbound webhook, overrides it.
552    ///
553    /// # Errors
554    ///
555    /// Returns the sink's delivery error; the bus logs it and carries on.
556    async fn emit_record(&self, record: &EventRecord) -> Result<()> {
557        self.emit(&record.event).await
558    }
559}
560
561/// The kernel's event bus (spec 3.2 §7.6).
562///
563/// Cloning shares the bus. Each event gets the next cursor and goes to every subscriber and
564/// sink:
565///
566/// | Receiver | Delivery | When it falls behind |
567/// |---|---|---|
568/// | [`EventSubscriber`] (the control plane's SSE stream) | A broadcast of `capacity` events | Skips to the oldest event still held |
569/// | [`EventSink`] | Its own queue of `capacity` events, drained in order by a task on the Tokio runtime through [`EventSink::emit_record`] | Drops a queued `Health` first, then its oldest event; [`publish`](Self::publish) never waits |
570///
571/// The bus keeps its last `capacity` events, so [`subscribe_after`](Self::subscribe_after)
572/// replays what a reconnecting surface missed before the live events, with no gap and no
573/// repeat.
574///
575/// # Example
576///
577/// ```rust
578/// use adk_kernel::{EventBus, KernelEvent};
579///
580/// # #[tokio::main(flavor = "current_thread")]
581/// # async fn main() {
582/// let bus = EventBus::new(16);
583/// let mut subscriber = bus.subscribe();
584/// let record = bus.publish(KernelEvent::Governance { frozen: true, reason: Some("incident".into()) });
585/// assert_eq!(subscriber.recv().await.unwrap(), record);
586/// # }
587/// ```
588#[derive(Clone)]
589pub struct EventBus {
590    inner: Arc<BusInner>,
591}
592
593struct BusInner {
594    sender: broadcast::Sender<EventRecord>,
595    capacity: usize,
596    /// The next cursor and the recent events; held across the broadcast so a replay and a
597    /// live subscription meet exactly.
598    log: Mutex<BusLog>,
599    sinks: Mutex<Vec<Arc<SinkQueue>>>,
600}
601
602struct BusLog {
603    next: u64,
604    history: VecDeque<EventRecord>,
605}
606
607impl Drop for BusInner {
608    fn drop(&mut self) {
609        for sink in self.sinks.get_mut().unwrap_or_else(PoisonError::into_inner).iter() {
610            sink.close();
611        }
612    }
613}
614
615/// One sink's bounded queue and the task that drains it.
616struct SinkQueue {
617    sink: Arc<dyn EventSink>,
618    capacity: usize,
619    queue: Mutex<VecDeque<EventRecord>>,
620    ready: Notify,
621    started: AtomicBool,
622    closed: AtomicBool,
623    dropped: AtomicU64,
624}
625
626impl SinkQueue {
627    /// Queues `event`, shedding a `Health` event first and then the oldest when full, and
628    /// starts the drain task when a runtime is available.
629    fn push(self: &Arc<Self>, record: EventRecord) {
630        {
631            let mut queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner);
632            if queue.len() >= self.capacity {
633                let dropped = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
634                if matches!(record.event, KernelEvent::Health(_)) {
635                    tracing::warn!(sink.dropped = dropped, "event sink is behind; health dropped");
636                    return;
637                }
638                let health =
639                    queue.iter().position(|queued| matches!(queued.event, KernelEvent::Health(_)));
640                let shed = match health {
641                    Some(index) => queue.remove(index),
642                    None => queue.pop_front(),
643                };
644                let shed = shed.as_ref().map_or("none", |shed| shed.event.name());
645                tracing::warn!(
646                    event.dropped = shed,
647                    sink.dropped = dropped,
648                    "event sink is behind; event dropped"
649                );
650            }
651            queue.push_back(record);
652        }
653        self.ready.notify_one();
654        self.start();
655    }
656
657    fn start(self: &Arc<Self>) {
658        if self.started.load(Ordering::Acquire) {
659            return;
660        }
661        let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
662        if self.started.swap(true, Ordering::AcqRel) {
663            return;
664        }
665        let queue = Arc::clone(self);
666        runtime.spawn(async move { queue.drain().await });
667    }
668
669    async fn drain(&self) {
670        loop {
671            let next = self.queue.lock().unwrap_or_else(PoisonError::into_inner).pop_front();
672            match next {
673                Some(record) => {
674                    if let Err(error) = self.sink.emit_record(&record).await {
675                        tracing::warn!(event.kind = record.event.name(), error = %error, "event sink failed");
676                    }
677                }
678                None if self.closed.load(Ordering::Acquire) => return,
679                None => self.ready.notified().await,
680            }
681        }
682    }
683
684    fn close(&self) {
685        self.closed.store(true, Ordering::Release);
686        self.ready.notify_one();
687    }
688}
689
690impl fmt::Debug for EventBus {
691    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692        f.debug_struct("EventBus")
693            .field("subscribers", &self.inner.sender.receiver_count())
694            .finish_non_exhaustive()
695    }
696}
697
698impl Default for EventBus {
699    fn default() -> Self {
700        Self::new(DEFAULT_EVENT_CAPACITY)
701    }
702}
703
704impl EventBus {
705    /// A bus whose subscribers may fall `capacity` events behind.
706    pub fn new(capacity: usize) -> Self {
707        let capacity = capacity.max(1);
708        let (sender, _) = broadcast::channel(capacity);
709        Self {
710            inner: Arc::new(BusInner {
711                sender,
712                capacity,
713                log: Mutex::new(BusLog { next: 1, history: VecDeque::with_capacity(capacity) }),
714                sinks: Mutex::new(Vec::new()),
715            }),
716        }
717    }
718
719    /// Adds a sink that receives every later event, in order, through its own queue of the
720    /// bus's capacity. The queue drains on the Tokio runtime of the first publish that finds
721    /// one.
722    pub fn add_sink(&self, sink: Arc<dyn EventSink>) {
723        let queue = Arc::new(SinkQueue {
724            sink,
725            capacity: self.inner.capacity,
726            queue: Mutex::new(VecDeque::new()),
727            ready: Notify::new(),
728            started: AtomicBool::new(false),
729            closed: AtomicBool::new(false),
730            dropped: AtomicU64::new(0),
731        });
732        queue.start();
733        self.inner.sinks.lock().unwrap_or_else(PoisonError::into_inner).push(queue);
734    }
735
736    /// Numbers `event`, delivers it to subscribers and sinks, and returns its record. Never
737    /// blocks on a slow sink.
738    pub fn publish(&self, event: KernelEvent) -> EventRecord {
739        let record = {
740            let mut log = self.inner.log.lock().unwrap_or_else(PoisonError::into_inner);
741            let record = EventRecord { cursor: log.next, at: Utc::now(), event };
742            log.next += 1;
743            if log.history.len() == self.inner.capacity {
744                log.history.pop_front();
745            }
746            log.history.push_back(record.clone());
747            // A send fails only when no one subscribes, which drops nothing anyone awaits.
748            let _ = self.inner.sender.send(record.clone());
749            record
750        };
751        let sinks = self.inner.sinks.lock().unwrap_or_else(PoisonError::into_inner).clone();
752        for sink in sinks {
753            sink.push(record.clone());
754        }
755        record
756    }
757
758    /// Subscribes to every event published from now on.
759    pub fn subscribe(&self) -> EventSubscriber {
760        EventSubscriber { backlog: VecDeque::new(), receiver: self.inner.sender.subscribe() }
761    }
762
763    /// Subscribes from just after `cursor`: the held events after it, then the live ones,
764    /// with no gap and no repeat (spec 3.2 §7.6).
765    ///
766    /// The replay comes from the bus's own history of its last `capacity` events, not from
767    /// the stores. A surface that fell further behind gets the oldest held event onward and
768    /// re-reads the process table (`ProcessTable::ps`, `GET /api/kernel/processes`) for the
769    /// state it missed. A cursor the bus never issued, such as one from before a kernel
770    /// restart, replays every held event.
771    ///
772    /// # Example
773    ///
774    /// ```rust
775    /// use adk_kernel::{EventBus, KernelEvent};
776    ///
777    /// # #[tokio::main(flavor = "current_thread")]
778    /// # async fn main() -> adk_kernel::Result<()> {
779    /// let bus = EventBus::new(16);
780    /// let seen = bus.publish(KernelEvent::Governance { frozen: true, reason: None });
781    /// let missed = bus.publish(KernelEvent::Governance { frozen: false, reason: None });
782    /// let mut subscriber = bus.subscribe_after(seen.cursor).await?;
783    /// assert_eq!(subscriber.recv().await.unwrap(), missed);
784    /// # Ok(())
785    /// # }
786    /// ```
787    ///
788    /// # Errors
789    ///
790    /// None today; a store-backed replay returns its store error.
791    pub async fn subscribe_after(&self, cursor: u64) -> Result<EventSubscriber> {
792        let log = self.inner.log.lock().unwrap_or_else(PoisonError::into_inner);
793        let receiver = self.inner.sender.subscribe();
794        let issued = cursor < log.next;
795        let backlog = log
796            .history
797            .iter()
798            .filter(|record| !issued || record.cursor > cursor)
799            .cloned()
800            .collect();
801        Ok(EventSubscriber { backlog, receiver })
802    }
803}
804
805/// A subscription to the [`EventBus`] (spec 3.2 §7.6).
806#[derive(Debug)]
807pub struct EventSubscriber {
808    /// Replayed events, delivered before the live ones.
809    backlog: VecDeque<EventRecord>,
810    receiver: broadcast::Receiver<EventRecord>,
811}
812
813impl EventSubscriber {
814    /// The next event, or `None` once the bus is gone. A subscriber that fell more than the
815    /// bus's capacity behind skips to the oldest event still held.
816    pub async fn recv(&mut self) -> Option<EventRecord> {
817        if let Some(record) = self.backlog.pop_front() {
818            return Some(record);
819        }
820        loop {
821            match self.receiver.recv().await {
822                Ok(record) => return Some(record),
823                Err(broadcast::error::RecvError::Lagged(skipped)) => {
824                    tracing::warn!(events.skipped = skipped, "event subscriber fell behind");
825                }
826                Err(broadcast::error::RecvError::Closed) => return None,
827            }
828        }
829    }
830
831    /// The subscription as a stream that ends with the bus.
832    pub fn into_stream(self) -> BoxStream<'static, EventRecord> {
833        stream::unfold(self, |mut subscriber| async move {
834            subscriber.recv().await.map(|record| (record, subscriber))
835        })
836        .boxed()
837    }
838}
839
840/// Writes the events that are audit records to the signed audit log (spec 3.2 §7.6, §9.3),
841/// kind `Other(`[`KERNEL_AUDIT_KIND`](crate::audit::KERNEL_AUDIT_KIND)`)` with the
842/// `kernel.*` actions of [`crate::audit`].
843///
844/// | Event | Record |
845/// |---|---|
846/// | [`KernelEvent::Wake`] that concerned a process | [`audit::WAKE`](crate::audit::WAKE) with `source`, `key`, `matchedPid` (woken, deduplicated, expired) or `newPid` and `trigger` (spawned), `deduplicated`, and `expiry` for an expired wake set; the actor is the source as a service |
847/// | Every other event | None: `governance.*` records are written by `freeze_recorded`, and the `kernel.process.*` records by the supervisor, which holds the side-table fields they carry |
848///
849/// A wake that matched nothing writes no record. The trail's failure mode applies: under
850/// `AuditFailureMode::Block` a failed write is an error the bus logs.
851///
852/// # Example
853///
854/// ```rust
855/// use std::sync::Arc;
856/// use adk_core::audit_log::{AuditTrail, InMemoryAuditRecorder};
857/// use adk_kernel::{AuditSink, EventBus};
858///
859/// let bus = EventBus::default();
860/// bus.add_sink(Arc::new(AuditSink::new(AuditTrail::new(Arc::new(InMemoryAuditRecorder::new())))));
861/// ```
862#[derive(Debug, Clone)]
863pub struct AuditSink {
864    trail: AuditTrail,
865}
866
867impl AuditSink {
868    /// A sink writing to `trail`.
869    pub fn new(trail: AuditTrail) -> Self {
870        Self { trail }
871    }
872
873    /// The trail the sink writes to.
874    pub fn trail(&self) -> &AuditTrail {
875        &self.trail
876    }
877}
878
879#[async_trait]
880impl EventSink for AuditSink {
881    async fn emit(&self, event: &KernelEvent) -> Result<()> {
882        let KernelEvent::Wake { source, key, outcome: Some(outcome), .. } = event else {
883            return Ok(());
884        };
885        let mut draft = AuditRecordDraft::new(
886            AuditRecordKind::Other(crate::audit::KERNEL_AUDIT_KIND.to_string()),
887            crate::audit::WAKE,
888        )
889        .actor(AuditActor::subject(SubjectRef::service(source.clone())))
890        .ext("source", json!(source))
891        .ext("key", json!(key))
892        .ext("deduplicated", json!(matches!(outcome, WakeOutcome::Deduplicated { .. })));
893        draft = match outcome {
894            WakeOutcome::Spawned { pid, trigger } => {
895                draft.ext("newPid", json!(pid)).ext("trigger", json!(trigger))
896            }
897            WakeOutcome::Expired { pid, action } => {
898                draft.ext("matchedPid", json!(pid)).ext("expiry", json!(action))
899            }
900            WakeOutcome::Woke { pid } | WakeOutcome::Deduplicated { pid } => {
901                draft.ext("matchedPid", json!(pid))
902            }
903            WakeOutcome::Skipped { pid, trigger } => draft
904                .ext("matchedPid", json!(pid))
905                .ext("trigger", json!(trigger))
906                .ext("overlap", json!("skipped")),
907            WakeOutcome::Coalesced { pid, trigger } => draft
908                .ext("matchedPid", json!(pid))
909                .ext("trigger", json!(trigger))
910                .ext("overlap", json!("coalesced")),
911            WakeOutcome::Missed { trigger } => {
912                draft.ext("trigger", json!(trigger)).ext("missed", json!(true))
913            }
914        };
915        self.trail.record(draft).await?;
916        Ok(())
917    }
918}
919
920/// Publishes the approvals inbox's changes on a kernel's bus (`KernelBuilder::approval_service`):
921/// [`KernelEvent::Held`] when a call is filed, [`KernelEvent::Decided`] when a decision
922/// resolves it. Both carry the call's redacted arguments only, and the fingerprint of the
923/// redacted call, so a `held` and its `decided` share it.
924#[derive(Clone)]
925pub(crate) struct ApprovalEvents(EventBus);
926
927impl ApprovalEvents {
928    pub(crate) fn new(bus: EventBus) -> Self {
929        Self(bus)
930    }
931}
932
933impl fmt::Debug for ApprovalEvents {
934    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935        f.debug_struct("ApprovalEvents").finish_non_exhaustive()
936    }
937}
938
939#[async_trait]
940impl adk_core::ApprovalNotifier for ApprovalEvents {
941    async fn notify(&self, notification: &adk_core::ApprovalNotification) -> adk_core::Result<()> {
942        use adk_core::{ApprovalEventKind, ApprovalState};
943
944        let request = &notification.request;
945        let mut call =
946            ToolConfirmationRequest::new(request.tool_name.clone(), request.args_redacted.clone());
947        call.origin = request.origin.clone();
948        call.acting = request.acting.clone().map(Box::new);
949        let pid = request.run_id.clone().unwrap_or_default();
950        match (notification.kind, &notification.decision) {
951            (ApprovalEventKind::Submitted, _) => {
952                self.0.publish(KernelEvent::Held { pid, request: call });
953            }
954            (ApprovalEventKind::Decided, Some(decision)) if request.state.is_terminal() => {
955                let decision_kind = match request.state {
956                    ApprovalState::Approved => ToolConfirmationDecision::Approve,
957                    ApprovalState::Pending
958                    | ApprovalState::Rejected
959                    | ApprovalState::Responded
960                    | ApprovalState::Expired
961                    | ApprovalState::Cancelled => ToolConfirmationDecision::Deny,
962                };
963                self.0.publish(KernelEvent::Decided {
964                    pid,
965                    fingerprint: call.fingerprint(),
966                    decision: decision_kind,
967                    by: decision.authority().clone(),
968                });
969            }
970            _ => {}
971        }
972        Ok(())
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use std::time::Duration;
979
980    use adk_core::audit_log::InMemoryAuditRecorder;
981    use tokio::sync::Semaphore;
982
983    use super::*;
984    use crate::wake::ExpiryAction;
985
986    fn governance(frozen: bool) -> KernelEvent {
987        KernelEvent::Governance { frozen, reason: None }
988    }
989
990    fn health() -> KernelEvent {
991        KernelEvent::Health(KernelHealth::default())
992    }
993
994    fn wake(outcome: Option<WakeOutcome>) -> KernelEvent {
995        KernelEvent::Wake {
996            pid: outcome.as_ref().and_then(WakeOutcome::pid).map(str::to_string),
997            source: "hook:github".into(),
998            key: "hook:github:msg_1".into(),
999            outcome,
1000        }
1001    }
1002
1003    /// Records every event; each `emit` waits for a permit, so the test decides when the
1004    /// sink catches up.
1005    struct GatedSink {
1006        permits: Semaphore,
1007        seen: Mutex<Vec<KernelEvent>>,
1008    }
1009
1010    #[async_trait]
1011    impl EventSink for GatedSink {
1012        async fn emit(&self, event: &KernelEvent) -> Result<()> {
1013            self.permits.acquire().await.unwrap().forget();
1014            self.seen.lock().unwrap().push(event.clone());
1015            Ok(())
1016        }
1017    }
1018
1019    async fn seen(sink: &GatedSink, count: usize) -> Vec<KernelEvent> {
1020        for _ in 0..500 {
1021            if sink.seen.lock().unwrap().len() >= count {
1022                break;
1023            }
1024            tokio::time::sleep(Duration::from_millis(10)).await;
1025        }
1026        sink.seen.lock().unwrap().clone()
1027    }
1028
1029    #[tokio::test]
1030    async fn a_reconnecting_subscriber_replays_from_its_cursor_without_gap_or_repeat() {
1031        let bus = EventBus::new(8);
1032        let first = bus.publish(governance(true));
1033        let missed = [bus.publish(governance(false)), bus.publish(governance(true))];
1034        let mut subscriber = bus.subscribe_after(first.cursor).await.unwrap();
1035        let live = bus.publish(governance(false));
1036        for expected in missed.iter().chain([&live]) {
1037            assert_eq!(&subscriber.recv().await.unwrap(), expected);
1038        }
1039
1040        let mut current = bus.subscribe_after(live.cursor).await.unwrap();
1041        let next = bus.publish(governance(true));
1042        assert_eq!(current.recv().await.unwrap(), next);
1043    }
1044
1045    #[tokio::test]
1046    async fn a_cursor_from_before_a_restart_replays_everything_held() {
1047        let bus = EventBus::new(2);
1048        bus.publish(governance(true));
1049        let held = [bus.publish(governance(false)), bus.publish(governance(true))];
1050        let mut subscriber = bus.subscribe_after(9_999).await.unwrap();
1051        for expected in &held {
1052            assert_eq!(&subscriber.recv().await.unwrap(), expected);
1053        }
1054        let mut lagging = bus.subscribe_after(0).await.unwrap();
1055        assert_eq!(lagging.recv().await.unwrap(), held[0], "only the last two are held");
1056    }
1057
1058    #[tokio::test]
1059    async fn sinks_receive_every_event_in_order() {
1060        let bus = EventBus::new(16);
1061        let sink = Arc::new(GatedSink { permits: Semaphore::new(100), seen: Mutex::default() });
1062        bus.add_sink(sink.clone());
1063        let events = [governance(true), wake(None), governance(false)];
1064        for event in &events {
1065            bus.publish(event.clone());
1066        }
1067        assert_eq!(seen(&sink, 3).await, events);
1068    }
1069
1070    #[tokio::test]
1071    async fn a_slow_sink_drops_health_first_and_never_blocks_the_publisher() {
1072        let bus = EventBus::new(3);
1073        let sink = Arc::new(GatedSink { permits: Semaphore::new(0), seen: Mutex::default() });
1074        bus.add_sink(sink.clone());
1075        // The drain task takes the first event and waits on the gate; three more fill the queue.
1076        bus.publish(governance(true));
1077        tokio::time::sleep(Duration::from_millis(50)).await;
1078        bus.publish(health());
1079        bus.publish(governance(false));
1080        bus.publish(health());
1081        // Full: a new health event is dropped, then each other event sheds a queued health.
1082        bus.publish(health());
1083        bus.publish(wake(None));
1084        bus.publish(governance(true));
1085        sink.permits.add_permits(100);
1086        assert_eq!(
1087            seen(&sink, 4).await,
1088            [governance(true), governance(false), wake(None), governance(true)]
1089        );
1090        // With no health left to shed, the oldest queued event goes.
1091        let bus = EventBus::new(1);
1092        let sink = Arc::new(GatedSink { permits: Semaphore::new(0), seen: Mutex::default() });
1093        bus.add_sink(sink.clone());
1094        bus.publish(governance(true));
1095        tokio::time::sleep(Duration::from_millis(50)).await;
1096        bus.publish(governance(false));
1097        bus.publish(wake(None));
1098        sink.permits.add_permits(100);
1099        assert_eq!(seen(&sink, 2).await, [governance(true), wake(None)]);
1100    }
1101
1102    #[tokio::test]
1103    async fn the_audit_sink_writes_kernel_wake_records() {
1104        let recorder = Arc::new(InMemoryAuditRecorder::new());
1105        let sink = AuditSink::new(AuditTrail::new(recorder.clone()));
1106        let outcomes = [
1107            WakeOutcome::Woke { pid: "run-1".into() },
1108            WakeOutcome::Spawned { pid: "run-2".into(), trigger: "triage".into() },
1109            WakeOutcome::Deduplicated { pid: "run-2".into() },
1110            WakeOutcome::Expired { pid: "run-3".into(), action: ExpiryAction::Cancel },
1111        ];
1112        for outcome in &outcomes {
1113            sink.emit(&wake(Some(outcome.clone()))).await.unwrap();
1114        }
1115        sink.emit(&wake(None)).await.unwrap();
1116        sink.emit(&governance(true)).await.unwrap();
1117        sink.emit(&health()).await.unwrap();
1118
1119        let records = recorder.records();
1120        assert_eq!(records.len(), 4, "only wakes that concerned a process are records");
1121        for record in &records {
1122            assert_eq!(record.kind, AuditRecordKind::Other(crate::audit::KERNEL_AUDIT_KIND.into()));
1123            assert_eq!(record.action, crate::audit::WAKE);
1124            assert_eq!(record.actor, AuditActor::subject(SubjectRef::service("hook:github")));
1125            assert_eq!(record.ext["source"], "hook:github");
1126            assert_eq!(record.ext["key"], "hook:github:msg_1");
1127        }
1128        let fields = |index: usize, field: &str| records[index].ext.get(field).cloned();
1129        assert_eq!(fields(0, "matchedPid"), Some(json!("run-1")));
1130        assert_eq!(fields(0, "deduplicated"), Some(json!(false)));
1131        assert_eq!(fields(1, "newPid"), Some(json!("run-2")));
1132        assert_eq!(fields(1, "trigger"), Some(json!("triage")));
1133        assert_eq!(fields(1, "matchedPid"), None);
1134        assert_eq!(fields(2, "matchedPid"), Some(json!("run-2")));
1135        assert_eq!(fields(2, "deduplicated"), Some(json!(true)));
1136        assert_eq!(fields(3, "matchedPid"), Some(json!("run-3")));
1137        assert_eq!(fields(3, "expiry"), Some(json!("cancel")));
1138    }
1139
1140    #[test]
1141    fn every_event_kind_round_trips_by_its_type_name() {
1142        for kind in EventKind::ALL {
1143            assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
1144            assert_eq!(kind.as_str().parse::<EventKind>().unwrap(), kind);
1145            assert_eq!(kind.to_string(), kind.as_str());
1146        }
1147        let names: BTreeSet<&str> = EventKind::ALL.iter().map(|kind| kind.as_str()).collect();
1148        assert_eq!(names.len(), EventKind::ALL.len(), "each kind has its own name");
1149        for event in [governance(true), health(), wake(None)] {
1150            assert_eq!(serde_json::to_value(&event).unwrap()["type"], event.kind().as_str());
1151            assert_eq!(event.name(), event.kind().as_str());
1152        }
1153        assert!("Governance".parse::<EventKind>().is_err());
1154    }
1155
1156    #[test]
1157    fn a_filter_selects_by_kind_and_refuses_unknown_type_names() {
1158        let filter = EventFilter::parse(["decided", "held"]).unwrap();
1159        assert_eq!(filter.kinds().collect::<Vec<_>>(), [EventKind::Held, EventKind::Decided]);
1160        assert!(!filter.matches(&governance(true)));
1161        let error = EventFilter::parse(["held", "helth"]).unwrap_err().to_string();
1162        assert!(error.contains("`helth`") && error.contains("governance"), "{error}");
1163
1164        let default = EventFilter::default();
1165        assert!(!default.matches(&health()) && default.matches(&governance(false)));
1166        assert_eq!(default.kinds().count(), EventKind::ALL.len() - 1);
1167        assert_eq!(EventFilter::all().without(EventKind::Health), default);
1168    }
1169
1170    #[test]
1171    fn wake_events_serialize_their_outcome() {
1172        let event =
1173            wake(Some(WakeOutcome::Spawned { pid: "run-2".into(), trigger: "triage".into() }));
1174        let json = serde_json::to_value(&event).unwrap();
1175        assert_eq!(json["type"], "wake");
1176        assert_eq!(json["pid"], "run-2");
1177        assert_eq!(json["outcome"], json!({"spawned": {"pid": "run-2", "trigger": "triage"}}));
1178        assert_eq!(serde_json::from_value::<KernelEvent>(json).unwrap(), event);
1179        let unmatched = serde_json::to_value(wake(None)).unwrap();
1180        assert!(unmatched.get("outcome").is_none() && unmatched.get("pid").is_none());
1181    }
1182}