lean-ctx 3.9.16

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! OCLA Event Bus (P2 / Track B — Event-Backbone).
//!
//! Zero-cost when disabled: a single `AtomicBool` check (< 5ns) gates all
//! emission. When enabled, events flow into the existing `core::events` ring
//! buffer and JSONL persistence.
//!
//! ## Design principles
//!
//! - **Wrap, don't replace**: The existing `events.rs` infrastructure (ring
//!   buffer, JSONL rotation, persistence) is used as-is. `OclaBus` adds the
//!   OCLA semantic layer on top.
//! - **10 event types**: 5 existing (wired to current code) + 5 new (for
//!   P8/P9/P11 traits, wired as those modules integrate).
//! - **Test isolation**: `OclaBus::scoped(capacity)` creates a bus instance
//!   that does NOT touch the global singleton, enabling parallel tests.
//! - **Determinism**: Event IDs come from the existing sequence allocator.
//!   Timestamps are the only non-deterministic field (acceptable for
//!   observability; not included in contract assertions).

use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};

use serde::{Deserialize, Serialize};

use crate::core::context_kernel::bounded::BoundedQueue;

// ─── OCLA Event Types ────────────────────────────────────────────────────────

/// The 10 OCLA event types defined in the P2 spec.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub(crate) enum OclaEvent {
    /// A proxy request completed (usage_meter.rs).
    RequestCompleted {
        model: String,
        input_tokens: u64,
        output_tokens: u64,
        duration_ms: u64,
        session_id: Option<String>,
    },
    /// User feedback recorded (feedback.rs).
    FeedbackRecorded {
        session_id: String,
        outcome: FeedbackOutcome,
        tool: Option<String>,
    },
    /// Compression threshold shifted (threshold_learning.rs).
    ThresholdShift {
        language: String,
        old_value: f64,
        new_value: f64,
        metric: ThresholdMetric,
    },
    /// Compression applied to a request (compress.rs).
    CompressionApplied {
        path: Option<String>,
        before_tokens: u64,
        after_tokens: u64,
        strategy: String,
    },
    /// Savings recorded to the ledger (savings_ledger/store.rs).
    SavingsRecorded {
        input_saved: u64,
        output_saved: u64,
        source: SavingsSource,
        attribution_id: Option<String>,
        evidence_class: Option<String>,
        measurement_method: Option<String>,
    },
    /// Intent classified for a request (P8 — model_router.rs).
    IntentClassified {
        tier: String,
        confidence: f64,
        reasoning: String,
    },
    /// Outcome tracked for a response (P3 — future outcome_tracker.rs).
    OutcomeRecorded {
        session_id: String,
        accepted: bool,
        implicit: bool,
    },
    /// Response optimization applied (P9 — response_optimizer.rs).
    ResponseOptimized {
        cache_hit: bool,
        is_duplicate: bool,
        tokens_saved: u64,
    },
    /// Model routing decision made (P8 — model_router.rs).
    ModelRouted {
        requested_model: String,
        routed_model: String,
        tier: String,
        model_changed: bool,
    },
    /// Agent chain event (P11 — future agent_gateway.rs).
    AgentChainEvent {
        agent_id: String,
        action: String,
        parent_agent: Option<String>,
    },
    /// Cross-agent stub served instead of full read (delivery_registry.rs).
    CrossAgentStubServed {
        path: String,
        tokens_saved: u64,
        serving_agent: String,
        original_agent: String,
    },
}

/// Feedback outcome enum.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum FeedbackOutcome {
    Accept,
    Reject,
    Partial,
}

/// Threshold metric that shifted.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ThresholdMetric {
    Entropy,
    Jaccard,
}

/// Source of savings.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum SavingsSource {
    Compression,
    Cache,
    Routing,
    Verbosity,
    ResponseCache,
}

// ─── Bus Record ──────────────────────────────────────────────────────────────

/// A timestamped OCLA event in the bus ring buffer.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct OclaBusRecord {
    pub id: u64,
    pub timestamp_ms: u64,
    pub event: OclaEvent,
}

/// Policy applied when the OCLA bus reaches its configured capacity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum OverflowPolicy {
    /// Retain the new event and evict the oldest queued event.
    DropOldest,
    /// Retain queued events and reject the new event.
    DropNewest,
    /// Warn and reject the new event because this synchronous bus cannot block.
    Backpressure,
}

