use std::collections::{BTreeSet, VecDeque};
use std::fmt;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
use adk_core::{RunState, SpendKey, SubjectRef, ToolConfirmationDecision, ToolConfirmationRequest};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::stream::{self, BoxStream, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::{Notify, broadcast};
use crate::agenda::AgendaState;
use crate::error::{KernelError, Result};
use crate::kernel::KernelHealth;
use crate::partition::PartitionId;
use crate::review::ReviewReport;
use crate::wake::WakeOutcome;
#[cfg(feature = "webhooks")]
mod webhook;
#[cfg(feature = "webhooks")]
pub use webhook::WebhookSink;
pub const DEFAULT_EVENT_CAPACITY: usize = 1024;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum KernelEvent {
Process {
pid: String,
from: RunState,
to: RunState,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
Wake {
#[serde(default, skip_serializing_if = "Option::is_none")]
pid: Option<String>,
source: String,
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
outcome: Option<WakeOutcome>,
},
Held {
pid: String,
request: ToolConfirmationRequest,
},
Decided {
pid: String,
fingerprint: String,
decision: ToolConfirmationDecision,
by: SubjectRef,
},
RuleHit {
pid: String,
rule_id: String,
},
Spend {
partition: PartitionId,
key: SpendKey,
delta: SpendDelta,
},
Agenda {
item: String,
from: AgendaState,
to: AgendaState,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
Review(ReviewReport),
Driver {
id: String,
state: crate::drivers::DriverState,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
Observation {
id: String,
partition: PartitionId,
},
Agent {
id: String,
change: crate::agents::AgentChange,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
Subagent {
pid: String,
id: String,
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
parent: Option<String>,
status: adk_core::SubagentStatus,
},
Governance {
frozen: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
Health(KernelHealth),
}
impl KernelEvent {
pub fn name(&self) -> &'static str {
self.kind().as_str()
}
pub fn kind(&self) -> EventKind {
match self {
Self::Process { .. } => EventKind::Process,
Self::Wake { .. } => EventKind::Wake,
Self::Held { .. } => EventKind::Held,
Self::Decided { .. } => EventKind::Decided,
Self::RuleHit { .. } => EventKind::RuleHit,
Self::Spend { .. } => EventKind::Spend,
Self::Agenda { .. } => EventKind::Agenda,
Self::Review(_) => EventKind::Review,
Self::Driver { .. } => EventKind::Driver,
Self::Observation { .. } => EventKind::Observation,
Self::Agent { .. } => EventKind::Agent,
Self::Subagent { .. } => EventKind::Subagent,
Self::Governance { .. } => EventKind::Governance,
Self::Health(_) => EventKind::Health,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum EventKind {
Process,
Wake,
Held,
Decided,
RuleHit,
Spend,
Agenda,
Review,
Driver,
Observation,
Agent,
Subagent,
Governance,
Health,
}
impl EventKind {
pub const ALL: [EventKind; 14] = [
Self::Process,
Self::Wake,
Self::Held,
Self::Decided,
Self::RuleHit,
Self::Spend,
Self::Agenda,
Self::Review,
Self::Driver,
Self::Observation,
Self::Agent,
Self::Subagent,
Self::Governance,
Self::Health,
];
pub fn as_str(self) -> &'static str {
match self {
Self::Process => "process",
Self::Wake => "wake",
Self::Held => "held",
Self::Decided => "decided",
Self::RuleHit => "ruleHit",
Self::Spend => "spend",
Self::Agenda => "agenda",
Self::Review => "review",
Self::Driver => "driver",
Self::Observation => "observation",
Self::Agent => "agent",
Self::Subagent => "subagent",
Self::Governance => "governance",
Self::Health => "health",
}
}
}
impl fmt::Display for EventKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for EventKind {
type Err = KernelError;
fn from_str(text: &str) -> Result<Self> {
Self::ALL.into_iter().find(|kind| kind.as_str() == text.trim()).ok_or_else(|| {
KernelError::Config {
reason: format!(
"unknown kernel event type `{text}`; use one of {}",
Self::ALL.map(Self::as_str).join(", ")
),
}
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventFilter {
kinds: BTreeSet<EventKind>,
}
impl Default for EventFilter {
fn default() -> Self {
Self::all().without(EventKind::Health)
}
}
impl EventFilter {
pub fn all() -> Self {
Self::only(EventKind::ALL)
}
pub fn only(kinds: impl IntoIterator<Item = EventKind>) -> Self {
Self { kinds: kinds.into_iter().collect() }
}
pub fn parse<S: AsRef<str>>(names: impl IntoIterator<Item = S>) -> Result<Self> {
names
.into_iter()
.map(|name| name.as_ref().parse())
.collect::<Result<Vec<EventKind>>>()
.map(Self::only)
}
#[must_use]
pub fn without(mut self, kind: EventKind) -> Self {
self.kinds.remove(&kind);
self
}
pub fn selects(&self, kind: EventKind) -> bool {
self.kinds.contains(&kind)
}
pub fn matches(&self, event: &KernelEvent) -> bool {
self.selects(event.kind())
}
pub fn kinds(&self) -> impl Iterator<Item = EventKind> + '_ {
self.kinds.iter().copied()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SpendDelta {
pub micro_usd: u64,
#[serde(default, skip_serializing_if = "is_zero")]
pub model_calls: u64,
#[serde(default, skip_serializing_if = "is_zero")]
pub total_tokens: u64,
#[serde(default, skip_serializing_if = "adk_core::UsageVector::is_empty")]
pub units: adk_core::UsageVector,
}
fn is_zero(value: &u64) -> bool {
*value == 0
}
impl SpendDelta {
pub fn new(micro_usd: u64) -> Self {
Self { micro_usd, ..Self::default() }
}
#[must_use]
pub fn with_model_calls(mut self, model_calls: u64) -> Self {
self.model_calls = model_calls;
self
}
#[must_use]
pub fn with_total_tokens(mut self, total_tokens: u64) -> Self {
self.total_tokens = total_tokens;
self
}
#[must_use]
pub fn with_units(mut self, units: adk_core::UsageVector) -> Self {
self.units = units;
self
}
pub fn is_empty(&self) -> bool {
self.micro_usd == 0
&& self.model_calls == 0
&& self.total_tokens == 0
&& self.units.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct EventRecord {
pub cursor: u64,
pub at: DateTime<Utc>,
pub event: KernelEvent,
}
#[async_trait]
pub trait EventSink: Send + Sync {
async fn emit(&self, event: &KernelEvent) -> Result<()>;
async fn emit_record(&self, record: &EventRecord) -> Result<()> {
self.emit(&record.event).await
}
}
#[derive(Clone)]
pub struct EventBus {
inner: Arc<BusInner>,
}
struct BusInner {
sender: broadcast::Sender<EventRecord>,
capacity: usize,
log: Mutex<BusLog>,
sinks: Mutex<Vec<Arc<SinkQueue>>>,
}
struct BusLog {
next: u64,
history: VecDeque<EventRecord>,
}
impl Drop for BusInner {
fn drop(&mut self) {
for sink in self.sinks.get_mut().unwrap_or_else(PoisonError::into_inner).iter() {
sink.close();
}
}
}
struct SinkQueue {
sink: Arc<dyn EventSink>,
capacity: usize,
queue: Mutex<VecDeque<EventRecord>>,
ready: Notify,
started: AtomicBool,
closed: AtomicBool,
dropped: AtomicU64,
}
impl SinkQueue {
fn push(self: &Arc<Self>, record: EventRecord) {
{
let mut queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner);
if queue.len() >= self.capacity {
let dropped = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
if matches!(record.event, KernelEvent::Health(_)) {
tracing::warn!(sink.dropped = dropped, "event sink is behind; health dropped");
return;
}
let health =
queue.iter().position(|queued| matches!(queued.event, KernelEvent::Health(_)));
let shed = match health {
Some(index) => queue.remove(index),
None => queue.pop_front(),
};
let shed = shed.as_ref().map_or("none", |shed| shed.event.name());
tracing::warn!(
event.dropped = shed,
sink.dropped = dropped,
"event sink is behind; event dropped"
);
}
queue.push_back(record);
}
self.ready.notify_one();
self.start();
}
fn start(self: &Arc<Self>) {
if self.started.load(Ordering::Acquire) {
return;
}
let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
if self.started.swap(true, Ordering::AcqRel) {
return;
}
let queue = Arc::clone(self);
runtime.spawn(async move { queue.drain().await });
}
async fn drain(&self) {
loop {
let next = self.queue.lock().unwrap_or_else(PoisonError::into_inner).pop_front();
match next {
Some(record) => {
if let Err(error) = self.sink.emit_record(&record).await {
tracing::warn!(event.kind = record.event.name(), error = %error, "event sink failed");
}
}
None if self.closed.load(Ordering::Acquire) => return,
None => self.ready.notified().await,
}
}
}
fn close(&self) {
self.closed.store(true, Ordering::Release);
self.ready.notify_one();
}
}
impl fmt::Debug for EventBus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EventBus")
.field("subscribers", &self.inner.sender.receiver_count())
.finish_non_exhaustive()
}
}
impl Default for EventBus {
fn default() -> Self {
Self::new(DEFAULT_EVENT_CAPACITY)
}
}
impl EventBus {
pub fn new(capacity: usize) -> Self {
let capacity = capacity.max(1);
let (sender, _) = broadcast::channel(capacity);
Self {
inner: Arc::new(BusInner {
sender,
capacity,
log: Mutex::new(BusLog { next: 1, history: VecDeque::with_capacity(capacity) }),
sinks: Mutex::new(Vec::new()),
}),
}
}
pub fn add_sink(&self, sink: Arc<dyn EventSink>) {
let queue = Arc::new(SinkQueue {
sink,
capacity: self.inner.capacity,
queue: Mutex::new(VecDeque::new()),
ready: Notify::new(),
started: AtomicBool::new(false),
closed: AtomicBool::new(false),
dropped: AtomicU64::new(0),
});
queue.start();
self.inner.sinks.lock().unwrap_or_else(PoisonError::into_inner).push(queue);
}
pub fn publish(&self, event: KernelEvent) -> EventRecord {
let record = {
let mut log = self.inner.log.lock().unwrap_or_else(PoisonError::into_inner);
let record = EventRecord { cursor: log.next, at: Utc::now(), event };
log.next += 1;
if log.history.len() == self.inner.capacity {
log.history.pop_front();
}
log.history.push_back(record.clone());
let _ = self.inner.sender.send(record.clone());
record
};
let sinks = self.inner.sinks.lock().unwrap_or_else(PoisonError::into_inner).clone();
for sink in sinks {
sink.push(record.clone());
}
record
}
pub fn subscribe(&self) -> EventSubscriber {
EventSubscriber { backlog: VecDeque::new(), receiver: self.inner.sender.subscribe() }
}
pub async fn subscribe_after(&self, cursor: u64) -> Result<EventSubscriber> {
let log = self.inner.log.lock().unwrap_or_else(PoisonError::into_inner);
let receiver = self.inner.sender.subscribe();
let issued = cursor < log.next;
let backlog = log
.history
.iter()
.filter(|record| !issued || record.cursor > cursor)
.cloned()
.collect();
Ok(EventSubscriber { backlog, receiver })
}
}
#[derive(Debug)]
pub struct EventSubscriber {
backlog: VecDeque<EventRecord>,
receiver: broadcast::Receiver<EventRecord>,
}
impl EventSubscriber {
pub async fn recv(&mut self) -> Option<EventRecord> {
if let Some(record) = self.backlog.pop_front() {
return Some(record);
}
loop {
match self.receiver.recv().await {
Ok(record) => return Some(record),
Err(broadcast::error::RecvError::Lagged(skipped)) => {
tracing::warn!(events.skipped = skipped, "event subscriber fell behind");
}
Err(broadcast::error::RecvError::Closed) => return None,
}
}
}
pub fn into_stream(self) -> BoxStream<'static, EventRecord> {
stream::unfold(self, |mut subscriber| async move {
subscriber.recv().await.map(|record| (record, subscriber))
})
.boxed()
}
}
#[derive(Debug, Clone)]
pub struct AuditSink {
trail: AuditTrail,
}
impl AuditSink {
pub fn new(trail: AuditTrail) -> Self {
Self { trail }
}
pub fn trail(&self) -> &AuditTrail {
&self.trail
}
}
#[async_trait]
impl EventSink for AuditSink {
async fn emit(&self, event: &KernelEvent) -> Result<()> {
let KernelEvent::Wake { source, key, outcome: Some(outcome), .. } = event else {
return Ok(());
};
let mut draft = AuditRecordDraft::new(
AuditRecordKind::Other(crate::audit::KERNEL_AUDIT_KIND.to_string()),
crate::audit::WAKE,
)
.actor(AuditActor::subject(SubjectRef::service(source.clone())))
.ext("source", json!(source))
.ext("key", json!(key))
.ext("deduplicated", json!(matches!(outcome, WakeOutcome::Deduplicated { .. })));
draft = match outcome {
WakeOutcome::Spawned { pid, trigger } => {
draft.ext("newPid", json!(pid)).ext("trigger", json!(trigger))
}
WakeOutcome::Expired { pid, action } => {
draft.ext("matchedPid", json!(pid)).ext("expiry", json!(action))
}
WakeOutcome::Woke { pid } | WakeOutcome::Deduplicated { pid } => {
draft.ext("matchedPid", json!(pid))
}
WakeOutcome::Skipped { pid, trigger } => draft
.ext("matchedPid", json!(pid))
.ext("trigger", json!(trigger))
.ext("overlap", json!("skipped")),
WakeOutcome::Coalesced { pid, trigger } => draft
.ext("matchedPid", json!(pid))
.ext("trigger", json!(trigger))
.ext("overlap", json!("coalesced")),
WakeOutcome::Missed { trigger } => {
draft.ext("trigger", json!(trigger)).ext("missed", json!(true))
}
};
self.trail.record(draft).await?;
Ok(())
}
}
#[derive(Clone)]
pub(crate) struct ApprovalEvents(EventBus);
impl ApprovalEvents {
pub(crate) fn new(bus: EventBus) -> Self {
Self(bus)
}
}
impl fmt::Debug for ApprovalEvents {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApprovalEvents").finish_non_exhaustive()
}
}
#[async_trait]
impl adk_core::ApprovalNotifier for ApprovalEvents {
async fn notify(&self, notification: &adk_core::ApprovalNotification) -> adk_core::Result<()> {
use adk_core::{ApprovalEventKind, ApprovalState};
let request = ¬ification.request;
let mut call =
ToolConfirmationRequest::new(request.tool_name.clone(), request.args_redacted.clone());
call.origin = request.origin.clone();
call.acting = request.acting.clone().map(Box::new);
let pid = request.run_id.clone().unwrap_or_default();
match (notification.kind, ¬ification.decision) {
(ApprovalEventKind::Submitted, _) => {
self.0.publish(KernelEvent::Held { pid, request: call });
}
(ApprovalEventKind::Decided, Some(decision)) if request.state.is_terminal() => {
let decision_kind = match request.state {
ApprovalState::Approved => ToolConfirmationDecision::Approve,
ApprovalState::Pending
| ApprovalState::Rejected
| ApprovalState::Responded
| ApprovalState::Expired
| ApprovalState::Cancelled => ToolConfirmationDecision::Deny,
};
self.0.publish(KernelEvent::Decided {
pid,
fingerprint: call.fingerprint(),
decision: decision_kind,
by: decision.authority().clone(),
});
}
_ => {}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use adk_core::audit_log::InMemoryAuditRecorder;
use tokio::sync::Semaphore;
use super::*;
use crate::wake::ExpiryAction;
fn governance(frozen: bool) -> KernelEvent {
KernelEvent::Governance { frozen, reason: None }
}
fn health() -> KernelEvent {
KernelEvent::Health(KernelHealth::default())
}
fn wake(outcome: Option<WakeOutcome>) -> KernelEvent {
KernelEvent::Wake {
pid: outcome.as_ref().and_then(WakeOutcome::pid).map(str::to_string),
source: "hook:github".into(),
key: "hook:github:msg_1".into(),
outcome,
}
}
struct GatedSink {
permits: Semaphore,
seen: Mutex<Vec<KernelEvent>>,
}
#[async_trait]
impl EventSink for GatedSink {
async fn emit(&self, event: &KernelEvent) -> Result<()> {
self.permits.acquire().await.unwrap().forget();
self.seen.lock().unwrap().push(event.clone());
Ok(())
}
}
async fn seen(sink: &GatedSink, count: usize) -> Vec<KernelEvent> {
for _ in 0..500 {
if sink.seen.lock().unwrap().len() >= count {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
sink.seen.lock().unwrap().clone()
}
#[tokio::test]
async fn a_reconnecting_subscriber_replays_from_its_cursor_without_gap_or_repeat() {
let bus = EventBus::new(8);
let first = bus.publish(governance(true));
let missed = [bus.publish(governance(false)), bus.publish(governance(true))];
let mut subscriber = bus.subscribe_after(first.cursor).await.unwrap();
let live = bus.publish(governance(false));
for expected in missed.iter().chain([&live]) {
assert_eq!(&subscriber.recv().await.unwrap(), expected);
}
let mut current = bus.subscribe_after(live.cursor).await.unwrap();
let next = bus.publish(governance(true));
assert_eq!(current.recv().await.unwrap(), next);
}
#[tokio::test]
async fn a_cursor_from_before_a_restart_replays_everything_held() {
let bus = EventBus::new(2);
bus.publish(governance(true));
let held = [bus.publish(governance(false)), bus.publish(governance(true))];
let mut subscriber = bus.subscribe_after(9_999).await.unwrap();
for expected in &held {
assert_eq!(&subscriber.recv().await.unwrap(), expected);
}
let mut lagging = bus.subscribe_after(0).await.unwrap();
assert_eq!(lagging.recv().await.unwrap(), held[0], "only the last two are held");
}
#[tokio::test]
async fn sinks_receive_every_event_in_order() {
let bus = EventBus::new(16);
let sink = Arc::new(GatedSink { permits: Semaphore::new(100), seen: Mutex::default() });
bus.add_sink(sink.clone());
let events = [governance(true), wake(None), governance(false)];
for event in &events {
bus.publish(event.clone());
}
assert_eq!(seen(&sink, 3).await, events);
}
#[tokio::test]
async fn a_slow_sink_drops_health_first_and_never_blocks_the_publisher() {
let bus = EventBus::new(3);
let sink = Arc::new(GatedSink { permits: Semaphore::new(0), seen: Mutex::default() });
bus.add_sink(sink.clone());
bus.publish(governance(true));
tokio::time::sleep(Duration::from_millis(50)).await;
bus.publish(health());
bus.publish(governance(false));
bus.publish(health());
bus.publish(health());
bus.publish(wake(None));
bus.publish(governance(true));
sink.permits.add_permits(100);
assert_eq!(
seen(&sink, 4).await,
[governance(true), governance(false), wake(None), governance(true)]
);
let bus = EventBus::new(1);
let sink = Arc::new(GatedSink { permits: Semaphore::new(0), seen: Mutex::default() });
bus.add_sink(sink.clone());
bus.publish(governance(true));
tokio::time::sleep(Duration::from_millis(50)).await;
bus.publish(governance(false));
bus.publish(wake(None));
sink.permits.add_permits(100);
assert_eq!(seen(&sink, 2).await, [governance(true), wake(None)]);
}
#[tokio::test]
async fn the_audit_sink_writes_kernel_wake_records() {
let recorder = Arc::new(InMemoryAuditRecorder::new());
let sink = AuditSink::new(AuditTrail::new(recorder.clone()));
let outcomes = [
WakeOutcome::Woke { pid: "run-1".into() },
WakeOutcome::Spawned { pid: "run-2".into(), trigger: "triage".into() },
WakeOutcome::Deduplicated { pid: "run-2".into() },
WakeOutcome::Expired { pid: "run-3".into(), action: ExpiryAction::Cancel },
];
for outcome in &outcomes {
sink.emit(&wake(Some(outcome.clone()))).await.unwrap();
}
sink.emit(&wake(None)).await.unwrap();
sink.emit(&governance(true)).await.unwrap();
sink.emit(&health()).await.unwrap();
let records = recorder.records();
assert_eq!(records.len(), 4, "only wakes that concerned a process are records");
for record in &records {
assert_eq!(record.kind, AuditRecordKind::Other(crate::audit::KERNEL_AUDIT_KIND.into()));
assert_eq!(record.action, crate::audit::WAKE);
assert_eq!(record.actor, AuditActor::subject(SubjectRef::service("hook:github")));
assert_eq!(record.ext["source"], "hook:github");
assert_eq!(record.ext["key"], "hook:github:msg_1");
}
let fields = |index: usize, field: &str| records[index].ext.get(field).cloned();
assert_eq!(fields(0, "matchedPid"), Some(json!("run-1")));
assert_eq!(fields(0, "deduplicated"), Some(json!(false)));
assert_eq!(fields(1, "newPid"), Some(json!("run-2")));
assert_eq!(fields(1, "trigger"), Some(json!("triage")));
assert_eq!(fields(1, "matchedPid"), None);
assert_eq!(fields(2, "matchedPid"), Some(json!("run-2")));
assert_eq!(fields(2, "deduplicated"), Some(json!(true)));
assert_eq!(fields(3, "matchedPid"), Some(json!("run-3")));
assert_eq!(fields(3, "expiry"), Some(json!("cancel")));
}
#[test]
fn every_event_kind_round_trips_by_its_type_name() {
for kind in EventKind::ALL {
assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
assert_eq!(kind.as_str().parse::<EventKind>().unwrap(), kind);
assert_eq!(kind.to_string(), kind.as_str());
}
let names: BTreeSet<&str> = EventKind::ALL.iter().map(|kind| kind.as_str()).collect();
assert_eq!(names.len(), EventKind::ALL.len(), "each kind has its own name");
for event in [governance(true), health(), wake(None)] {
assert_eq!(serde_json::to_value(&event).unwrap()["type"], event.kind().as_str());
assert_eq!(event.name(), event.kind().as_str());
}
assert!("Governance".parse::<EventKind>().is_err());
}
#[test]
fn a_filter_selects_by_kind_and_refuses_unknown_type_names() {
let filter = EventFilter::parse(["decided", "held"]).unwrap();
assert_eq!(filter.kinds().collect::<Vec<_>>(), [EventKind::Held, EventKind::Decided]);
assert!(!filter.matches(&governance(true)));
let error = EventFilter::parse(["held", "helth"]).unwrap_err().to_string();
assert!(error.contains("`helth`") && error.contains("governance"), "{error}");
let default = EventFilter::default();
assert!(!default.matches(&health()) && default.matches(&governance(false)));
assert_eq!(default.kinds().count(), EventKind::ALL.len() - 1);
assert_eq!(EventFilter::all().without(EventKind::Health), default);
}
#[test]
fn wake_events_serialize_their_outcome() {
let event =
wake(Some(WakeOutcome::Spawned { pid: "run-2".into(), trigger: "triage".into() }));
let json = serde_json::to_value(&event).unwrap();
assert_eq!(json["type"], "wake");
assert_eq!(json["pid"], "run-2");
assert_eq!(json["outcome"], json!({"spawned": {"pid": "run-2", "trigger": "triage"}}));
assert_eq!(serde_json::from_value::<KernelEvent>(json).unwrap(), event);
let unmatched = serde_json::to_value(wake(None)).unwrap();
assert!(unmatched.get("outcome").is_none() && unmatched.get("pid").is_none());
}
}