Skip to main content

oxios_kernel/
event_bus.rs

1//! Event bus: inter-agent communication via `oxi_sdk::EventBus<KernelEvent>`.
2//!
3//! The event bus is the "pipe" of Oxios. All agents communicate
4//! through kernel events published on the bus.
5//!
6//! After RFC-014 Phase C, this module no longer owns the broadcast channel —
7//! it reuses `oxi_sdk::EventBus<E>`, which is a generic wrapper over
8//! `tokio::sync::broadcast`. The only Oxios-specific bits are:
9//!
10//! - `KernelEvent` enum (oxios-internal event vocabulary)
11//! - `kernel_event_to_audit_action` mapping for the audit trail
12//! - `attach_audit_trail` helper (subscribes the bus to the trail)
13
14use oxi_sdk::EventBus as SdkEventBus;
15use oxi_sdk::observability::{AuditAction, AuditTrail};
16use serde::{Deserialize, Serialize};
17use std::sync::Arc;
18use uuid::Uuid;
19
20use crate::types::AgentId;
21
22/// Kernel event bus — generic SDK bus specialised for `KernelEvent`.
23///
24/// The broadcast channel is owned by `oxi_sdk::EventBus`; this type alias
25/// just makes the call sites read more naturally (`crate::event_bus::EventBus`
26/// instead of `oxi_sdk::EventBus<KernelEvent>`).
27pub type EventBus = SdkEventBus<KernelEvent>;
28
29/// Events that flow through the kernel event bus.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub enum KernelEvent {
32    /// A new agent has been created.
33    AgentCreated {
34        /// The new agent's ID.
35        id: AgentId,
36        /// The agent's name/goal.
37        name: String,
38    },
39    /// An agent has started executing.
40    AgentStarted {
41        /// The agent's ID.
42        id: AgentId,
43    },
44    /// An agent has been stopped.
45    ///
46    /// Carries `success` so consumers can distinguish a normal completion
47    /// (`success: true`) from an evaluation/assessment failure
48    /// (`success: false`). Infrastructure errors (panic, timeout) emit
49    /// `AgentFailed` instead.
50    AgentStopped {
51        /// The agent's ID.
52        id: AgentId,
53        /// Whether the agent's result passed evaluation. Mirrors
54        /// `ExecutionResult.success` from the Ok path; `false` on the
55        /// kill/terminate path (user-initiated stop).
56        #[serde(default)]
57        success: bool,
58    },
59    /// An agent has encountered a failure.
60    AgentFailed {
61        /// The agent's ID.
62        id: AgentId,
63        /// Description of the error.
64        error: String,
65    },
66    /// A message has been received from an agent.
67    MessageReceived {
68        /// The sending agent's ID.
69        from: AgentId,
70        /// Message content.
71        content: String,
72    },
73    /// An agent has produced output.
74    AgentOutput {
75        /// The session this output belongs to.
76        session_id: String,
77        /// The agent's ID.
78        agent_id: AgentId,
79        /// The output content.
80        output: String,
81    },
82    /// A HitL approval request has been submitted.
83    ApprovalRequested {
84        /// The approval request ID.
85        id: uuid::Uuid,
86        /// The tool requesting approval.
87        tool_name: String,
88        /// The action requiring approval.
89        action: String,
90        /// The resource involved.
91        resource: String,
92        /// Reason for the request.
93        reason: String,
94        /// The session ID that triggered this request.
95        session_id: Option<String>,
96    },
97    /// A HitL approval has been resolved (approved or rejected).
98    ApprovalResolved {
99        /// The approval request ID.
100        id: uuid::Uuid,
101        /// Whether it was approved (true) or rejected (false).
102        approved: bool,
103    },
104    /// A memory entry was stored.
105    MemoryStored {
106        /// Memory entry ID.
107        id: String,
108        /// Memory type label.
109        memory_type: String,
110        /// Source of the memory.
111        source: String,
112    },
113    /// Memories were recalled for a new session.
114    MemoryRecalled {
115        /// The recall query.
116        query: String,
117        /// Number of memories returned.
118        count: usize,
119    },
120    /// Multi-agent group created.
121    AgentGroupCreated {
122        /// The group's ID.
123        group_id: uuid::Uuid,
124        /// Number of agents in the group.
125        agent_count: usize,
126    },
127    /// An agent in a group completed.
128    AgentGroupMemberCompleted {
129        /// The group's ID.
130        group_id: uuid::Uuid,
131        /// The agent's ID.
132        agent_id: uuid::Uuid,
133        /// Whether the agent succeeded.
134        success: bool,
135    },
136    /// A new Project has been created (RFC-011).
137    ProjectCreated {
138        /// The project's ID.
139        project_id: uuid::Uuid,
140        /// The project's name.
141        name: String,
142        /// How it was created.
143        source: String,
144    },
145    /// A Project has been activated (RFC-011).
146    ProjectActivated {
147        /// The project's ID.
148        project_id: uuid::Uuid,
149        /// The project's name.
150        name: String,
151    },
152
153    // ── RFC-015 Chat Transparency ─────────────────────────────
154    // Real-time events emitted by AgentRuntime during tool execution
155    // and streaming. Web channel converts these to WS chunks.
156    /// A tool execution has started (real-time, RFC-015).
157    ToolExecutionStarted {
158        /// Session this tool call belongs to.
159        session_id: String,
160        /// Name of the tool (e.g. "read_file", "bash", "memory_recall").
161        tool_name: String,
162        /// Provider-specific tool call ID used to correlate start/end.
163        tool_call_id: String,
164        /// Tool input arguments (JSON).
165        tool_args: serde_json::Value,
166        /// Semantic context inferred by oxi-agent 0.32+ from tool name/args
167        /// (e.g. WebSearch, PageVisit). `None` for tools without context mapping.
168        #[serde(default, skip_serializing_if = "Option::is_none")]
169        context: Option<serde_json::Value>,
170    },
171    /// A tool execution has finished (real-time, RFC-015).
172    ToolExecutionFinished {
173        /// Session this tool call belongs to.
174        session_id: String,
175        /// Provider-specific tool call ID.
176        tool_call_id: String,
177        /// Name of the tool.
178        tool_name: String,
179        /// Wall-clock duration in milliseconds.
180        duration_ms: u64,
181        /// Whether the tool returned an error.
182        is_error: bool,
183        /// Truncated output (max ~500 chars) for streaming.
184        output_summary: String,
185    },
186    /// A tool execution emitted a progress update (real-time, RFC-015).
187    ToolExecutionProgress {
188        /// Session this tool call belongs to.
189        session_id: String,
190        /// Provider-specific tool call ID.
191        tool_call_id: String,
192        /// Name of the tool.
193        tool_name: String,
194        /// Human-readable progress text (already-formatted by the tool).
195        progress: String,
196        /// Tab that emitted this progress event, if the upstream tool tracks
197        /// tabs. `None` for tools that don't have a tab concept (e.g. legacy
198        /// oxi-agent versions that don't propagate `tab_id`).
199        #[serde(default, skip_serializing_if = "Option::is_none")]
200        tab_id: Option<Uuid>,
201        /// Semantic context from the tool call (e.g. PageVisit, WebSearch).
202        /// Stored as `serde_json::Value` to decouple kernel events from
203        /// oxi-sdk's internal `ToolCallContext` enum. UI consumers that
204        /// understand a context variant render it richly; older consumers
205        /// simply ignore the field.
206        #[serde(default, skip_serializing_if = "Option::is_none")]
207        context: Option<serde_json::Value>,
208    },
209    /// Memory was recalled during agent execution (RFC-015).
210    MemoryRecallUsed {
211        /// Session this recall belongs to.
212        session_id: String,
213        /// The recall query.
214        query: String,
215        /// Number of memories returned.
216        count: usize,
217        /// Memory tier source ("hot" | "warm" | "cold").
218        source: String,
219    },
220    /// Token usage update (RFC-015).
221    TokenUsageUpdate {
222        /// Session this usage belongs to.
223        session_id: String,
224        /// Cumulative input tokens.
225        input_tokens: u64,
226        /// Cumulative output tokens.
227        output_tokens: u64,
228    },
229    /// Reasoning/compaction fragment (RFC-015).
230    ReasoningFragment {
231        /// Session this fragment belongs to.
232        session_id: String,
233        /// The fragment text (chain-of-thought, compaction summary, etc).
234        content: String,
235        /// Source label: "chain_of_thought" | "compaction" | "reflection".
236        source: String,
237    },
238
239    /// Compaction was triggered (RFC-035 gap 2 observability).
240    ///
241    /// Emitted when `oxi_sdk::CompactionEvent::Triggered` fires (0.53.0+).
242    /// `source` is one of:
243    /// - `"provider-reported"` — provider-reported `usage.input_tokens` drove
244    ///   the trigger (ground truth; gap 2's primary signal)
245    /// - `"bytes/4 heuristic (cold start)"` — legacy heuristic; only on turn 1
246    ///   before any `ProviderEvent::Done` has been observed
247    /// - `"empty"` — empty context (no trigger source)
248    CompactionTriggered {
249        /// Session this compaction belongs to.
250        session_id: Option<String>,
251        /// The trigger source label from `CompactionEvent::Triggered::source`.
252        source: String,
253    },
254    // ── RFC-015 Chat Transparency: lifecycle phases (P3) ────────────────
255    // Real-time events emitted by the Orchestrator as it transitions
256    // between ouroboros phases (assess → crystallize → execute → review).
257    // The web channel converts these to WS `phase` chunks; the orchestrator
258    // is the single source of truth for phase boundaries.
259    /// A lifecycle phase has begun.
260    PhaseStarted {
261        /// Session this phase belongs to.
262        session_id: String,
263        /// Phase name: `"assess"` | `"plan"` (crystallize) | `"execute"` | `"review"`.
264        phase: String,
265        /// Optional human-readable summary for the timeline header.
266        summary: Option<String>,
267    },
268    /// A lifecycle phase has completed.
269    PhaseCompleted {
270        /// Session this phase belongs to.
271        session_id: String,
272        /// Phase name — same vocabulary as `PhaseStarted::phase`.
273        phase: String,
274    },
275
276    // ── Calendar ──────────────────────────────────────────────
277    /// A calendar event was created.
278    CalendarEventCreated {
279        /// Event UID.
280        uid: String,
281        /// Event title.
282        title: String,
283        /// Start time.
284        start: String,
285        /// End time.
286        end: String,
287    },
288    /// A calendar event was updated.
289    CalendarEventUpdated {
290        /// Event UID.
291        uid: String,
292        /// Event title.
293        title: String,
294    },
295    /// A calendar event was deleted.
296    CalendarEventDeleted {
297        /// Event UID.
298        uid: String,
299        /// Event title.
300        title: String,
301    },
302    /// An email has been sent.
303    EmailSent {
304        /// Email subject.
305        subject: String,
306        /// SMTP message ID.
307        message_id: String,
308        /// Template name (if template was used/saved).
309        #[serde(default, skip_serializing_if = "Option::is_none")]
310        template_name: Option<String>,
311    },
312
313    // ── Knowledge ──────────────────────────────────────────────
314    /// A knowledge note was persisted (hook, user, or tool).
315    KnowledgePersisted {
316        session_id: String,
317        message_index: usize,
318        path: String,
319        source: String, // "hook", "user", "tool"
320    },
321    /// A knowledge note was removed by user action.
322    KnowledgeRemoved {
323        session_id: String,
324        message_index: usize,
325    },
326    /// A question was posed to the user by the agent (RFC-027, `ask_user`).
327    /// The frontend renders an input/option picker and resolves the
328    /// pending oneshot via a separate response endpoint.
329    AskUserRequest {
330        /// Unique request ID — used by the response handler to resolve
331        /// the oneshot the tool is awaiting.
332        id: String,
333        /// The question text the user sees.
334        question: String,
335        /// Optional structured options. Empty when the question is open-ended.
336        options: Vec<String>,
337    },
338    // ── Persona (agent-authored writes are security-reviewed) ───────────
339    /// A persona was created (by an agent tool, the HTTP API, or the UI).
340    PersonaCreated {
341        /// Persona ID.
342        id: String,
343        /// Persona display name.
344        name: String,
345        /// Whether it was registered enabled.
346        enabled: bool,
347        /// Origin of the change: "agent" | "api" | "ui".
348        source: String,
349    },
350    /// A persona was updated.
351    PersonaUpdated {
352        /// Persona ID.
353        id: String,
354        /// Persona display name.
355        name: String,
356        /// Origin of the change: "agent" | "api" | "ui".
357        source: String,
358    },
359}
360
361/// Convert a KernelEvent to an AuditAction for the audit trail.
362pub fn kernel_event_to_audit_action(event: &KernelEvent) -> AuditAction {
363    match event {
364        KernelEvent::AgentCreated { name, .. } => AuditAction::AgentSpawn {
365            task_type: name.clone(),
366        },
367        KernelEvent::AgentStarted { .. } => AuditAction::AgentSpawn {
368            task_type: "started".to_string(),
369        },
370        KernelEvent::AgentStopped { success, .. } => AuditAction::AgentExit {
371            reason: if *success {
372                "completed".to_string()
373            } else {
374                "stopped".to_string()
375            },
376        },
377        KernelEvent::AgentFailed { error, .. } => AuditAction::AgentExit {
378            reason: error.clone(),
379        },
380        KernelEvent::MessageReceived { content, .. } => AuditAction::Other {
381            detail: format!("message: {content}"),
382        },
383        KernelEvent::AgentOutput { output, .. } => AuditAction::Other {
384            detail: format!("agent_output:{output}"),
385        },
386        KernelEvent::ApprovalRequested {
387            id,
388            action,
389            resource,
390            ..
391        } => AuditAction::Other {
392            detail: format!("approval_requested:{id}:{action}:{resource}"),
393        },
394        KernelEvent::ApprovalResolved { id, approved } => AuditAction::Other {
395            detail: format!("approval_resolved:{id}:{approved}"),
396        },
397        KernelEvent::MemoryStored {
398            id, memory_type, ..
399        } => AuditAction::MemoryWrite {
400            entry_id: format!("{id}:{memory_type}"),
401        },
402        KernelEvent::MemoryRecalled { query, count } => AuditAction::MemoryRead {
403            entry_id: format!("query:{query}:{count}results"),
404        },
405        KernelEvent::AgentGroupCreated {
406            group_id,
407            agent_count,
408        } => AuditAction::Other {
409            detail: format!("group_created:{group_id}:{agent_count}agents"),
410        },
411        KernelEvent::AgentGroupMemberCompleted {
412            group_id,
413            agent_id,
414            success,
415        } => AuditAction::Other {
416            detail: format!("group_member_completed:{group_id}:{agent_id}:{success}"),
417        },
418        KernelEvent::ProjectCreated {
419            project_id: _,
420            name,
421            source,
422        } => AuditAction::Other {
423            detail: format!("project_created:{name}:{source}"),
424        },
425        KernelEvent::ProjectActivated {
426            project_id: _,
427            name,
428        } => AuditAction::Other {
429            detail: format!("project_activated:{name}"),
430        },
431        // ── RFC-015 ──
432        KernelEvent::ToolExecutionStarted { tool_name, .. } => AuditAction::Other {
433            detail: format!("tool_started:{tool_name}"),
434        },
435        KernelEvent::ToolExecutionFinished {
436            tool_name,
437            is_error,
438            ..
439        } => AuditAction::Other {
440            detail: format!(
441                "tool_finished:{tool_name}:{}",
442                if *is_error { "error" } else { "ok" }
443            ),
444        },
445        KernelEvent::ToolExecutionProgress {
446            tool_name,
447            tab_id,
448            context,
449            ..
450        } => AuditAction::Other {
451            detail: {
452                let mut d = format!("tool_progress:{tool_name}");
453                if let Some(id) = tab_id {
454                    d.push_str(&format!(":tab={id}"));
455                }
456                if let Some(ctx) = context
457                    .as_ref()
458                    .and_then(|c| c.get("kind"))
459                    .and_then(|k| k.as_str())
460                {
461                    d.push_str(&format!(":{ctx}"));
462                }
463                d
464            },
465        },
466        KernelEvent::MemoryRecallUsed { query, count, .. } => AuditAction::MemoryRead {
467            entry_id: format!("recall:{query}:{count}results"),
468        },
469        KernelEvent::TokenUsageUpdate {
470            input_tokens,
471            output_tokens,
472            ..
473        } => AuditAction::Other {
474            detail: format!("tokens:in={input_tokens}:out={output_tokens}"),
475        },
476        KernelEvent::ReasoningFragment { source, .. } => AuditAction::Other {
477            detail: format!("reasoning:{source}"),
478        },
479        KernelEvent::CompactionTriggered { source, .. } => AuditAction::Other {
480            detail: format!("compaction:triggered:{source}"),
481        },
482        KernelEvent::CalendarEventCreated { uid, title, .. } => AuditAction::Other {
483            detail: format!("calendar:created:{uid}:{title}"),
484        },
485        KernelEvent::CalendarEventUpdated { uid, title } => AuditAction::Other {
486            detail: format!("calendar:updated:{uid}:{title}"),
487        },
488        KernelEvent::CalendarEventDeleted { uid, title } => AuditAction::Other {
489            detail: format!("calendar:deleted:{uid}:{title}"),
490        },
491        KernelEvent::EmailSent {
492            subject,
493            message_id,
494            template_name,
495        } => AuditAction::Other {
496            detail: format!("email:sent:{subject} (msg={message_id}, tpl={template_name:?})"),
497        },
498        KernelEvent::KnowledgePersisted {
499            session_id,
500            message_index,
501            path,
502            source,
503        } => AuditAction::Other {
504            detail: format!("knowledge:persisted:{session_id}:{message_index}:{path}:{source}"),
505        },
506        KernelEvent::KnowledgeRemoved {
507            session_id,
508            message_index,
509        } => AuditAction::Other {
510            detail: format!("knowledge:removed:{session_id}:{message_index}"),
511        },
512        KernelEvent::AskUserRequest { id, question, .. } => AuditAction::Other {
513            detail: format!("ask_user:{id}:{question}"),
514        },
515        KernelEvent::PersonaCreated {
516            id, name, source, ..
517        } => AuditAction::Other {
518            detail: format!("persona:created:{id}:{name}:{source}"),
519        },
520        KernelEvent::PersonaUpdated { id, name, source } => AuditAction::Other {
521            detail: format!("persona:updated:{id}:{name}:{source}"),
522        },
523        KernelEvent::PhaseStarted { phase, .. } => AuditAction::Other {
524            detail: format!("phase_started:{phase}"),
525        },
526        KernelEvent::PhaseCompleted { phase, .. } => AuditAction::Other {
527            detail: format!("phase_completed:{phase}"),
528        },
529    }
530}
531
532/// Extract agent ID from a KernelEvent variant.
533fn extract_agent_id(event: &KernelEvent) -> String {
534    match event {
535        KernelEvent::AgentCreated { id, .. } => id.to_string(),
536        KernelEvent::AgentStarted { id, .. } => id.to_string(),
537        KernelEvent::AgentStopped { id, .. } => id.to_string(),
538        KernelEvent::AgentFailed { id, .. } => id.to_string(),
539        KernelEvent::MessageReceived { from, .. } => from.to_string(),
540        KernelEvent::AgentOutput { agent_id, .. } => agent_id.to_string(),
541        KernelEvent::AgentGroupMemberCompleted { agent_id, .. } => agent_id.to_string(),
542        KernelEvent::ProjectActivated { project_id, .. } => format!("project:{project_id}"),
543        // RFC-015: session-scoped events use session_id as the subject
544        KernelEvent::ToolExecutionStarted { session_id, .. } => format!("session:{session_id}"),
545        KernelEvent::ToolExecutionFinished { session_id, .. } => format!("session:{session_id}"),
546        KernelEvent::ToolExecutionProgress { session_id, .. } => format!("session:{session_id}"),
547        KernelEvent::MemoryRecallUsed { session_id, .. } => format!("session:{session_id}"),
548        KernelEvent::TokenUsageUpdate { session_id, .. } => format!("session:{session_id}"),
549        KernelEvent::ReasoningFragment { session_id, .. } => format!("session:{session_id}"),
550        KernelEvent::PhaseStarted { session_id, .. } => format!("session:{session_id}"),
551        KernelEvent::PhaseCompleted { session_id, .. } => format!("session:{session_id}"),
552        KernelEvent::KnowledgePersisted { session_id, .. } => format!("session:{session_id}"),
553        KernelEvent::KnowledgeRemoved { session_id, .. } => format!("session:{session_id}"),
554        KernelEvent::CompactionTriggered { session_id, .. } => session_id
555            .as_ref()
556            .map(|s| format!("session:{s}"))
557            .unwrap_or_else(|| "system".to_string()),
558        _ => "system".to_string(),
559    }
560}
561
562/// Subscribe the audit trail to all kernel events.
563///
564/// The bus is broadcast-based; this spawns a long-running task that
565/// forwards every event into the audit trail as a structured entry.
566/// Lagged subscribers are logged and recovered.
567pub fn attach_audit_trail(bus: &EventBus, audit: Arc<AuditTrail>) {
568    let mut rx = bus.subscribe();
569    tokio::spawn(async move {
570        loop {
571            match rx.recv().await {
572                Ok(event) => {
573                    let actor = extract_agent_id(&event);
574                    let action = kernel_event_to_audit_action(&event);
575                    let resource = format!("{event:?}");
576                    audit.append(actor, action, resource);
577                }
578                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
579                    // Surface the drop as a metric so operators can detect
580                    // incomplete audit trails instead of the events
581                    // vanishing silently (state-area F4).
582                    crate::metrics::get_metrics().audit_lagged_events.inc_by(n);
583                    tracing::warn!(
584                        skipped = n,
585                        "Audit trail subscriber lagged, skipping events"
586                    );
587                    continue;
588                }
589                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
590                    tracing::info!("Audit trail event bus closed, exiting");
591                    break;
592                }
593            }
594        }
595    });
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    fn sample_event(name: &str) -> KernelEvent {
603        KernelEvent::AgentCreated {
604            id: AgentId::new_v4(),
605            name: name.to_string(),
606        }
607    }
608
609    #[test]
610    fn test_event_bus_uses_sdk() {
611        let bus: EventBus = EventBus::new(256);
612        assert!(format!("{:?}", bus).contains("EventBus"));
613    }
614
615    #[tokio::test]
616    async fn test_publish_no_subscribers_ok() {
617        let bus = EventBus::new(16);
618        let result = bus.publish(sample_event("orphan"));
619        assert!(result.is_ok());
620    }
621
622    #[tokio::test]
623    async fn test_single_subscriber_receives_event() {
624        let bus = EventBus::new(16);
625        let mut rx = bus.subscribe();
626
627        let event = sample_event("test-agent");
628        bus.publish(event.clone()).unwrap();
629
630        let received = rx.try_recv().expect("should receive event");
631        match received {
632            KernelEvent::AgentCreated { name, .. } => assert_eq!(name, "test-agent"),
633            _ => panic!("wrong event type"),
634        }
635    }
636
637    #[tokio::test]
638    async fn test_multiple_subscribers_receive_events() {
639        let bus = EventBus::new(16);
640        let mut rx1 = bus.subscribe();
641        let mut rx2 = bus.subscribe();
642
643        let event = sample_event("multi");
644        bus.publish(event.clone()).unwrap();
645
646        let r1 = rx1.try_recv().expect("rx1 should receive event");
647        let r2 = rx2.try_recv().expect("rx2 should receive event");
648
649        assert!(matches!(r1, KernelEvent::AgentCreated { .. }));
650        assert!(matches!(r2, KernelEvent::AgentCreated { .. }));
651    }
652
653    #[tokio::test]
654    async fn test_kernel_event_to_audit_action() {
655        let event = KernelEvent::AgentFailed {
656            id: AgentId::new_v4(),
657            error: "boom".to_string(),
658        };
659        let action = kernel_event_to_audit_action(&event);
660        match action {
661            AuditAction::AgentExit { reason } => assert_eq!(reason, "boom"),
662            other => panic!("expected AgentExit, got {other:?}"),
663        }
664    }
665
666    // ── RFC-015 chat transparency event coverage ──
667
668    /// Round-trip JSON serialization for every new RFC-015 variant. This
669    /// guards against accidental renames that would break the WebSocket
670    /// wire format on the frontend.
671    #[test]
672    fn test_rfc015_event_round_trip_json() {
673        let cases: Vec<KernelEvent> = vec![
674            KernelEvent::ToolExecutionStarted {
675                session_id: "s1".into(),
676                tool_name: "read_file".into(),
677                tool_call_id: "call_1".into(),
678                tool_args: serde_json::json!({"path": "/src/main.rs"}),
679                context: None,
680            },
681            KernelEvent::ToolExecutionFinished {
682                session_id: "s1".into(),
683                tool_call_id: "call_1".into(),
684                tool_name: "read_file".into(),
685                duration_ms: 234,
686                is_error: false,
687                output_summary: "fn main() {}".into(),
688            },
689            KernelEvent::ToolExecutionProgress {
690                session_id: "s1".into(),
691                tool_call_id: "call_1".into(),
692                tool_name: "read_file".into(),
693                progress: "reading line 42/100".into(),
694                tab_id: None,
695                context: None,
696            },
697            KernelEvent::MemoryRecallUsed {
698                session_id: "s1".into(),
699                query: "rust errors".into(),
700                count: 3,
701                source: "warm".into(),
702            },
703            KernelEvent::TokenUsageUpdate {
704                session_id: "s1".into(),
705                input_tokens: 1234,
706                output_tokens: 567,
707            },
708            KernelEvent::ReasoningFragment {
709                session_id: "s1".into(),
710                content: "compaction done".into(),
711                source: "compaction".into(),
712            },
713        ];
714        for event in cases {
715            let json = serde_json::to_string(&event).expect("serialize");
716            let back: KernelEvent = serde_json::from_str(&json).expect("deserialize");
717            let json2 = serde_json::to_string(&back).expect("serialize round-trip");
718            assert_eq!(json, json2, "round-trip should be stable");
719        }
720    }
721
722    /// Tool progress events serialize/deserialize cleanly and round-trip
723    /// stable JSON, matching the wire format the WS layer expects.
724    #[test]
725    fn test_tool_execution_progress_serde_round_trip() {
726        let event = KernelEvent::ToolExecutionProgress {
727            session_id: "s-abc".into(),
728            tool_call_id: "call_42".into(),
729            tool_name: "browse".into(),
730            progress: "loading https://example.com".into(),
731            tab_id: Some(Uuid::new_v4()),
732            context: None,
733        };
734        let json = serde_json::to_string(&event).expect("serialize");
735        let back: KernelEvent = serde_json::from_str(&json).expect("deserialize");
736        match back {
737            KernelEvent::ToolExecutionProgress {
738                ref session_id,
739                ref tool_call_id,
740                ref tool_name,
741                ref progress,
742                tab_id,
743                ..
744            } => {
745                assert_eq!(session_id, "s-abc");
746                assert_eq!(tool_call_id, "call_42");
747                assert_eq!(tool_name, "browse");
748                assert_eq!(progress, "loading https://example.com");
749                assert!(tab_id.is_some(), "tab_id should round-trip when present");
750            }
751            other => panic!("expected ToolExecutionProgress, got {other:?}"),
752        }
753    }
754
755    /// The audit-action mapping for tool progress should produce a stable,
756    /// searchable detail string (used by the audit-trail UI to filter).
757    /// When `tab_id` is set, the detail includes `:tab=<id>`; when absent,
758    /// the original `tool_progress:<tool>` form is preserved (back-compat
759    /// for older oxi-agent versions that don't propagate tabs).
760    #[test]
761    fn test_tool_execution_progress_audit_action() {
762        let with_tab = KernelEvent::ToolExecutionProgress {
763            session_id: "s1".into(),
764            tool_call_id: "c1".into(),
765            tool_name: "browse".into(),
766            progress: "navigating".into(),
767            tab_id: Some(Uuid::new_v4()),
768            context: None,
769        };
770        match kernel_event_to_audit_action(&with_tab) {
771            AuditAction::Other { detail } => {
772                assert!(detail.contains("tool_progress"), "detail: {detail}");
773                assert!(detail.contains("browse"), "detail: {detail}");
774                assert!(
775                    detail.contains(":tab="),
776                    "detail should include tab id: {detail}"
777                );
778            }
779            other => panic!("expected Other, got {other:?}"),
780        }
781        let without_tab = KernelEvent::ToolExecutionProgress {
782            session_id: "s1".into(),
783            tool_call_id: "c1".into(),
784            tool_name: "browse".into(),
785            progress: "navigating".into(),
786            tab_id: None,
787            context: None,
788        };
789        match kernel_event_to_audit_action(&without_tab) {
790            AuditAction::Other { detail } => {
791                assert_eq!(detail, "tool_progress:browse");
792            }
793            other => panic!("expected Other, got {other:?}"),
794        }
795    }
796
797    /// `tab_id` is optional in serde (`#[serde(default)]`) so older oxi-agent
798    /// versions that don't emit it still round-trip cleanly. This guards the
799    /// backwards-compat contract explicitly.
800    #[test]
801    fn test_tool_execution_progress_tab_id_optional_in_serde() {
802        // Simulate a payload from a legacy oxi-agent (no tab_id key).
803        // KernelEvent is externally tagged, so the variant is the JSON key.
804        let legacy_json = r#"{
805            "ToolExecutionProgress": {
806                "session_id": "s-old",
807                "tool_call_id": "call_legacy",
808                "tool_name": "browse",
809                "progress": "step 1"
810            }
811        }"#;
812        let event: KernelEvent = serde_json::from_str(legacy_json).expect("deserialize legacy");
813        match &event {
814            KernelEvent::ToolExecutionProgress {
815                session_id,
816                tool_call_id,
817                tool_name,
818                progress,
819                tab_id,
820                ..
821            } => {
822                assert_eq!(session_id, "s-old");
823                assert_eq!(tool_call_id, "call_legacy");
824                assert_eq!(tool_name, "browse");
825                assert_eq!(progress, "step 1");
826                assert!(tab_id.is_none(), "missing field should default to None");
827            }
828            other => panic!("expected ToolExecutionProgress, got {other:?}"),
829        }
830        // And re-serialise — `skip_serializing_if = "Option::is_none"` keeps
831        // the wire format clean when downstream tools don't set tab_id.
832        let json = serde_json::to_string(&event).expect("serialize");
833        assert!(
834            !json.contains("tab_id"),
835            "tab_id should be omitted when None: {json}"
836        );
837    }
838
839    /// The agent_id extractor should map session-scoped RFC-015 events to
840    /// `session:<id>` for audit-trail grouping, while non-session events
841    /// keep their existing behaviour.
842    #[test]
843    fn test_rfc015_extract_agent_id() {
844        let event = KernelEvent::ToolExecutionStarted {
845            session_id: "abc-123".into(),
846            tool_name: "bash".into(),
847            tool_call_id: "c1".into(),
848            tool_args: serde_json::Value::Null,
849            context: None,
850        };
851        // The function is private; verify via the public AuditAction mapping
852        // that session-scoped events do not collide with real agent ids.
853        let action = kernel_event_to_audit_action(&event);
854        match action {
855            AuditAction::Other { detail } => {
856                assert!(
857                    detail.contains("bash"),
858                    "tool name in audit detail: {detail}"
859                );
860            }
861            other => panic!("expected Other, got {other:?}"),
862        }
863    }
864}