impl OverflowPolicy {
    fn from_env() -> Self {
        match std::env::var("LEANCTX_BUS_OVERFLOW").as_deref() {
            Ok("drop_newest") => Self::DropNewest,
            Ok("backpressure") => Self::Backpressure,
            Ok("drop_oldest") | Err(_) => Self::DropOldest,
            Ok(value) => {
                tracing::warn!(
                    value,
                    "invalid LEANCTX_BUS_OVERFLOW value; using drop_oldest"
                );
                Self::DropOldest
            }
        }
    }
}

/// Details recorded whenever an event cannot be retained without overflow.
#[derive(Debug, Clone)]
pub(crate) struct OverflowEvent {
    /// Policy active when the overflow occurred.
    pub policy: OverflowPolicy,
    /// Number of overflows observed by this bus since creation.
    pub dropped_count: usize,
    /// Maximum number of events retained by the queue.
    pub queue_capacity: usize,
}

// ─── OclaBus ─────────────────────────────────────────────────────────────────

/// The OCLA event bus. Zero-cost when disabled.
///
/// Global usage: `ocla_bus::emit(event)` — checks the global enable flag first.
/// Test usage: `OclaBus::scoped(cap)` — isolated instance, no global state.
pub(crate) struct OclaBus {
    enabled: AtomicBool,
    ring: Mutex<BoundedQueue<OclaBusRecord>>,
    capacity: usize,
    next_id: AtomicU64,
    overflow_policy: OverflowPolicy,
    overflow_count: AtomicUsize,
}

impl OclaBus {
    /// Create a new bus with the given ring buffer capacity.
    fn new(capacity: usize) -> Self {
        Self::new_with_policy(capacity, OverflowPolicy::from_env())
    }

    fn new_with_policy(capacity: usize, overflow_policy: OverflowPolicy) -> Self {
        Self {
            enabled: AtomicBool::new(false),
            ring: Mutex::new(BoundedQueue::new(capacity)),
            capacity,
            next_id: AtomicU64::new(1),
            overflow_policy,
            overflow_count: AtomicUsize::new(0),
        }
    }

    /// Create a scoped (isolated) bus for testing. Does NOT affect the global bus.
    pub(crate) fn scoped(capacity: usize) -> Self {
        let bus = Self::new_with_policy(capacity, OverflowPolicy::DropOldest);
        bus.enabled.store(true, Ordering::Relaxed);
        bus
    }

    #[cfg(test)]
    fn scoped_with_policy(capacity: usize, overflow_policy: OverflowPolicy) -> Self {
        let bus = Self::new_with_policy(capacity, overflow_policy);
        bus.enabled.store(true, Ordering::Relaxed);
        bus
    }

    /// Enable the bus. Events will be recorded after this call.
    pub(crate) fn enable(&self) {
        self.enabled.store(true, Ordering::Release);
    }

    /// Disable the bus. Events will be discarded (< 5ns per call).
    pub(crate) fn disable(&self) {
        self.enabled.store(false, Ordering::Release);
    }

    /// Check if the bus is enabled.
    #[inline]
    pub(crate) fn is_enabled(&self) -> bool {
        self.enabled.load(Ordering::Acquire)
    }

    /// Emit an event if the bus is enabled. Returns the event ID, or 0 if disabled.
    #[inline]
    pub(crate) fn emit_if_enabled(&self, event: OclaEvent) -> u64 {
        if !self.is_enabled() {
            return 0;
        }
        self.emit_unconditional(event)
    }

    /// Emit unconditionally (skips the enable check). Used internally and by
    /// callers who have already verified the bus is enabled.
    fn emit_unconditional(&self, event: OclaEvent) -> u64 {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let record = OclaBusRecord {
            id,
            timestamp_ms: current_timestamp_ms(),
            event,
        };

        let mut ring = self
            .ring
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let _dropped = if ring.is_full() {
            let dropped_count = self.overflow_count.fetch_add(1, Ordering::Relaxed) + 1;
            let overflow = OverflowEvent {
                policy: self.overflow_policy,
                dropped_count,
                queue_capacity: self.capacity,
            };

            match self.overflow_policy {
                OverflowPolicy::DropOldest => ring.push(record),
                OverflowPolicy::DropNewest => Some(record),
                OverflowPolicy::Backpressure => {
                    tracing::warn!(
                        dropped_count = overflow.dropped_count,
                        queue_capacity = overflow.queue_capacity,
                        "OCLA bus backpressure requested; dropping newest event"
                    );
                    Some(record)
                }
            }
        } else {
            ring.push(record)
        };

        id
    }

