1use 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
45pub const DEFAULT_EVENT_CAPACITY: usize = 1024;
47
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
69#[non_exhaustive]
70pub enum KernelEvent {
71 Process {
73 pid: String,
75 from: RunState,
77 to: RunState,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
81 reason: Option<String>,
82 },
83 Wake {
85 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pid: Option<String>,
89 source: String,
91 key: String,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
96 outcome: Option<WakeOutcome>,
97 },
98 Held {
100 pid: String,
102 request: ToolConfirmationRequest,
104 },
105 Decided {
107 pid: String,
109 fingerprint: String,
111 decision: ToolConfirmationDecision,
113 by: SubjectRef,
115 },
116 RuleHit {
118 pid: String,
120 rule_id: String,
122 },
123 Spend {
125 partition: PartitionId,
127 key: SpendKey,
129 delta: SpendDelta,
131 },
132 Agenda {
135 item: String,
137 from: AgendaState,
139 to: AgendaState,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
143 reason: Option<String>,
144 },
145 Review(ReviewReport),
148 Driver {
151 id: String,
153 state: crate::drivers::DriverState,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 reason: Option<String>,
158 },
159 Observation {
161 id: String,
163 partition: PartitionId,
165 },
166 Agent {
169 id: String,
171 change: crate::agents::AgentChange,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
175 reason: Option<String>,
176 },
177 Subagent {
181 pid: String,
183 id: String,
185 name: String,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
189 parent: Option<String>,
190 status: adk_core::SubagentStatus,
192 },
193 Governance {
195 frozen: bool,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
199 reason: Option<String>,
200 },
201 Health(KernelHealth),
203}
204
205impl KernelEvent {
206 pub fn name(&self) -> &'static str {
208 self.kind().as_str()
209 }
210
211 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255#[non_exhaustive]
256pub enum EventKind {
257 Process,
259 Wake,
261 Held,
263 Decided,
265 RuleHit,
267 Spend,
269 Agenda,
271 Review,
273 Driver,
275 Observation,
277 Agent,
279 Subagent,
281 Governance,
283 Health,
285}
286
287impl EventKind {
288 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 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#[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 pub fn all() -> Self {
381 Self::only(EventKind::ALL)
382 }
383
384 pub fn only(kinds: impl IntoIterator<Item = EventKind>) -> Self {
386 Self { kinds: kinds.into_iter().collect() }
387 }
388
389 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 #[must_use]
405 pub fn without(mut self, kind: EventKind) -> Self {
406 self.kinds.remove(&kind);
407 self
408 }
409
410 pub fn selects(&self, kind: EventKind) -> bool {
412 self.kinds.contains(&kind)
413 }
414
415 pub fn matches(&self, event: &KernelEvent) -> bool {
417 self.selects(event.kind())
418 }
419
420 pub fn kinds(&self) -> impl Iterator<Item = EventKind> + '_ {
422 self.kinds.iter().copied()
423 }
424}
425
426#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "camelCase")]
450#[non_exhaustive]
451pub struct SpendDelta {
452 pub micro_usd: u64,
454 #[serde(default, skip_serializing_if = "is_zero")]
456 pub model_calls: u64,
457 #[serde(default, skip_serializing_if = "is_zero")]
459 pub total_tokens: u64,
460 #[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 pub fn new(micro_usd: u64) -> Self {
472 Self { micro_usd, ..Self::default() }
473 }
474
475 #[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 #[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 #[must_use]
491 pub fn with_units(mut self, units: adk_core::UsageVector) -> Self {
492 self.units = units;
493 self
494 }
495
496 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
510#[serde(rename_all = "camelCase")]
511#[non_exhaustive]
512pub struct EventRecord {
513 pub cursor: u64,
515 pub at: DateTime<Utc>,
517 pub event: KernelEvent,
519}
520
521#[async_trait]
541pub trait EventSink: Send + Sync {
542 async fn emit(&self, event: &KernelEvent) -> Result<()>;
548
549 async fn emit_record(&self, record: &EventRecord) -> Result<()> {
557 self.emit(&record.event).await
558 }
559}
560
561#[derive(Clone)]
589pub struct EventBus {
590 inner: Arc<BusInner>,
591}
592
593struct BusInner {
594 sender: broadcast::Sender<EventRecord>,
595 capacity: usize,
596 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
615struct 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 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 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 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 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 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 pub fn subscribe(&self) -> EventSubscriber {
760 EventSubscriber { backlog: VecDeque::new(), receiver: self.inner.sender.subscribe() }
761 }
762
763 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#[derive(Debug)]
807pub struct EventSubscriber {
808 backlog: VecDeque<EventRecord>,
810 receiver: broadcast::Receiver<EventRecord>,
811}
812
813impl EventSubscriber {
814 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 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#[derive(Debug, Clone)]
863pub struct AuditSink {
864 trail: AuditTrail,
865}
866
867impl AuditSink {
868 pub fn new(trail: AuditTrail) -> Self {
870 Self { trail }
871 }
872
873 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#[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 = ¬ification.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, ¬ification.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 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 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 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 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}