Skip to main content

lean_ctx/core/
ocla_bus.rs

1//! OCLA Event Bus (P2 / Track B — Event-Backbone).
2//!
3//! Zero-cost when disabled: a single `AtomicBool` check (< 5ns) gates all
4//! emission. When enabled, events flow into the existing `core::events` ring
5//! buffer and JSONL persistence.
6//!
7//! ## Design principles
8//!
9//! - **Wrap, don't replace**: The existing `events.rs` infrastructure (ring
10//!   buffer, JSONL rotation, persistence) is used as-is. `OclaBus` adds the
11//!   OCLA semantic layer on top.
12//! - **10 event types**: 5 existing (wired to current code) + 5 new (for
13//!   P8/P9/P11 traits, wired as those modules integrate).
14//! - **Test isolation**: `OclaBus::scoped(capacity)` creates a bus instance
15//!   that does NOT touch the global singleton, enabling parallel tests.
16//! - **Determinism**: Event IDs come from the existing sequence allocator.
17//!   Timestamps are the only non-deterministic field (acceptable for
18//!   observability; not included in contract assertions).
19
20use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
21use std::sync::{Mutex, OnceLock};
22
23use serde::{Deserialize, Serialize};
24
25use crate::core::context_kernel::bounded::BoundedQueue;
26
27// ─── OCLA Event Types ────────────────────────────────────────────────────────
28
29/// The 10 OCLA event types defined in the P2 spec.
30#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
31#[serde(tag = "type")]
32pub enum OclaEvent {
33    /// A proxy request completed (usage_meter.rs).
34    RequestCompleted {
35        model: String,
36        input_tokens: u64,
37        output_tokens: u64,
38        duration_ms: u64,
39        session_id: Option<String>,
40    },
41    /// User feedback recorded (feedback.rs).
42    FeedbackRecorded {
43        session_id: String,
44        outcome: FeedbackOutcome,
45        tool: Option<String>,
46    },
47    /// Compression threshold shifted (threshold_learning.rs).
48    ThresholdShift {
49        language: String,
50        old_value: f64,
51        new_value: f64,
52        metric: ThresholdMetric,
53    },
54    /// Compression applied to a request (compress.rs).
55    CompressionApplied {
56        path: Option<String>,
57        before_tokens: u64,
58        after_tokens: u64,
59        strategy: String,
60    },
61    /// Savings recorded to the ledger (savings_ledger/store.rs).
62    SavingsRecorded {
63        input_saved: u64,
64        output_saved: u64,
65        source: SavingsSource,
66        attribution_id: Option<String>,
67        evidence_class: Option<String>,
68        measurement_method: Option<String>,
69    },
70    /// Intent classified for a request (P8 — model_router.rs).
71    IntentClassified {
72        tier: String,
73        confidence: f64,
74        reasoning: String,
75    },
76    /// Outcome tracked for a response (P3 — future outcome_tracker.rs).
77    OutcomeRecorded {
78        session_id: String,
79        accepted: bool,
80        implicit: bool,
81    },
82    /// Response optimization applied (P9 — response_optimizer.rs).
83    ResponseOptimized {
84        cache_hit: bool,
85        is_duplicate: bool,
86        tokens_saved: u64,
87    },
88    /// Model routing decision made (P8 — model_router.rs).
89    ModelRouted {
90        requested_model: String,
91        routed_model: String,
92        tier: String,
93        model_changed: bool,
94    },
95    /// Agent chain event (P11 — future agent_gateway.rs).
96    AgentChainEvent {
97        agent_id: String,
98        action: String,
99        parent_agent: Option<String>,
100    },
101    /// Cross-agent stub served instead of full read (delivery_registry.rs).
102    CrossAgentStubServed {
103        path: String,
104        tokens_saved: u64,
105        serving_agent: String,
106        original_agent: String,
107    },
108}
109
110/// Feedback outcome enum.
111#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
112#[serde(rename_all = "snake_case")]
113pub enum FeedbackOutcome {
114    Accept,
115    Reject,
116    Partial,
117}
118
119/// Threshold metric that shifted.
120#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
121#[serde(rename_all = "snake_case")]
122pub enum ThresholdMetric {
123    Entropy,
124    Jaccard,
125}
126
127/// Source of savings.
128#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
129#[serde(rename_all = "snake_case")]
130pub enum SavingsSource {
131    Compression,
132    Cache,
133    Routing,
134    Verbosity,
135    ResponseCache,
136}
137
138// ─── Bus Record ──────────────────────────────────────────────────────────────
139
140/// A timestamped OCLA event in the bus ring buffer.
141#[derive(Clone, Debug, Serialize, Deserialize)]
142pub struct OclaBusRecord {
143    pub id: u64,
144    pub timestamp_ms: u64,
145    pub event: OclaEvent,
146}
147
148/// Policy applied when the OCLA bus reaches its configured capacity.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum OverflowPolicy {
152    /// Retain the new event and evict the oldest queued event.
153    DropOldest,
154    /// Retain queued events and reject the new event.
155    DropNewest,
156    /// Warn and reject the new event because this synchronous bus cannot block.
157    Backpressure,
158}
159
160impl OverflowPolicy {
161    fn from_env() -> Self {
162        match std::env::var("LEANCTX_BUS_OVERFLOW").as_deref() {
163            Ok("drop_newest") => Self::DropNewest,
164            Ok("backpressure") => Self::Backpressure,
165            Ok("drop_oldest") | Err(_) => Self::DropOldest,
166            Ok(value) => {
167                tracing::warn!(
168                    value,
169                    "invalid LEANCTX_BUS_OVERFLOW value; using drop_oldest"
170                );
171                Self::DropOldest
172            }
173        }
174    }
175}
176
177/// Details recorded whenever an event cannot be retained without overflow.
178#[derive(Debug, Clone)]
179pub struct OverflowEvent {
180    /// Policy active when the overflow occurred.
181    pub policy: OverflowPolicy,
182    /// Number of overflows observed by this bus since creation.
183    pub dropped_count: usize,
184    /// Maximum number of events retained by the queue.
185    pub queue_capacity: usize,
186}
187
188// ─── OclaBus ─────────────────────────────────────────────────────────────────
189
190/// The OCLA event bus. Zero-cost when disabled.
191///
192/// Global usage: `ocla_bus::emit(event)` — checks the global enable flag first.
193/// Test usage: `OclaBus::scoped(cap)` — isolated instance, no global state.
194pub struct OclaBus {
195    enabled: AtomicBool,
196    ring: Mutex<BoundedQueue<OclaBusRecord>>,
197    capacity: usize,
198    next_id: AtomicU64,
199    overflow_policy: OverflowPolicy,
200    overflow_count: AtomicUsize,
201}
202
203impl OclaBus {
204    /// Create a new bus with the given ring buffer capacity.
205    fn new(capacity: usize) -> Self {
206        Self::new_with_policy(capacity, OverflowPolicy::from_env())
207    }
208
209    fn new_with_policy(capacity: usize, overflow_policy: OverflowPolicy) -> Self {
210        Self {
211            enabled: AtomicBool::new(false),
212            ring: Mutex::new(BoundedQueue::new(capacity)),
213            capacity,
214            next_id: AtomicU64::new(1),
215            overflow_policy,
216            overflow_count: AtomicUsize::new(0),
217        }
218    }
219
220    /// Create a scoped (isolated) bus for testing. Does NOT affect the global bus.
221    pub fn scoped(capacity: usize) -> Self {
222        let bus = Self::new_with_policy(capacity, OverflowPolicy::DropOldest);
223        bus.enabled.store(true, Ordering::Relaxed);
224        bus
225    }
226
227    #[cfg(test)]
228    fn scoped_with_policy(capacity: usize, overflow_policy: OverflowPolicy) -> Self {
229        let bus = Self::new_with_policy(capacity, overflow_policy);
230        bus.enabled.store(true, Ordering::Relaxed);
231        bus
232    }
233
234    /// Enable the bus. Events will be recorded after this call.
235    pub fn enable(&self) {
236        self.enabled.store(true, Ordering::Release);
237    }
238
239    /// Disable the bus. Events will be discarded (< 5ns per call).
240    pub fn disable(&self) {
241        self.enabled.store(false, Ordering::Release);
242    }
243
244    /// Check if the bus is enabled.
245    #[inline]
246    pub fn is_enabled(&self) -> bool {
247        self.enabled.load(Ordering::Acquire)
248    }
249
250    /// Emit an event if the bus is enabled. Returns the event ID, or 0 if disabled.
251    #[inline]
252    pub fn emit_if_enabled(&self, event: OclaEvent) -> u64 {
253        if !self.is_enabled() {
254            return 0;
255        }
256        self.emit_unconditional(event)
257    }
258
259    /// Emit unconditionally (skips the enable check). Used internally and by
260    /// callers who have already verified the bus is enabled.
261    fn emit_unconditional(&self, event: OclaEvent) -> u64 {
262        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
263        let record = OclaBusRecord {
264            id,
265            timestamp_ms: current_timestamp_ms(),
266            event,
267        };
268
269        let mut ring = self
270            .ring
271            .lock()
272            .unwrap_or_else(std::sync::PoisonError::into_inner);
273        let _dropped = if ring.is_full() {
274            let dropped_count = self.overflow_count.fetch_add(1, Ordering::Relaxed) + 1;
275            let overflow = OverflowEvent {
276                policy: self.overflow_policy,
277                dropped_count,
278                queue_capacity: self.capacity,
279            };
280
281            match self.overflow_policy {
282                OverflowPolicy::DropOldest => ring.push(record),
283                OverflowPolicy::DropNewest => Some(record),
284                OverflowPolicy::Backpressure => {
285                    tracing::warn!(
286                        dropped_count = overflow.dropped_count,
287                        queue_capacity = overflow.queue_capacity,
288                        "OCLA bus backpressure requested; dropping newest event"
289                    );
290                    Some(record)
291                }
292            }
293        } else {
294            ring.push(record)
295        };
296
297        id
298    }
299
300    /// Drain all events from the ring (consumes them). Useful for test assertions.
301    pub fn drain(&self) -> Vec<OclaBusRecord> {
302        let mut ring = self
303            .ring
304            .lock()
305            .unwrap_or_else(std::sync::PoisonError::into_inner);
306        let count = ring.len();
307        ring.drain_oldest(count)
308    }
309
310    /// Read events since a given ID (non-consuming).
311    pub fn events_since(&self, after_id: u64) -> Vec<OclaBusRecord> {
312        let ring = self
313            .ring
314            .lock()
315            .unwrap_or_else(std::sync::PoisonError::into_inner);
316        ring.iter().filter(|r| r.id > after_id).cloned().collect()
317    }
318
319    /// Read the last N events.
320    pub fn latest(&self, n: usize) -> Vec<OclaBusRecord> {
321        let ring = self
322            .ring
323            .lock()
324            .unwrap_or_else(std::sync::PoisonError::into_inner);
325        let start = ring.len().saturating_sub(n);
326        ring.iter().skip(start).cloned().collect()
327    }
328
329    /// Current ring buffer occupancy.
330    pub fn len(&self) -> usize {
331        self.ring
332            .lock()
333            .unwrap_or_else(std::sync::PoisonError::into_inner)
334            .len()
335    }
336
337    /// Whether the ring is empty.
338    pub fn is_empty(&self) -> bool {
339        self.len() == 0
340    }
341
342    /// Total events emitted (including those evicted from the ring).
343    pub fn total_emitted(&self) -> u64 {
344        self.next_id.load(Ordering::Relaxed) - 1
345    }
346
347    /// Total queue overflows observed by this bus since creation.
348    pub fn overflow_count(&self) -> usize {
349        self.overflow_count.load(Ordering::Relaxed)
350    }
351
352    /// Overflow policy active for this bus.
353    pub fn overflow_policy(&self) -> OverflowPolicy {
354        self.overflow_policy
355    }
356}
357
358impl std::fmt::Debug for OclaBus {
359    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360        let ring_len = self.ring.lock().map_or(0, |r| r.len());
361        f.debug_struct("OclaBus")
362            .field("enabled", &self.is_enabled())
363            .field("ring", &format_args!("[{ring_len} events]"))
364            .field("capacity", &self.capacity)
365            .field("next_id", &self.next_id.load(Ordering::Relaxed))
366            .field("overflow_policy", &self.overflow_policy)
367            .field("overflow_count", &self.overflow_count())
368            .finish()
369    }
370}
371
372// ─── Global singleton ────────────────────────────────────────────────────────
373
374const DEFAULT_CAPACITY: usize = 1000;
375
376fn global_bus() -> &'static OclaBus {
377    static INSTANCE: OnceLock<OclaBus> = OnceLock::new();
378    INSTANCE.get_or_init(|| OclaBus::new(DEFAULT_CAPACITY))
379}
380
381/// Emit an OCLA event on the global bus. No-op (< 5ns) when disabled.
382#[inline]
383pub fn emit(event: OclaEvent) -> u64 {
384    global_bus().emit_if_enabled(event)
385}
386
387/// Enable the global OCLA bus.
388pub fn enable() {
389    global_bus().enable();
390}
391
392/// Disable the global OCLA bus.
393pub fn disable() {
394    global_bus().disable();
395}
396
397/// Check if the global OCLA bus is enabled.
398#[inline]
399pub fn is_enabled() -> bool {
400    global_bus().is_enabled()
401}
402
403/// Read events since a given ID from the global bus.
404pub fn events_since(after_id: u64) -> Vec<OclaBusRecord> {
405    global_bus().events_since(after_id)
406}
407
408/// Read the last N events from the global bus.
409pub fn latest(n: usize) -> Vec<OclaBusRecord> {
410    global_bus().latest(n)
411}
412
413/// Total events emitted on the global bus.
414pub fn total_emitted() -> u64 {
415    global_bus().total_emitted()
416}
417
418/// Total queue overflows observed by the global bus since startup.
419pub fn overflow_count() -> usize {
420    global_bus().overflow_count()
421}
422
423/// Overflow policy active for the global bus.
424pub fn overflow_policy() -> OverflowPolicy {
425    global_bus().overflow_policy()
426}
427
428// ─── Bridge to existing events.rs ────────────────────────────────────────────
429
430/// Bridge: emit an OCLA event AND forward it to the existing events.rs system.
431/// This ensures backward compatibility — the dashboard, CLI, and JSONL all
432/// continue to see events through the legacy path.
433pub fn emit_and_bridge(event: OclaEvent) -> u64 {
434    bridge_to_legacy(&event);
435    emit(event)
436}
437
438/// Convert an OCLA event to a legacy EventKind and emit it.
439fn bridge_to_legacy(event: &OclaEvent) {
440    use super::events::{EventKind, emit as legacy_emit};
441
442    let kind = match event {
443        OclaEvent::CompressionApplied {
444            path,
445            before_tokens,
446            after_tokens,
447            strategy,
448        } => EventKind::Compression {
449            path: path.clone().unwrap_or_default(),
450            before_lines: *before_tokens as u32,
451            after_lines: *after_tokens as u32,
452            strategy: strategy.clone(),
453            kept_line_count: *after_tokens as u32,
454            removed_line_count: before_tokens.saturating_sub(*after_tokens) as u32,
455        },
456        OclaEvent::ThresholdShift {
457            language,
458            old_value,
459            new_value,
460            metric,
461        } => EventKind::ThresholdShift {
462            language: language.clone(),
463            old_entropy: if *metric == ThresholdMetric::Entropy {
464                *old_value
465            } else {
466                0.0
467            },
468            new_entropy: if *metric == ThresholdMetric::Entropy {
469                *new_value
470            } else {
471                0.0
472            },
473            old_jaccard: if *metric == ThresholdMetric::Jaccard {
474                *old_value
475            } else {
476                0.0
477            },
478            new_jaccard: if *metric == ThresholdMetric::Jaccard {
479                *new_value
480            } else {
481                0.0
482            },
483        },
484        OclaEvent::RequestCompleted { .. }
485        | OclaEvent::FeedbackRecorded { .. }
486        | OclaEvent::SavingsRecorded { .. }
487        | OclaEvent::IntentClassified { .. }
488        | OclaEvent::OutcomeRecorded { .. }
489        | OclaEvent::ResponseOptimized { .. }
490        | OclaEvent::ModelRouted { .. }
491        | OclaEvent::AgentChainEvent { .. }
492        | OclaEvent::CrossAgentStubServed { .. } => {
493            return;
494        }
495    };
496
497    legacy_emit(kind);
498}
499
500// ─── Helpers ─────────────────────────────────────────────────────────────────
501
502fn current_timestamp_ms() -> u64 {
503    use std::time::{SystemTime, UNIX_EPOCH};
504    SystemTime::now()
505        .duration_since(UNIX_EPOCH)
506        .unwrap_or_default()
507        .as_millis() as u64
508}
509
510// ─── Tests ───────────────────────────────────────────────────────────────────
511
512#[cfg(test)]
513pub mod tests {
514    use super::*;
515
516    fn savings_event(input_saved: u64) -> OclaEvent {
517        OclaEvent::SavingsRecorded {
518            input_saved,
519            output_saved: 0,
520            source: SavingsSource::Compression,
521            attribution_id: None,
522            evidence_class: None,
523            measurement_method: None,
524        }
525    }
526
527    #[test]
528    fn disabled_bus_returns_zero() {
529        let bus = OclaBus::new(16);
530        assert!(!bus.is_enabled());
531        let id = bus.emit_if_enabled(OclaEvent::RequestCompleted {
532            model: "gpt-4o".into(),
533            input_tokens: 100,
534            output_tokens: 50,
535            duration_ms: 200,
536            session_id: None,
537        });
538        assert_eq!(id, 0);
539        assert!(bus.is_empty());
540    }
541
542    #[test]
543    fn enabled_bus_records_events() {
544        let bus = OclaBus::scoped(16);
545        let id = bus.emit_if_enabled(OclaEvent::ModelRouted {
546            requested_model: "gpt-4o".into(),
547            routed_model: "gpt-4o-mini".into(),
548            tier: "fast".into(),
549            model_changed: true,
550        });
551        assert!(id > 0);
552        assert_eq!(bus.len(), 1);
553    }
554
555    #[test]
556    fn scoped_bus_is_isolated() {
557        let bus1 = OclaBus::scoped(8);
558        let bus2 = OclaBus::scoped(8);
559
560        bus1.emit_if_enabled(OclaEvent::ResponseOptimized {
561            cache_hit: true,
562            is_duplicate: false,
563            tokens_saved: 42,
564        });
565
566        assert_eq!(bus1.len(), 1);
567        assert_eq!(bus2.len(), 0, "scoped buses are isolated");
568    }
569
570    #[test]
571    fn test_bounded_queue_replaces_vecdeque() {
572        let bus = OclaBus::scoped(2);
573        bus.emit_if_enabled(savings_event(1));
574        bus.emit_if_enabled(savings_event(2));
575
576        assert_eq!(bus.len(), 2);
577        assert_eq!(bus.drain().len(), 2);
578        assert!(bus.is_empty());
579    }
580
581    #[test]
582    fn test_overflow_drop_oldest() {
583        let bus = OclaBus::scoped_with_policy(3, OverflowPolicy::DropOldest);
584        let id1 = bus.emit_if_enabled(OclaEvent::SavingsRecorded {
585            input_saved: 10,
586            output_saved: 5,
587            source: SavingsSource::Compression,
588            attribution_id: None,
589            evidence_class: None,
590            measurement_method: None,
591        });
592        bus.emit_if_enabled(OclaEvent::SavingsRecorded {
593            input_saved: 20,
594            output_saved: 10,
595            source: SavingsSource::Cache,
596            attribution_id: None,
597            evidence_class: None,
598            measurement_method: None,
599        });
600        bus.emit_if_enabled(OclaEvent::SavingsRecorded {
601            input_saved: 30,
602            output_saved: 15,
603            source: SavingsSource::Routing,
604            attribution_id: None,
605            evidence_class: None,
606            measurement_method: None,
607        });
608        // At capacity. Next emit evicts oldest.
609        bus.emit_if_enabled(OclaEvent::SavingsRecorded {
610            input_saved: 40,
611            output_saved: 20,
612            source: SavingsSource::Verbosity,
613            attribution_id: None,
614            evidence_class: None,
615            measurement_method: None,
616        });
617
618        assert_eq!(bus.len(), 3);
619        let events = bus.events_since(0);
620        assert!(events.iter().all(|r| r.id > id1), "oldest evicted");
621    }
622
623    #[test]
624    fn test_overflow_drop_newest() {
625        let bus = OclaBus::scoped_with_policy(2, OverflowPolicy::DropNewest);
626        bus.emit_if_enabled(savings_event(1));
627        bus.emit_if_enabled(savings_event(2));
628        let rejected_id = bus.emit_if_enabled(savings_event(3));
629
630        let retained_ids = bus
631            .events_since(0)
632            .into_iter()
633            .map(|record| record.id)
634            .collect::<Vec<_>>();
635        assert_eq!(retained_ids, vec![1, 2]);
636        assert_eq!(rejected_id, 3);
637    }
638
639    #[test]
640    fn test_overflow_metrics() {
641        let bus = OclaBus::scoped_with_policy(1, OverflowPolicy::DropNewest);
642        bus.emit_if_enabled(savings_event(1));
643        bus.emit_if_enabled(savings_event(2));
644        bus.emit_if_enabled(savings_event(3));
645
646        assert_eq!(bus.overflow_count(), 2);
647        assert_eq!(bus.overflow_policy(), OverflowPolicy::DropNewest);
648    }
649
650    #[test]
651    fn test_overflow_policy_from_env() {
652        let _env_lock = crate::core::data_dir::test_env_lock();
653        let previous = std::env::var_os("LEANCTX_BUS_OVERFLOW");
654        crate::test_env::set_var("LEANCTX_BUS_OVERFLOW", "backpressure");
655
656        let bus = OclaBus::new(1);
657        assert_eq!(bus.overflow_policy(), OverflowPolicy::Backpressure);
658
659        if let Some(value) = previous {
660            crate::test_env::set_var("LEANCTX_BUS_OVERFLOW", value);
661        } else {
662            crate::test_env::remove_var("LEANCTX_BUS_OVERFLOW");
663        }
664    }
665
666    #[test]
667    fn drain_consumes_all_events() {
668        let bus = OclaBus::scoped(16);
669        bus.emit_if_enabled(OclaEvent::IntentClassified {
670            tier: "fast".into(),
671            confidence: 0.9,
672            reasoning: "simple query".into(),
673        });
674        bus.emit_if_enabled(OclaEvent::IntentClassified {
675            tier: "premium".into(),
676            confidence: 0.8,
677            reasoning: "complex architecture".into(),
678        });
679
680        let drained = bus.drain();
681        assert_eq!(drained.len(), 2);
682        assert!(bus.is_empty(), "drain consumes events");
683    }
684
685    #[test]
686    fn events_since_filters_by_id() {
687        let bus = OclaBus::scoped(16);
688        let id1 = bus.emit_if_enabled(OclaEvent::FeedbackRecorded {
689            session_id: "s1".into(),
690            outcome: FeedbackOutcome::Accept,
691            tool: Some("ctx_read".into()),
692        });
693        let id2 = bus.emit_if_enabled(OclaEvent::FeedbackRecorded {
694            session_id: "s2".into(),
695            outcome: FeedbackOutcome::Reject,
696            tool: None,
697        });
698
699        let after = bus.events_since(id1);
700        assert_eq!(after.len(), 1);
701        assert_eq!(after[0].id, id2);
702    }
703
704    #[test]
705    fn latest_returns_tail() {
706        let bus = OclaBus::scoped(16);
707        for i in 0..5 {
708            bus.emit_if_enabled(OclaEvent::CompressionApplied {
709                path: Some(format!("file_{i}.rs")),
710                before_tokens: 100,
711                after_tokens: 50,
712                strategy: "treesitter".into(),
713            });
714        }
715
716        let tail = bus.latest(2);
717        assert_eq!(tail.len(), 2);
718        assert_eq!(tail[0].id, 4);
719        assert_eq!(tail[1].id, 5);
720    }
721
722    #[test]
723    fn enable_disable_toggle() {
724        let bus = OclaBus::new(16);
725        assert!(!bus.is_enabled());
726
727        bus.enable();
728        assert!(bus.is_enabled());
729        let id = bus.emit_if_enabled(OclaEvent::AgentChainEvent {
730            agent_id: "a1".into(),
731            action: "start".into(),
732            parent_agent: None,
733        });
734        assert!(id > 0);
735
736        bus.disable();
737        let id2 = bus.emit_if_enabled(OclaEvent::AgentChainEvent {
738            agent_id: "a2".into(),
739            action: "stop".into(),
740            parent_agent: Some("a1".into()),
741        });
742        assert_eq!(id2, 0);
743        assert_eq!(bus.len(), 1, "disabled emit is a no-op");
744    }
745
746    #[test]
747    fn total_emitted_counts_all() {
748        let bus = OclaBus::scoped(3);
749        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
750            session_id: "s1".into(),
751            accepted: true,
752            implicit: false,
753        });
754        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
755            session_id: "s2".into(),
756            accepted: false,
757            implicit: true,
758        });
759        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
760            session_id: "s3".into(),
761            accepted: true,
762            implicit: true,
763        });
764        // Emit one more (evicts first).
765        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
766            session_id: "s4".into(),
767            accepted: true,
768            implicit: false,
769        });
770
771        assert_eq!(bus.total_emitted(), 4, "counts all, even evicted");
772        assert_eq!(bus.len(), 3, "ring only holds capacity");
773    }
774
775    #[test]
776    fn event_serialization_roundtrip() {
777        let event = OclaEvent::ModelRouted {
778            requested_model: "claude-sonnet-4-20250514".into(),
779            routed_model: "claude-haiku-3".into(),
780            tier: "fast".into(),
781            model_changed: true,
782        };
783        let json = serde_json::to_string(&event).unwrap();
784        let deserialized: OclaEvent = serde_json::from_str(&json).unwrap();
785        assert_eq!(event, deserialized);
786    }
787
788    #[test]
789    fn all_11_event_types_serialize() {
790        let events = vec![
791            OclaEvent::RequestCompleted {
792                model: "m".into(),
793                input_tokens: 1,
794                output_tokens: 1,
795                duration_ms: 1,
796                session_id: None,
797            },
798            OclaEvent::FeedbackRecorded {
799                session_id: "s".into(),
800                outcome: FeedbackOutcome::Partial,
801                tool: None,
802            },
803            OclaEvent::ThresholdShift {
804                language: "rust".into(),
805                old_value: 0.5,
806                new_value: 0.6,
807                metric: ThresholdMetric::Entropy,
808            },
809            OclaEvent::CompressionApplied {
810                path: None,
811                before_tokens: 100,
812                after_tokens: 50,
813                strategy: "s".into(),
814            },
815            OclaEvent::SavingsRecorded {
816                input_saved: 10,
817                output_saved: 5,
818                source: SavingsSource::ResponseCache,
819                attribution_id: None,
820                evidence_class: None,
821                measurement_method: None,
822            },
823            OclaEvent::IntentClassified {
824                tier: "standard".into(),
825                confidence: 0.7,
826                reasoning: "r".into(),
827            },
828            OclaEvent::OutcomeRecorded {
829                session_id: "s".into(),
830                accepted: true,
831                implicit: false,
832            },
833            OclaEvent::ResponseOptimized {
834                cache_hit: false,
835                is_duplicate: true,
836                tokens_saved: 0,
837            },
838            OclaEvent::ModelRouted {
839                requested_model: "a".into(),
840                routed_model: "b".into(),
841                tier: "premium".into(),
842                model_changed: true,
843            },
844            OclaEvent::AgentChainEvent {
845                agent_id: "x".into(),
846                action: "spawn".into(),
847                parent_agent: Some("y".into()),
848            },
849            OclaEvent::CrossAgentStubServed {
850                path: "src/main.rs".into(),
851                tokens_saved: 200,
852                serving_agent: "agent-a".into(),
853                original_agent: "agent-b".into(),
854            },
855        ];
856
857        for event in &events {
858            let json = serde_json::to_string(event).unwrap();
859            assert!(!json.is_empty());
860            let _: OclaEvent = serde_json::from_str(&json).unwrap();
861        }
862        assert_eq!(events.len(), 11, "exactly 11 event types");
863    }
864
865    #[test]
866    fn savings_recorded_p5_fields_roundtrip() {
867        let event = OclaEvent::SavingsRecorded {
868            input_saved: 100,
869            output_saved: 25,
870            source: SavingsSource::Routing,
871            attribution_id: Some("attr-42".into()),
872            evidence_class: Some("measured".into()),
873            measurement_method: Some("provider_reconciled".into()),
874        };
875        let json = serde_json::to_string(&event).unwrap();
876        assert!(json.contains("attribution_id"));
877        assert!(json.contains("evidence_class"));
878        assert!(json.contains("measurement_method"));
879        let deserialized: OclaEvent = serde_json::from_str(&json).unwrap();
880        assert_eq!(event, deserialized);
881    }
882}