    /// Drain all events from the ring (consumes them). Useful for test assertions.
    pub(crate) fn drain(&self) -> Vec<OclaBusRecord> {
        let mut ring = self
            .ring
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let count = ring.len();
        ring.drain_oldest(count)
    }

    /// Read events since a given ID (non-consuming).
    pub(crate) fn events_since(&self, after_id: u64) -> Vec<OclaBusRecord> {
        let ring = self
            .ring
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        ring.iter().filter(|r| r.id > after_id).cloned().collect()
    }

    /// Read the last N events.
    pub(crate) fn latest(&self, n: usize) -> Vec<OclaBusRecord> {
        let ring = self
            .ring
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let start = ring.len().saturating_sub(n);
        ring.iter().skip(start).cloned().collect()
    }

    /// Current ring buffer occupancy.
    pub(crate) fn len(&self) -> usize {
        self.ring
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    /// Whether the ring is empty.
    pub(crate) fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Total events emitted (including those evicted from the ring).
    pub(crate) fn total_emitted(&self) -> u64 {
        self.next_id.load(Ordering::Relaxed) - 1
    }

    /// Total queue overflows observed by this bus since creation.
    pub(crate) fn overflow_count(&self) -> usize {
        self.overflow_count.load(Ordering::Relaxed)
    }

    /// Overflow policy active for this bus.
    pub(crate) fn overflow_policy(&self) -> OverflowPolicy {
        self.overflow_policy
    }
}

impl std::fmt::Debug for OclaBus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ring_len = self.ring.lock().map_or(0, |r| r.len());
        f.debug_struct("OclaBus")
            .field("enabled", &self.is_enabled())
            .field("ring", &format_args!("[{ring_len} events]"))
            .field("capacity", &self.capacity)
            .field("next_id", &self.next_id.load(Ordering::Relaxed))
            .field("overflow_policy", &self.overflow_policy)
            .field("overflow_count", &self.overflow_count())
            .finish()
    }
}

// ─── Global singleton ────────────────────────────────────────────────────────

const DEFAULT_CAPACITY: usize = 1000;

fn global_bus() -> &'static OclaBus {
    static INSTANCE: OnceLock<OclaBus> = OnceLock::new();
    INSTANCE.get_or_init(|| OclaBus::new(DEFAULT_CAPACITY))
}

/// Emit an OCLA event on the global bus. No-op (< 5ns) when disabled.
#[inline]
pub(crate) fn emit(event: OclaEvent) -> u64 {
    global_bus().emit_if_enabled(event)
}

/// Enable the global OCLA bus.
pub(crate) fn enable() {
    global_bus().enable();
}

/// Disable the global OCLA bus.
pub(crate) fn disable() {
    global_bus().disable();
}

/// Check if the global OCLA bus is enabled.
#[inline]
pub(crate) fn is_enabled() -> bool {
    global_bus().is_enabled()
}

/// Read events since a given ID from the global bus.
pub(crate) fn events_since(after_id: u64) -> Vec<OclaBusRecord> {
    global_bus().events_since(after_id)
}

/// Read the last N events from the global bus.
pub(crate) fn latest(n: usize) -> Vec<OclaBusRecord> {
    global_bus().latest(n)
}

/// Total events emitted on the global bus.
pub(crate) fn total_emitted() -> u64 {
    global_bus().total_emitted()
}

/// Total queue overflows observed by the global bus since startup.
pub(crate) fn overflow_count() -> usize {
    global_bus().overflow_count()
}

/// Overflow policy active for the global bus.
pub(crate) fn overflow_policy() -> OverflowPolicy {
    global_bus().overflow_policy()
}

// ─── Bridge to existing events.rs ────────────────────────────────────────────

/// Bridge: emit an OCLA event AND forward it to the existing events.rs system.
/// This ensures backward compatibility — the dashboard, CLI, and JSONL all
/// continue to see events through the legacy path.
pub(crate) fn emit_and_bridge(event: OclaEvent) -> u64 {
    bridge_to_legacy(&event);
    emit(event)
}

