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    // ── Calendar ──────────────────────────────────────────────
240    /// A calendar event was created.
241    CalendarEventCreated {
242        /// Event UID.
243        uid: String,
244        /// Event title.
245        title: String,
246        /// Start time.
247        start: String,
248        /// End time.
249        end: String,
250    },
251    /// A calendar event was updated.
252    CalendarEventUpdated {
253        /// Event UID.
254        uid: String,
255        /// Event title.
256        title: String,
257    },
258    /// A calendar event was deleted.
259    CalendarEventDeleted {
260        /// Event UID.
261        uid: String,
262        /// Event title.
263        title: String,
264    },
265    /// An email has been sent.
266    EmailSent {
267        /// Email subject.
268        subject: String,
269        /// SMTP message ID.
270        message_id: String,
271        /// Template name (if template was used/saved).
272        #[serde(default, skip_serializing_if = "Option::is_none")]
273        template_name: Option<String>,
274    },
275
276    // ── Knowledge ──────────────────────────────────────────────
277    /// A knowledge note was persisted (hook, user, or tool).
278    KnowledgePersisted {
279        session_id: String,
280        message_index: usize,
281        path: String,
282        source: String, // "hook", "user", "tool"
283    },
284    /// A knowledge note was removed by user action.
285    KnowledgeRemoved {
286        session_id: String,
287        message_index: usize,
288    },
289    /// A question was posed to the user by the agent (RFC-027, `ask_user`).
290    /// The frontend renders an input/option picker and resolves the
291    /// pending oneshot via a separate response endpoint.
292    AskUserRequest {
293        /// Unique request ID — used by the response handler to resolve
294        /// the oneshot the tool is awaiting.
295        id: String,
296        /// The question text the user sees.
297        question: String,
298        /// Optional structured options. Empty when the question is open-ended.
299        options: Vec<String>,
300    },
301}
302
303/// Convert a KernelEvent to an AuditAction for the audit trail.
304pub fn kernel_event_to_audit_action(event: &KernelEvent) -> AuditAction {
305    match event {
306        KernelEvent::AgentCreated { name, .. } => AuditAction::AgentSpawn {
307            task_type: name.clone(),
308        },
309        KernelEvent::AgentStarted { .. } => AuditAction::AgentSpawn {
310            task_type: "started".to_string(),
311        },
312        KernelEvent::AgentStopped { success, .. } => AuditAction::AgentExit {
313            reason: if *success {
314                "completed".to_string()
315            } else {
316                "stopped".to_string()
317            },
318        },
319        KernelEvent::AgentFailed { error, .. } => AuditAction::AgentExit {
320            reason: error.clone(),
321        },
322        KernelEvent::MessageReceived { content, .. } => AuditAction::Other {
323            detail: format!("message: {content}"),
324        },
325        KernelEvent::AgentOutput { output, .. } => AuditAction::Other {
326            detail: format!("agent_output:{output}"),
327        },
328        KernelEvent::ApprovalRequested {
329            id,
330            action,
331            resource,
332            ..
333        } => AuditAction::Other {
334            detail: format!("approval_requested:{id}:{action}:{resource}"),
335        },
336        KernelEvent::ApprovalResolved { id, approved } => AuditAction::Other {
337            detail: format!("approval_resolved:{id}:{approved}"),
338        },
339        KernelEvent::MemoryStored {
340            id, memory_type, ..
341        } => AuditAction::MemoryWrite {
342            entry_id: format!("{id}:{memory_type}"),
343        },
344        KernelEvent::MemoryRecalled { query, count } => AuditAction::MemoryRead {
345            entry_id: format!("query:{query}:{count}results"),
346        },
347        KernelEvent::AgentGroupCreated {
348            group_id,
349            agent_count,
350        } => AuditAction::Other {
351            detail: format!("group_created:{group_id}:{agent_count}agents"),
352        },
353        KernelEvent::AgentGroupMemberCompleted {
354            group_id,
355            agent_id,
356            success,
357        } => AuditAction::Other {
358            detail: format!("group_member_completed:{group_id}:{agent_id}:{success}"),
359        },
360        KernelEvent::ProjectCreated {
361            project_id: _,
362            name,
363            source,
364        } => AuditAction::Other {
365            detail: format!("project_created:{name}:{source}"),
366        },
367        KernelEvent::ProjectActivated {
368            project_id: _,
369            name,
370        } => AuditAction::Other {
371            detail: format!("project_activated:{name}"),
372        },
373        // ── RFC-015 ──
374        KernelEvent::ToolExecutionStarted { tool_name, .. } => AuditAction::Other {
375            detail: format!("tool_started:{tool_name}"),
376        },
377        KernelEvent::ToolExecutionFinished {
378            tool_name,
379            is_error,
380            ..
381        } => AuditAction::Other {
382            detail: format!(
383                "tool_finished:{tool_name}:{}",
384                if *is_error { "error" } else { "ok" }
385            ),
386        },
387        KernelEvent::ToolExecutionProgress {
388            tool_name,
389            tab_id,
390            context,
391            ..
392        } => AuditAction::Other {
393            detail: {
394                let mut d = format!("tool_progress:{tool_name}");
395                if let Some(id) = tab_id {
396                    d.push_str(&format!(":tab={id}"));
397                }
398                if let Some(ctx) = context
399                    .as_ref()
400                    .and_then(|c| c.get("kind"))
401                    .and_then(|k| k.as_str())
402                {
403                    d.push_str(&format!(":{ctx}"));
404                }
405                d
406            },
407        },
408        KernelEvent::MemoryRecallUsed { query, count, .. } => AuditAction::MemoryRead {
409            entry_id: format!("recall:{query}:{count}results"),
410        },
411        KernelEvent::TokenUsageUpdate {
412            input_tokens,
413            output_tokens,
414            ..
415        } => AuditAction::Other {
416            detail: format!("tokens:in={input_tokens}:out={output_tokens}"),
417        },
418        KernelEvent::ReasoningFragment { source, .. } => AuditAction::Other {
419            detail: format!("reasoning:{source}"),
420        },
421        KernelEvent::CalendarEventCreated { uid, title, .. } => AuditAction::Other {
422            detail: format!("calendar:created:{uid}:{title}"),
423        },
424        KernelEvent::CalendarEventUpdated { uid, title } => AuditAction::Other {
425            detail: format!("calendar:updated:{uid}:{title}"),
426        },
427        KernelEvent::CalendarEventDeleted { uid, title } => AuditAction::Other {
428            detail: format!("calendar:deleted:{uid}:{title}"),
429        },
430        KernelEvent::EmailSent {
431            subject,
432            message_id,
433            template_name,
434        } => AuditAction::Other {
435            detail: format!("email:sent:{subject} (msg={message_id}, tpl={template_name:?})"),
436        },
437        KernelEvent::KnowledgePersisted {
438            session_id,
439            message_index,
440            path,
441            source,
442        } => AuditAction::Other {
443            detail: format!("knowledge:persisted:{session_id}:{message_index}:{path}:{source}"),
444        },
445        KernelEvent::KnowledgeRemoved {
446            session_id,
447            message_index,
448        } => AuditAction::Other {
449            detail: format!("knowledge:removed:{session_id}:{message_index}"),
450        },
451        KernelEvent::AskUserRequest { id, question, .. } => AuditAction::Other {
452            detail: format!("ask_user:{id}:{question}"),
453        },
454    }
455}
456
457/// Extract agent ID from a KernelEvent variant.
458fn extract_agent_id(event: &KernelEvent) -> String {
459    match event {
460        KernelEvent::AgentCreated { id, .. } => id.to_string(),
461        KernelEvent::AgentStarted { id, .. } => id.to_string(),
462        KernelEvent::AgentStopped { id, .. } => id.to_string(),
463        KernelEvent::AgentFailed { id, .. } => id.to_string(),
464        KernelEvent::MessageReceived { from, .. } => from.to_string(),
465        KernelEvent::AgentOutput { agent_id, .. } => agent_id.to_string(),
466        KernelEvent::AgentGroupMemberCompleted { agent_id, .. } => agent_id.to_string(),
467        KernelEvent::ProjectActivated { project_id, .. } => format!("project:{project_id}"),
468        // RFC-015: session-scoped events use session_id as the subject
469        KernelEvent::ToolExecutionStarted { session_id, .. } => format!("session:{session_id}"),
470        KernelEvent::ToolExecutionFinished { session_id, .. } => format!("session:{session_id}"),
471        KernelEvent::ToolExecutionProgress { session_id, .. } => format!("session:{session_id}"),
472        KernelEvent::MemoryRecallUsed { session_id, .. } => format!("session:{session_id}"),
473        KernelEvent::TokenUsageUpdate { session_id, .. } => format!("session:{session_id}"),
474        KernelEvent::ReasoningFragment { session_id, .. } => format!("session:{session_id}"),
475        KernelEvent::KnowledgePersisted { session_id, .. } => format!("session:{session_id}"),
476        KernelEvent::KnowledgeRemoved { session_id, .. } => format!("session:{session_id}"),
477        _ => "system".to_string(),
478    }
479}
480
481/// Subscribe the audit trail to all kernel events.
482///
483/// The bus is broadcast-based; this spawns a long-running task that
484/// forwards every event into the audit trail as a structured entry.
485/// Lagged subscribers are logged and recovered.
486pub fn attach_audit_trail(bus: &EventBus, audit: Arc<AuditTrail>) {
487    let mut rx = bus.subscribe();
488    tokio::spawn(async move {
489        loop {
490            match rx.recv().await {
491                Ok(event) => {
492                    let actor = extract_agent_id(&event);
493                    let action = kernel_event_to_audit_action(&event);
494                    let resource = format!("{event:?}");
495                    audit.append(actor, action, resource);
496                }
497                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
498                    // Surface the drop as a metric so operators can detect
499                    // incomplete audit trails instead of the events
500                    // vanishing silently (state-area F4).
501                    crate::metrics::get_metrics().audit_lagged_events.inc_by(n);
502                    tracing::warn!(
503                        skipped = n,
504                        "Audit trail subscriber lagged, skipping events"
505                    );
506                    continue;
507                }
508                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
509                    tracing::info!("Audit trail event bus closed, exiting");
510                    break;
511                }
512            }
513        }
514    });
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520
521    fn sample_event(name: &str) -> KernelEvent {
522        KernelEvent::AgentCreated {
523            id: AgentId::new_v4(),
524            name: name.to_string(),
525        }
526    }
527
528    #[test]
529    fn test_event_bus_uses_sdk() {
530        let bus: EventBus = EventBus::new(256);
531        assert!(format!("{:?}", bus).contains("EventBus"));
532    }
533
534    #[tokio::test]
535    async fn test_publish_no_subscribers_ok() {
536        let bus = EventBus::new(16);
537        let result = bus.publish(sample_event("orphan"));
538        assert!(result.is_ok());
539    }
540
541    #[tokio::test]
542    async fn test_single_subscriber_receives_event() {
543        let bus = EventBus::new(16);
544        let mut rx = bus.subscribe();
545
546        let event = sample_event("test-agent");
547        bus.publish(event.clone()).unwrap();
548
549        let received = rx.try_recv().expect("should receive event");
550        match received {
551            KernelEvent::AgentCreated { name, .. } => assert_eq!(name, "test-agent"),
552            _ => panic!("wrong event type"),
553        }
554    }
555
556    #[tokio::test]
557    async fn test_multiple_subscribers_receive_events() {
558        let bus = EventBus::new(16);
559        let mut rx1 = bus.subscribe();
560        let mut rx2 = bus.subscribe();
561
562        let event = sample_event("multi");
563        bus.publish(event.clone()).unwrap();
564
565        let r1 = rx1.try_recv().expect("rx1 should receive event");
566        let r2 = rx2.try_recv().expect("rx2 should receive event");
567
568        assert!(matches!(r1, KernelEvent::AgentCreated { .. }));
569        assert!(matches!(r2, KernelEvent::AgentCreated { .. }));
570    }
571
572    #[tokio::test]
573    async fn test_kernel_event_to_audit_action() {
574        let event = KernelEvent::AgentFailed {
575            id: AgentId::new_v4(),
576            error: "boom".to_string(),
577        };
578        let action = kernel_event_to_audit_action(&event);
579        match action {
580            AuditAction::AgentExit { reason } => assert_eq!(reason, "boom"),
581            other => panic!("expected AgentExit, got {other:?}"),
582        }
583    }
584
585    // ── RFC-015 chat transparency event coverage ──
586
587    /// Round-trip JSON serialization for every new RFC-015 variant. This
588    /// guards against accidental renames that would break the WebSocket
589    /// wire format on the frontend.
590    #[test]
591    fn test_rfc015_event_round_trip_json() {
592        let cases: Vec<KernelEvent> = vec![
593            KernelEvent::ToolExecutionStarted {
594                session_id: "s1".into(),
595                tool_name: "read_file".into(),
596                tool_call_id: "call_1".into(),
597                tool_args: serde_json::json!({"path": "/src/main.rs"}),
598                context: None,
599            },
600            KernelEvent::ToolExecutionFinished {
601                session_id: "s1".into(),
602                tool_call_id: "call_1".into(),
603                tool_name: "read_file".into(),
604                duration_ms: 234,
605                is_error: false,
606                output_summary: "fn main() {}".into(),
607            },
608            KernelEvent::ToolExecutionProgress {
609                session_id: "s1".into(),
610                tool_call_id: "call_1".into(),
611                tool_name: "read_file".into(),
612                progress: "reading line 42/100".into(),
613                tab_id: None,
614                context: None,
615            },
616            KernelEvent::MemoryRecallUsed {
617                session_id: "s1".into(),
618                query: "rust errors".into(),
619                count: 3,
620                source: "warm".into(),
621            },
622            KernelEvent::TokenUsageUpdate {
623                session_id: "s1".into(),
624                input_tokens: 1234,
625                output_tokens: 567,
626            },
627            KernelEvent::ReasoningFragment {
628                session_id: "s1".into(),
629                content: "compaction done".into(),
630                source: "compaction".into(),
631            },
632        ];
633        for event in cases {
634            let json = serde_json::to_string(&event).expect("serialize");
635            let back: KernelEvent = serde_json::from_str(&json).expect("deserialize");
636            let json2 = serde_json::to_string(&back).expect("serialize round-trip");
637            assert_eq!(json, json2, "round-trip should be stable");
638        }
639    }
640
641    /// Tool progress events serialize/deserialize cleanly and round-trip
642    /// stable JSON, matching the wire format the WS layer expects.
643    #[test]
644    fn test_tool_execution_progress_serde_round_trip() {
645        let event = KernelEvent::ToolExecutionProgress {
646            session_id: "s-abc".into(),
647            tool_call_id: "call_42".into(),
648            tool_name: "browse".into(),
649            progress: "loading https://example.com".into(),
650            tab_id: Some(Uuid::new_v4()),
651            context: None,
652        };
653        let json = serde_json::to_string(&event).expect("serialize");
654        let back: KernelEvent = serde_json::from_str(&json).expect("deserialize");
655        match back {
656            KernelEvent::ToolExecutionProgress {
657                ref session_id,
658                ref tool_call_id,
659                ref tool_name,
660                ref progress,
661                tab_id,
662                ..
663            } => {
664                assert_eq!(session_id, "s-abc");
665                assert_eq!(tool_call_id, "call_42");
666                assert_eq!(tool_name, "browse");
667                assert_eq!(progress, "loading https://example.com");
668                assert!(tab_id.is_some(), "tab_id should round-trip when present");
669            }
670            other => panic!("expected ToolExecutionProgress, got {other:?}"),
671        }
672    }
673
674    /// The audit-action mapping for tool progress should produce a stable,
675    /// searchable detail string (used by the audit-trail UI to filter).
676    /// When `tab_id` is set, the detail includes `:tab=<id>`; when absent,
677    /// the original `tool_progress:<tool>` form is preserved (back-compat
678    /// for older oxi-agent versions that don't propagate tabs).
679    #[test]
680    fn test_tool_execution_progress_audit_action() {
681        let with_tab = KernelEvent::ToolExecutionProgress {
682            session_id: "s1".into(),
683            tool_call_id: "c1".into(),
684            tool_name: "browse".into(),
685            progress: "navigating".into(),
686            tab_id: Some(Uuid::new_v4()),
687            context: None,
688        };
689        match kernel_event_to_audit_action(&with_tab) {
690            AuditAction::Other { detail } => {
691                assert!(detail.contains("tool_progress"), "detail: {detail}");
692                assert!(detail.contains("browse"), "detail: {detail}");
693                assert!(
694                    detail.contains(":tab="),
695                    "detail should include tab id: {detail}"
696                );
697            }
698            other => panic!("expected Other, got {other:?}"),
699        }
700        let without_tab = KernelEvent::ToolExecutionProgress {
701            session_id: "s1".into(),
702            tool_call_id: "c1".into(),
703            tool_name: "browse".into(),
704            progress: "navigating".into(),
705            tab_id: None,
706            context: None,
707        };
708        match kernel_event_to_audit_action(&without_tab) {
709            AuditAction::Other { detail } => {
710                assert_eq!(detail, "tool_progress:browse");
711            }
712            other => panic!("expected Other, got {other:?}"),
713        }
714    }
715
716    /// `tab_id` is optional in serde (`#[serde(default)]`) so older oxi-agent
717    /// versions that don't emit it still round-trip cleanly. This guards the
718    /// backwards-compat contract explicitly.
719    #[test]
720    fn test_tool_execution_progress_tab_id_optional_in_serde() {
721        // Simulate a payload from a legacy oxi-agent (no tab_id key).
722        // KernelEvent is externally tagged, so the variant is the JSON key.
723        let legacy_json = r#"{
724            "ToolExecutionProgress": {
725                "session_id": "s-old",
726                "tool_call_id": "call_legacy",
727                "tool_name": "browse",
728                "progress": "step 1"
729            }
730        }"#;
731        let event: KernelEvent = serde_json::from_str(legacy_json).expect("deserialize legacy");
732        match &event {
733            KernelEvent::ToolExecutionProgress {
734                session_id,
735                tool_call_id,
736                tool_name,
737                progress,
738                tab_id,
739                ..
740            } => {
741                assert_eq!(session_id, "s-old");
742                assert_eq!(tool_call_id, "call_legacy");
743                assert_eq!(tool_name, "browse");
744                assert_eq!(progress, "step 1");
745                assert!(tab_id.is_none(), "missing field should default to None");
746            }
747            other => panic!("expected ToolExecutionProgress, got {other:?}"),
748        }
749        // And re-serialise — `skip_serializing_if = "Option::is_none"` keeps
750        // the wire format clean when downstream tools don't set tab_id.
751        let json = serde_json::to_string(&event).expect("serialize");
752        assert!(
753            !json.contains("tab_id"),
754            "tab_id should be omitted when None: {json}"
755        );
756    }
757
758    /// The agent_id extractor should map session-scoped RFC-015 events to
759    /// `session:<id>` for audit-trail grouping, while non-session events
760    /// keep their existing behaviour.
761    #[test]
762    fn test_rfc015_extract_agent_id() {
763        let event = KernelEvent::ToolExecutionStarted {
764            session_id: "abc-123".into(),
765            tool_name: "bash".into(),
766            tool_call_id: "c1".into(),
767            tool_args: serde_json::Value::Null,
768            context: None,
769        };
770        // The function is private; verify via the public AuditAction mapping
771        // that session-scoped events do not collide with real agent ids.
772        let action = kernel_event_to_audit_action(&event);
773        match action {
774            AuditAction::Other { detail } => {
775                assert!(
776                    detail.contains("bash"),
777                    "tool name in audit detail: {detail}"
778                );
779            }
780            other => panic!("expected Other, got {other:?}"),
781        }
782    }
783}