/// Convert an OCLA event to a legacy EventKind and emit it.
fn bridge_to_legacy(event: &OclaEvent) {
    use super::events::{EventKind, emit as legacy_emit};

    let kind = match event {
        OclaEvent::CompressionApplied {
            path,
            before_tokens,
            after_tokens,
            strategy,
        } => EventKind::Compression {
            path: path.clone().unwrap_or_default(),
            before_lines: *before_tokens as u32,
            after_lines: *after_tokens as u32,
            strategy: strategy.clone(),
            kept_line_count: *after_tokens as u32,
            removed_line_count: before_tokens.saturating_sub(*after_tokens) as u32,
        },
        OclaEvent::ThresholdShift {
            language,
            old_value,
            new_value,
            metric,
        } => EventKind::ThresholdShift {
            language: language.clone(),
            old_entropy: if *metric == ThresholdMetric::Entropy {
                *old_value
            } else {
                0.0
            },
            new_entropy: if *metric == ThresholdMetric::Entropy {
                *new_value
            } else {
                0.0
            },
            old_jaccard: if *metric == ThresholdMetric::Jaccard {
                *old_value
            } else {
                0.0
            },
            new_jaccard: if *metric == ThresholdMetric::Jaccard {
                *new_value
            } else {
                0.0
            },
        },
        OclaEvent::RequestCompleted { .. }
        | OclaEvent::FeedbackRecorded { .. }
        | OclaEvent::SavingsRecorded { .. }
        | OclaEvent::IntentClassified { .. }
        | OclaEvent::OutcomeRecorded { .. }
        | OclaEvent::ResponseOptimized { .. }
        | OclaEvent::ModelRouted { .. }
        | OclaEvent::AgentChainEvent { .. }
        | OclaEvent::CrossAgentStubServed { .. } => {
            return;
        }
    };

    legacy_emit(kind);
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

fn current_timestamp_ms() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn savings_event(input_saved: u64) -> OclaEvent {
        OclaEvent::SavingsRecorded {
            input_saved,
            output_saved: 0,
            source: SavingsSource::Compression,
            attribution_id: None,
            evidence_class: None,
            measurement_method: None,
        }
    }

    #[test]
    fn disabled_bus_returns_zero() {
        let bus = OclaBus::new(16);
        assert!(!bus.is_enabled());
        let id = bus.emit_if_enabled(OclaEvent::RequestCompleted {
            model: "gpt-4o".into(),
            input_tokens: 100,
            output_tokens: 50,
            duration_ms: 200,
            session_id: None,
        });
        assert_eq!(id, 0);
        assert!(bus.is_empty());
    }

    #[test]
    fn enabled_bus_records_events() {
        let bus = OclaBus::scoped(16);
        let id = bus.emit_if_enabled(OclaEvent::ModelRouted {
            requested_model: "gpt-4o".into(),
            routed_model: "gpt-4o-mini".into(),
            tier: "fast".into(),
            model_changed: true,
        });
        assert!(id > 0);
        assert_eq!(bus.len(), 1);
    }

    #[test]
    fn scoped_bus_is_isolated() {
        let bus1 = OclaBus::scoped(8);
        let bus2 = OclaBus::scoped(8);

        bus1.emit_if_enabled(OclaEvent::ResponseOptimized {
            cache_hit: true,
            is_duplicate: false,
            tokens_saved: 42,
        });

        assert_eq!(bus1.len(), 1);
        assert_eq!(bus2.len(), 0, "scoped buses are isolated");
    }

    #[test]
    fn test_bounded_queue_replaces_vecdeque() {
        let bus = OclaBus::scoped(2);
        bus.emit_if_enabled(savings_event(1));
        bus.emit_if_enabled(savings_event(2));

        assert_eq!(bus.len(), 2);
        assert_eq!(bus.drain().len(), 2);
        assert!(bus.is_empty());
    }

    #[test]
    fn test_overflow_drop_oldest() {
        let bus = OclaBus::scoped_with_policy(3, OverflowPolicy::DropOldest);
        let id1 = bus.emit_if_enabled(OclaEvent::SavingsRecorded {
            input_saved: 10,
            output_saved: 5,
            source: SavingsSource::Compression,
            attribution_id: None,
            evidence_class: None,
            measurement_method: None,
        });
        bus.emit_if_enabled(OclaEvent::SavingsRecorded {
            input_saved: 20,
            output_saved: 10,
            source: SavingsSource::Cache,
            attribution_id: None,
            evidence_class: None,
            measurement_method: None,
        });
        bus.emit_if_enabled(OclaEvent::SavingsRecorded {
            input_saved: 30,
            output_saved: 15,
            source: SavingsSource::Routing,
            attribution_id: None,
            evidence_class: None,
            measurement_method: None,
        });
        // At capacity. Next emit evicts oldest.
        bus.emit_if_enabled(OclaEvent::SavingsRecorded {
            input_saved: 40,
            output_saved: 20,
            source: SavingsSource::Verbosity,
            attribution_id: None,
            evidence_class: None,
            measurement_method: None,
        });

        assert_eq!(bus.len(), 3);
        let events = bus.events_since(0);
        assert!(events.iter().all(|r| r.id > id1), "oldest evicted");
    }

    #[test]
    fn test_overflow_drop_newest() {
        let bus = OclaBus::scoped_with_policy(2, OverflowPolicy::DropNewest);
        bus.emit_if_enabled(savings_event(1));
        bus.emit_if_enabled(savings_event(2));
        let rejected_id = bus.emit_if_enabled(savings_event(3));

        let retained_ids = bus
            .events_since(0)
            .into_iter()
            .map(|record| record.id)
            .collect::<Vec<_>>();
        assert_eq!(retained_ids, vec![1, 2]);
        assert_eq!(rejected_id, 3);
    }

    #[test]
    fn test_overflow_metrics() {
        let bus = OclaBus::scoped_with_policy(1, OverflowPolicy::DropNewest);
        bus.emit_if_enabled(savings_event(1));
        bus.emit_if_enabled(savings_event(2));
        bus.emit_if_enabled(savings_event(3));

        assert_eq!(bus.overflow_count(), 2);
        assert_eq!(bus.overflow_policy(), OverflowPolicy::DropNewest);
    }

    #[test]
    fn test_overflow_policy_from_env() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        let previous = std::env::var_os("LEANCTX_BUS_OVERFLOW");
        crate::test_env::set_var("LEANCTX_BUS_OVERFLOW", "backpressure");

        let bus = OclaBus::new(1);
        assert_eq!(bus.overflow_policy(), OverflowPolicy::Backpressure);

        if let Some(value) = previous {
            crate::test_env::set_var("LEANCTX_BUS_OVERFLOW", value);
        } else {
            crate::test_env::remove_var("LEANCTX_BUS_OVERFLOW");
        }
    }

    #[test]
    fn drain_consumes_all_events() {
        let bus = OclaBus::scoped(16);
        bus.emit_if_enabled(OclaEvent::IntentClassified {
            tier: "fast".into(),
            confidence: 0.9,
            reasoning: "simple query".into(),
        });
        bus.emit_if_enabled(OclaEvent::IntentClassified {
            tier: "premium".into(),
            confidence: 0.8,
            reasoning: "complex architecture".into(),
        });

        let drained = bus.drain();
        assert_eq!(drained.len(), 2);
        assert!(bus.is_empty(), "drain consumes events");
    }

    #[test]
    fn events_since_filters_by_id() {
        let bus = OclaBus::scoped(16);
        let id1 = bus.emit_if_enabled(OclaEvent::FeedbackRecorded {
            session_id: "s1".into(),
            outcome: FeedbackOutcome::Accept,
            tool: Some("ctx_read".into()),
        });
        let id2 = bus.emit_if_enabled(OclaEvent::FeedbackRecorded {
            session_id: "s2".into(),
            outcome: FeedbackOutcome::Reject,
            tool: None,
        });

        let after = bus.events_since(id1);
        assert_eq!(after.len(), 1);
        assert_eq!(after[0].id, id2);
    }

    #[test]
    fn latest_returns_tail() {
        let bus = OclaBus::scoped(16);
        for i in 0..5 {
            bus.emit_if_enabled(OclaEvent::CompressionApplied {
                path: Some(format!("file_{i}.rs")),
                before_tokens: 100,
                after_tokens: 50,
                strategy: "treesitter".into(),
            });
        }

        let tail = bus.latest(2);
        assert_eq!(tail.len(), 2);
        assert_eq!(tail[0].id, 4);
        assert_eq!(tail[1].id, 5);
    }

    #[test]
    fn enable_disable_toggle() {
        let bus = OclaBus::new(16);
        assert!(!bus.is_enabled());

        bus.enable();
        assert!(bus.is_enabled());
        let id = bus.emit_if_enabled(OclaEvent::AgentChainEvent {
            agent_id: "a1".into(),
            action: "start".into(),
            parent_agent: None,
        });
        assert!(id > 0);

        bus.disable();
        let id2 = bus.emit_if_enabled(OclaEvent::AgentChainEvent {
            agent_id: "a2".into(),
            action: "stop".into(),
            parent_agent: Some("a1".into()),
        });
        assert_eq!(id2, 0);
        assert_eq!(bus.len(), 1, "disabled emit is a no-op");
    }

    #[test]
    fn total_emitted_counts_all() {
        let bus = OclaBus::scoped(3);
        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
            session_id: "s1".into(),
            accepted: true,
            implicit: false,
        });
        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
            session_id: "s2".into(),
            accepted: false,
            implicit: true,
        });
        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
            session_id: "s3".into(),
            accepted: true,
            implicit: true,
        });
        // Emit one more (evicts first).
        bus.emit_if_enabled(OclaEvent::OutcomeRecorded {
            session_id: "s4".into(),
            accepted: true,
            implicit: false,
        });

        assert_eq!(bus.total_emitted(), 4, "counts all, even evicted");
        assert_eq!(bus.len(), 3, "ring only holds capacity");
    }

    #[test]
    fn event_serialization_roundtrip() {
        let event = OclaEvent::ModelRouted {
            requested_model: "claude-sonnet-4-20250514".into(),
            routed_model: "claude-haiku-3".into(),
            tier: "fast".into(),
            model_changed: true,
        };
        let json = serde_json::to_string(&event).unwrap();
        let deserialized: OclaEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(event, deserialized);
    }

    #[test]
    fn all_11_event_types_serialize() {
        let events = vec![
            OclaEvent::RequestCompleted {
                model: "m".into(),
                input_tokens: 1,
                output_tokens: 1,
                duration_ms: 1,
                session_id: None,
            },
            OclaEvent::FeedbackRecorded {
                session_id: "s".into(),
                outcome: FeedbackOutcome::Partial,
                tool: None,
            },
            OclaEvent::ThresholdShift {
                language: "rust".into(),
                old_value: 0.5,
                new_value: 0.6,
                metric: ThresholdMetric::Entropy,
            },
            OclaEvent::CompressionApplied {
                path: None,
                before_tokens: 100,
                after_tokens: 50,
                strategy: "s".into(),
            },
            OclaEvent::SavingsRecorded {
                input_saved: 10,
                output_saved: 5,
                source: SavingsSource::ResponseCache,
                attribution_id: None,
                evidence_class: None,
                measurement_method: None,
            },
            OclaEvent::IntentClassified {
                tier: "standard".into(),
                confidence: 0.7,
                reasoning: "r".into(),
            },
            OclaEvent::OutcomeRecorded {
                session_id: "s".into(),
                accepted: true,
                implicit: false,
            },
            OclaEvent::ResponseOptimized {
                cache_hit: false,
                is_duplicate: true,
                tokens_saved: 0,
            },
            OclaEvent::ModelRouted {
                requested_model: "a".into(),
                routed_model: "b".into(),
                tier: "premium".into(),
                model_changed: true,
            },
            OclaEvent::AgentChainEvent {
                agent_id: "x".into(),
                action: "spawn".into(),
                parent_agent: Some("y".into()),
            },
            OclaEvent::CrossAgentStubServed {
                path: "src/main.rs".into(),
                tokens_saved: 200,
                serving_agent: "agent-a".into(),
                original_agent: "agent-b".into(),
            },
        ];

        for event in &events {
            let json = serde_json::to_string(event).unwrap();
            assert!(!json.is_empty());
            let _: OclaEvent = serde_json::from_str(&json).unwrap();
        }
        assert_eq!(events.len(), 11, "exactly 11 event types");
    }

    #[test]
    fn savings_recorded_p5_fields_roundtrip() {
        let event = OclaEvent::SavingsRecorded {
            input_saved: 100,
            output_saved: 25,
            source: SavingsSource::Routing,
            attribution_id: Some("attr-42".into()),
            evidence_class: Some("measured".into()),
            measurement_method: Some("provider_reconciled".into()),
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("attribution_id"));
        assert!(json.contains("evidence_class"));
        assert!(json.contains("measurement_method"));
        let deserialized: OclaEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(event, deserialized);
    }
}