Skip to main content

gemini_adk_rs/live/
temporal.rs

1//! Temporal pattern detection for live sessions.
2//!
3//! A [`TemporalRegistry`] holds named [`TemporalPattern`]s that combine a
4//! [`PatternDetector`] (the condition) with an async action (the response).
5//! Detectors track time-based and count-based conditions such as sustained
6//! state, event rates, consecutive turns, and consecutive tool failures.
7//!
8//! The registry is evaluated by the control-lane processor on each event and
9//! optionally on a periodic timer (when [`TemporalRegistry::needs_timer`]
10//! returns `true`).
11
12use std::collections::VecDeque;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU32, Ordering};
15use std::time::{Duration, Instant};
16
17use gemini_genai_rs::session::{SessionEvent, SessionWriter};
18
19use super::BoxFuture;
20use crate::state::State;
21
22// ── PatternDetector trait ─────────────────────────────────────────────────────
23
24/// A detector that evaluates whether a temporal pattern has been triggered.
25///
26/// Implementations track internal state (timestamps, counters) to decide
27/// when a pattern fires. All interior mutability is handled via atomic
28/// operations or `parking_lot` locks so that `&self` suffices.
29pub trait PatternDetector: Send + Sync {
30    /// Evaluate whether the pattern is currently triggered.
31    ///
32    /// - `state`: the current agent state snapshot.
33    /// - `event`: the session event that prompted this check (if any).
34    /// - `now`: the current instant (passed in for testability).
35    fn check(&self, state: &State, event: Option<&SessionEvent>, now: Instant) -> bool;
36
37    /// Reset the detector's internal state (counters, timestamps, etc.).
38    fn reset(&self);
39
40    /// Whether this detector requires periodic timer checks.
41    ///
42    /// Detectors that depend on elapsed time (e.g. [`SustainedDetector`])
43    /// should return `true` so the runtime can schedule a timer.
44    fn needs_timer(&self) -> bool {
45        false
46    }
47}
48
49// ── TemporalPattern ───────────────────────────────────────────────────────────
50
51/// A named temporal pattern: detector + action + cooldown.
52pub struct TemporalPattern {
53    /// Human-readable name for logging/debugging.
54    pub name: String,
55    /// The detector that decides when to fire.
56    pub detector: Box<dyn PatternDetector>,
57    /// The async action to execute when the pattern triggers.
58    /// Receives a cloned `State` and the session writer.
59    pub action: super::SessionHook,
60    /// Optional minimum interval between successive firings.
61    pub cooldown: Option<Duration>,
62    /// Tracks when this pattern last fired (for cooldown enforcement).
63    last_triggered: parking_lot::Mutex<Option<Instant>>,
64}
65
66impl TemporalPattern {
67    /// Create a new temporal pattern.
68    pub fn new(
69        name: impl Into<String>,
70        detector: Box<dyn PatternDetector>,
71        action: super::SessionHook,
72        cooldown: Option<Duration>,
73    ) -> Self {
74        Self {
75            name: name.into(),
76            detector,
77            action,
78            cooldown,
79            last_triggered: parking_lot::Mutex::new(None),
80        }
81    }
82
83    /// Check whether the pattern fires and cooldown allows it.
84    fn try_fire(
85        &self,
86        state: &State,
87        event: Option<&SessionEvent>,
88        writer: &Arc<dyn SessionWriter>,
89        now: Instant,
90    ) -> Option<BoxFuture<()>> {
91        if !pattern_fires(
92            self.detector.as_ref(),
93            state,
94            event,
95            now,
96            self.cooldown,
97            &mut self.last_triggered.lock(),
98        ) {
99            return None;
100        }
101
102        let s = state.clone();
103        let w = writer.clone();
104        Some((self.action)(s, w))
105    }
106}
107
108pub(crate) fn pattern_fires(
109    detector: &dyn PatternDetector,
110    state: &State,
111    event: Option<&SessionEvent>,
112    now: Instant,
113    cooldown: Option<Duration>,
114    last: &mut Option<Instant>,
115) -> bool {
116    if !detector.check(state, event, now) {
117        return false;
118    }
119    if let (Some(cooldown), Some(previous)) = (cooldown, *last)
120        && now.saturating_duration_since(previous) < cooldown
121    {
122        return false;
123    }
124    *last = Some(now);
125    true
126}
127
128// ── TemporalRegistry ─────────────────────────────────────────────────────────
129
130/// Registry of temporal patterns evaluated on events and/or timer ticks.
131pub struct TemporalRegistry {
132    patterns: Vec<TemporalPattern>,
133}
134
135impl Default for TemporalRegistry {
136    fn default() -> Self {
137        Self::new()
138    }
139}
140
141impl TemporalRegistry {
142    /// Create an empty registry.
143    pub fn new() -> Self {
144        Self {
145            patterns: Vec::new(),
146        }
147    }
148
149    /// Whether the registry contains no temporal patterns.
150    pub fn is_empty(&self) -> bool {
151        self.patterns.is_empty()
152    }
153
154    /// Register a pattern.
155    pub fn register(&mut self, pattern: TemporalPattern) {
156        self.patterns.push(pattern);
157    }
158
159    /// Check all patterns and return the futures for those that fired.
160    ///
161    /// Called by the control-lane processor on each event and optionally on
162    /// a periodic timer tick.
163    pub fn check_all(
164        &self,
165        state: &State,
166        event: Option<&SessionEvent>,
167        writer: &Arc<dyn SessionWriter>,
168    ) -> Vec<BoxFuture<()>> {
169        let now = state.clock().now();
170        self.patterns
171            .iter()
172            .filter_map(|p| p.try_fire(state, event, writer, now))
173            .collect()
174    }
175
176    /// Returns `true` if any registered pattern's detector needs periodic
177    /// timer checks (i.e. its [`PatternDetector::needs_timer`] returns `true`).
178    pub fn needs_timer(&self) -> bool {
179        self.patterns.iter().any(|p| p.detector.needs_timer())
180    }
181}
182
183// ── SustainedDetector ─────────────────────────────────────────────────────────
184
185/// Fires when a state-based condition remains true for at least `duration`.
186///
187/// On each `check()`:
188/// - If the condition is true and `became_true_at` is `None`, record `now`.
189/// - If the condition is true and `became_true_at` is `Some(t)`, return
190///   `true` when `now - t >= duration`.
191/// - If the condition is false, reset `became_true_at` to `None`.
192///
193/// This detector **needs periodic timer checks** because it depends on
194/// elapsed wall-clock time.
195pub struct SustainedDetector {
196    condition: Arc<dyn Fn(&State) -> bool + Send + Sync>,
197    duration: Duration,
198    became_true_at: parking_lot::Mutex<Option<Instant>>,
199}
200
201impl SustainedDetector {
202    /// Create a new sustained detector.
203    ///
204    /// - `condition`: evaluated against the current state.
205    /// - `duration`: how long the condition must remain true before firing.
206    pub fn new(condition: Arc<dyn Fn(&State) -> bool + Send + Sync>, duration: Duration) -> Self {
207        Self {
208            condition,
209            duration,
210            became_true_at: parking_lot::Mutex::new(None),
211        }
212    }
213}
214
215impl PatternDetector for SustainedDetector {
216    fn check(&self, state: &State, _event: Option<&SessionEvent>, now: Instant) -> bool {
217        if (self.condition)(state) {
218            let mut guard = self.became_true_at.lock();
219            match *guard {
220                None => {
221                    *guard = Some(now);
222                    false
223                }
224                Some(t) => now.duration_since(t) >= self.duration,
225            }
226        } else {
227            *self.became_true_at.lock() = None;
228            false
229        }
230    }
231
232    fn reset(&self) {
233        *self.became_true_at.lock() = None;
234    }
235
236    fn needs_timer(&self) -> bool {
237        true
238    }
239}
240
241// ── RateDetector ──────────────────────────────────────────────────────────────
242
243/// Fires when at least `count` matching events occur within `window`.
244///
245/// On each `check()`:
246/// - If `event` is `Some` and the filter accepts it, push the current
247///   timestamp.
248/// - Expire timestamps older than `window`.
249/// - Return `true` if the remaining count >= threshold.
250pub struct RateDetector {
251    filter: Arc<dyn Fn(&SessionEvent) -> bool + Send + Sync>,
252    count: u32,
253    window: Duration,
254    timestamps: parking_lot::Mutex<VecDeque<Instant>>,
255}
256
257impl RateDetector {
258    /// Create a new rate detector.
259    ///
260    /// - `filter`: predicate to select which events count.
261    /// - `count`: number of matching events required.
262    /// - `window`: sliding time window.
263    pub fn new(
264        filter: Arc<dyn Fn(&SessionEvent) -> bool + Send + Sync>,
265        count: u32,
266        window: Duration,
267    ) -> Self {
268        Self {
269            filter,
270            count,
271            window,
272            timestamps: parking_lot::Mutex::new(VecDeque::new()),
273        }
274    }
275}
276
277impl PatternDetector for RateDetector {
278    fn check(&self, _state: &State, event: Option<&SessionEvent>, now: Instant) -> bool {
279        let mut ts = self.timestamps.lock();
280
281        // Record matching event.
282        if let Some(evt) = event
283            && (self.filter)(evt)
284        {
285            ts.push_back(now);
286        }
287
288        // Expire old timestamps.
289        while let Some(&front) = ts.front() {
290            if now.duration_since(front) > self.window {
291                ts.pop_front();
292            } else {
293                break;
294            }
295        }
296
297        ts.len() as u32 >= self.count
298    }
299
300    fn reset(&self) {
301        self.timestamps.lock().clear();
302    }
303
304    // RateDetector does not need timer — it is event-driven.
305}
306
307// ── TurnCountDetector ─────────────────────────────────────────────────────────
308
309/// Fires when a state-based condition is true for `required` consecutive
310/// evaluations (typically one evaluation per turn).
311///
312/// The caller decides when to invoke `check()` — usually on `TurnComplete`
313/// events.
314pub struct TurnCountDetector {
315    condition: Arc<dyn Fn(&State) -> bool + Send + Sync>,
316    required: u32,
317    consecutive: AtomicU32,
318}
319
320impl TurnCountDetector {
321    /// Create a new turn-count detector.
322    ///
323    /// - `condition`: evaluated against the current state each turn.
324    /// - `required`: number of consecutive true results before firing.
325    pub fn new(condition: Arc<dyn Fn(&State) -> bool + Send + Sync>, required: u32) -> Self {
326        Self {
327            condition,
328            required,
329            consecutive: AtomicU32::new(0),
330        }
331    }
332}
333
334impl PatternDetector for TurnCountDetector {
335    fn check(&self, state: &State, _event: Option<&SessionEvent>, _now: Instant) -> bool {
336        if (self.condition)(state) {
337            let prev = self.consecutive.fetch_add(1, Ordering::SeqCst);
338            prev + 1 >= self.required
339        } else {
340            self.consecutive.store(0, Ordering::SeqCst);
341            false
342        }
343    }
344
345    fn reset(&self) {
346        self.consecutive.store(0, Ordering::SeqCst);
347    }
348}
349
350// ── ConsecutiveFailureDetector ────────────────────────────────────────────────
351
352/// Fires when a named tool has failed `threshold` consecutive times.
353///
354/// Uses a state-key convention: if `bg:{tool_name}_failed` is `true` the
355/// tool is considered to have failed; if `false` (or absent) the streak
356/// resets.
357pub struct ConsecutiveFailureDetector {
358    tool_name: String,
359    threshold: u32,
360    consecutive: AtomicU32,
361}
362
363impl ConsecutiveFailureDetector {
364    /// Create a new consecutive-failure detector.
365    ///
366    /// - `tool_name`: the tool whose failures are tracked.
367    /// - `threshold`: how many consecutive failures before firing.
368    pub fn new(tool_name: impl Into<String>, threshold: u32) -> Self {
369        Self {
370            tool_name: tool_name.into(),
371            threshold,
372            consecutive: AtomicU32::new(0),
373        }
374    }
375}
376
377impl PatternDetector for ConsecutiveFailureDetector {
378    fn check(&self, state: &State, _event: Option<&SessionEvent>, _now: Instant) -> bool {
379        let key = format!("bg:{}_failed", self.tool_name);
380        let failed: bool = state.get(&key).unwrap_or(false);
381
382        if failed {
383            let prev = self.consecutive.fetch_add(1, Ordering::SeqCst);
384            prev + 1 >= self.threshold
385        } else {
386            self.consecutive.store(0, Ordering::SeqCst);
387            false
388        }
389    }
390
391    fn reset(&self) {
392        self.consecutive.store(0, Ordering::SeqCst);
393    }
394}
395
396// ── Tests ─────────────────────────────────────────────────────────────────────
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use crate::test_helpers::MockWriter;
402    use std::sync::atomic::{AtomicU32, Ordering};
403
404    fn mock_writer() -> Arc<dyn SessionWriter> {
405        Arc::new(MockWriter)
406    }
407
408    /// Helper: action that increments a shared counter.
409    fn counting_action(counter: Arc<AtomicU32>) -> crate::live::SessionHook {
410        Arc::new(move |_state, _writer| {
411            let c = counter.clone();
412            Box::pin(async move {
413                c.fetch_add(1, Ordering::SeqCst);
414            })
415        })
416    }
417
418    // ── 1. SustainedDetector fires after duration elapses ─────────────────
419
420    #[test]
421    fn sustained_fires_after_duration() {
422        let state = State::new();
423        let _ = state.set("hot", true);
424
425        let detector = SustainedDetector::new(
426            Arc::new(|s: &State| s.get::<bool>("hot").unwrap_or(false)),
427            Duration::from_secs(5),
428        );
429
430        let t0 = Instant::now();
431
432        // First check: records the start time, does not fire yet.
433        assert!(!detector.check(&state, None, t0));
434
435        // 3 seconds later: not yet.
436        assert!(!detector.check(&state, None, t0 + Duration::from_secs(3)));
437
438        // 5 seconds later: fires.
439        assert!(detector.check(&state, None, t0 + Duration::from_secs(5)));
440
441        // Still fires on subsequent checks while condition holds.
442        assert!(detector.check(&state, None, t0 + Duration::from_secs(6)));
443    }
444
445    // ── 2. SustainedDetector resets when condition becomes false ───────────
446
447    #[test]
448    fn sustained_resets_on_false() {
449        let state = State::new();
450        let _ = state.set("hot", true);
451
452        let detector = SustainedDetector::new(
453            Arc::new(|s: &State| s.get::<bool>("hot").unwrap_or(false)),
454            Duration::from_secs(5),
455        );
456
457        let t0 = Instant::now();
458
459        // Start tracking.
460        assert!(!detector.check(&state, None, t0));
461
462        // Condition becomes false at t0+2s — resets internal timer.
463        let _ = state.set("hot", false);
464        assert!(!detector.check(&state, None, t0 + Duration::from_secs(2)));
465
466        // Condition becomes true again at t0+3s — starts fresh.
467        let _ = state.set("hot", true);
468        assert!(!detector.check(&state, None, t0 + Duration::from_secs(3)));
469
470        // t0+7s: only 4s since re-start at t0+3s — not enough.
471        assert!(!detector.check(&state, None, t0 + Duration::from_secs(7)));
472
473        // t0+8s: 5s since t0+3s — fires.
474        assert!(detector.check(&state, None, t0 + Duration::from_secs(8)));
475    }
476
477    // ── 3. SustainedDetector reset() clears state ─────────────────────────
478
479    #[test]
480    fn sustained_reset_clears_state() {
481        let state = State::new();
482        let _ = state.set("hot", true);
483
484        let detector = SustainedDetector::new(
485            Arc::new(|s: &State| s.get::<bool>("hot").unwrap_or(false)),
486            Duration::from_secs(5),
487        );
488
489        let t0 = Instant::now();
490
491        // Start tracking.
492        assert!(!detector.check(&state, None, t0));
493
494        // Explicit reset.
495        detector.reset();
496
497        // Must start tracking from scratch — 5s from the new check.
498        assert!(!detector.check(&state, None, t0 + Duration::from_secs(4)));
499        assert!(detector.check(&state, None, t0 + Duration::from_secs(9)));
500    }
501
502    // ── 4. RateDetector fires when count reached in window ────────────────
503
504    #[test]
505    fn rate_fires_when_count_reached() {
506        let state = State::new();
507        let detector = RateDetector::new(
508            Arc::new(|evt: &SessionEvent| matches!(evt, SessionEvent::TurnComplete)),
509            3,
510            Duration::from_secs(10),
511        );
512
513        let t0 = Instant::now();
514        let event = SessionEvent::TurnComplete;
515
516        assert!(!detector.check(&state, Some(&event), t0));
517        assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(1)));
518        // Third event: fires.
519        assert!(detector.check(&state, Some(&event), t0 + Duration::from_secs(2)));
520    }
521
522    // ── 5. RateDetector does not fire when events outside window ──────────
523
524    #[test]
525    fn rate_does_not_fire_when_events_outside_window() {
526        let state = State::new();
527        let detector = RateDetector::new(
528            Arc::new(|evt: &SessionEvent| matches!(evt, SessionEvent::TurnComplete)),
529            3,
530            Duration::from_secs(5),
531        );
532
533        let t0 = Instant::now();
534        let event = SessionEvent::TurnComplete;
535
536        // Two events at t0.
537        assert!(!detector.check(&state, Some(&event), t0));
538        assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(1)));
539
540        // Third event at t0+10s: first two have expired.
541        assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(10)));
542    }
543
544    // ── 6. RateDetector with filter that rejects events ───────────────────
545
546    #[test]
547    fn rate_filter_rejects_events() {
548        let state = State::new();
549        let detector = RateDetector::new(
550            Arc::new(|evt: &SessionEvent| matches!(evt, SessionEvent::TurnComplete)),
551            2,
552            Duration::from_secs(10),
553        );
554
555        let t0 = Instant::now();
556
557        // These events don't match the filter.
558        let text_event = SessionEvent::TextDelta("hello".to_string());
559        assert!(!detector.check(&state, Some(&text_event), t0));
560        assert!(!detector.check(&state, Some(&text_event), t0 + Duration::from_secs(1)));
561        assert!(!detector.check(&state, Some(&text_event), t0 + Duration::from_secs(2)));
562
563        // Still at 0 matching events — no fire.
564        assert!(!detector.check(&state, None, t0 + Duration::from_secs(3)));
565    }
566
567    // ── 7. TurnCountDetector fires after N consecutive true ───────────────
568
569    #[test]
570    fn turn_count_fires_after_n_consecutive() {
571        let state = State::new();
572        let _ = state.set("confused", true);
573
574        let detector = TurnCountDetector::new(
575            Arc::new(|s: &State| s.get::<bool>("confused").unwrap_or(false)),
576            3,
577        );
578
579        let t0 = Instant::now();
580
581        assert!(!detector.check(&state, None, t0));
582        assert!(!detector.check(&state, None, t0));
583        // Third consecutive true: fires.
584        assert!(detector.check(&state, None, t0));
585    }
586
587    // ── 8. TurnCountDetector resets on false ──────────────────────────────
588
589    #[test]
590    fn turn_count_resets_on_false() {
591        let state = State::new();
592        let _ = state.set("confused", true);
593
594        let detector = TurnCountDetector::new(
595            Arc::new(|s: &State| s.get::<bool>("confused").unwrap_or(false)),
596            3,
597        );
598
599        let t0 = Instant::now();
600
601        assert!(!detector.check(&state, None, t0));
602        assert!(!detector.check(&state, None, t0));
603
604        // Condition becomes false — resets counter.
605        let _ = state.set("confused", false);
606        assert!(!detector.check(&state, None, t0));
607
608        // Start again — need 3 more consecutive trues.
609        let _ = state.set("confused", true);
610        assert!(!detector.check(&state, None, t0));
611        assert!(!detector.check(&state, None, t0));
612        assert!(detector.check(&state, None, t0));
613    }
614
615    // ── 9. ConsecutiveFailureDetector fires after threshold ───────────────
616
617    #[test]
618    fn consecutive_failure_fires_after_threshold() {
619        let state = State::new();
620        let _ = state.set("bg:search_failed", true);
621
622        let detector = ConsecutiveFailureDetector::new("search", 3);
623
624        let t0 = Instant::now();
625
626        assert!(!detector.check(&state, None, t0));
627        assert!(!detector.check(&state, None, t0));
628        // Third consecutive failure: fires.
629        assert!(detector.check(&state, None, t0));
630    }
631
632    // ── 10. ConsecutiveFailureDetector resets on success ──────────────────
633
634    #[test]
635    fn consecutive_failure_resets_on_success() {
636        let state = State::new();
637        let _ = state.set("bg:search_failed", true);
638
639        let detector = ConsecutiveFailureDetector::new("search", 3);
640
641        let t0 = Instant::now();
642
643        assert!(!detector.check(&state, None, t0));
644        assert!(!detector.check(&state, None, t0));
645
646        // Tool succeeds — reset.
647        let _ = state.set("bg:search_failed", false);
648        assert!(!detector.check(&state, None, t0));
649
650        // Must accumulate again from 0.
651        let _ = state.set("bg:search_failed", true);
652        assert!(!detector.check(&state, None, t0));
653        assert!(!detector.check(&state, None, t0));
654        assert!(detector.check(&state, None, t0));
655    }
656
657    // ── 11. TemporalPattern cooldown prevents rapid re-firing ─────────────
658
659    #[tokio::test]
660    async fn pattern_cooldown_prevents_rapid_refiring() {
661        let counter = Arc::new(AtomicU32::new(0));
662        let state = State::new();
663        let _ = state.set("active", true);
664        let writer = mock_writer();
665
666        let pattern = TemporalPattern::new(
667            "test-cooldown",
668            Box::new(SustainedDetector::new(
669                Arc::new(|s: &State| s.get::<bool>("active").unwrap_or(false)),
670                Duration::from_secs(0), // fires immediately once became_true_at is set
671            )),
672            counting_action(counter.clone()),
673            Some(Duration::from_secs(10)), // 10s cooldown
674        );
675
676        let t0 = Instant::now();
677
678        // First check: sets became_true_at but doesn't fire (duration=0, but
679        // the first check just records the start time).
680        assert!(pattern.try_fire(&state, None, &writer, t0).is_none());
681
682        // Second check: fires (condition true + duration=0 elapsed).
683        let fut = pattern.try_fire(&state, None, &writer, t0 + Duration::from_millis(1));
684        assert!(fut.is_some());
685        fut.unwrap().await;
686        assert_eq!(counter.load(Ordering::SeqCst), 1);
687
688        // Immediate re-check: cooldown blocks.
689        assert!(
690            pattern
691                .try_fire(&state, None, &writer, t0 + Duration::from_millis(2))
692                .is_none()
693        );
694
695        // After cooldown: fires again.
696        let fut = pattern.try_fire(&state, None, &writer, t0 + Duration::from_secs(11));
697        assert!(fut.is_some());
698        fut.unwrap().await;
699        assert_eq!(counter.load(Ordering::SeqCst), 2);
700    }
701
702    // ── 12. TemporalRegistry check_all returns actions ────────────────────
703
704    #[tokio::test]
705    async fn registry_check_all_returns_actions() {
706        let counter = Arc::new(AtomicU32::new(0));
707        let state = State::new();
708        let _ = state.set("confused", true);
709        let writer = mock_writer();
710
711        let mut registry = TemporalRegistry::new();
712
713        // TurnCountDetector with required=1 — fires on first true check.
714        registry.register(TemporalPattern::new(
715            "confusion",
716            Box::new(TurnCountDetector::new(
717                Arc::new(|s: &State| s.get::<bool>("confused").unwrap_or(false)),
718                1,
719            )),
720            counting_action(counter.clone()),
721            None,
722        ));
723
724        let actions = registry.check_all(&state, None, &writer);
725        assert_eq!(actions.len(), 1);
726
727        for fut in actions {
728            fut.await;
729        }
730        assert_eq!(counter.load(Ordering::SeqCst), 1);
731    }
732
733    /// A sustained pattern measures its duration on the state's clock, so a
734    /// manual clock decides when it fires, not the wall clock.
735    #[tokio::test]
736    async fn registry_reads_time_from_the_state_clock() {
737        let counter = Arc::new(AtomicU32::new(0));
738        let clock = Arc::new(crate::clock::ManualClock::new());
739        let state = State::new().with_clock(clock.clone());
740        let writer = mock_writer();
741
742        let mut registry = TemporalRegistry::new();
743        registry.register(TemporalPattern::new(
744            "sustained",
745            Box::new(SustainedDetector::new(
746                Arc::new(|_: &State| true),
747                Duration::from_secs(5),
748            )),
749            counting_action(counter.clone()),
750            None,
751        ));
752
753        assert!(registry.check_all(&state, None, &writer).is_empty());
754        clock.advance(Duration::from_secs(4));
755        assert!(registry.check_all(&state, None, &writer).is_empty());
756        clock.advance(Duration::from_secs(1));
757        let fired = registry.check_all(&state, None, &writer);
758        assert_eq!(fired.len(), 1, "fires once five clock seconds have passed");
759        for fut in fired {
760            fut.await;
761        }
762        assert_eq!(counter.load(Ordering::SeqCst), 1);
763    }
764
765    // ── 13. needs_timer returns true when SustainedDetector is registered ─
766
767    #[test]
768    fn needs_timer_true_with_sustained_detector() {
769        let counter = Arc::new(AtomicU32::new(0));
770        let mut registry = TemporalRegistry::new();
771
772        registry.register(TemporalPattern::new(
773            "sustained",
774            Box::new(SustainedDetector::new(
775                Arc::new(|_: &State| true),
776                Duration::from_secs(5),
777            )),
778            counting_action(counter),
779            None,
780        ));
781
782        assert!(registry.needs_timer());
783    }
784
785    // ── 14. needs_timer returns false when no SustainedDetector ───────────
786
787    #[test]
788    fn needs_timer_false_without_sustained_detector() {
789        let counter = Arc::new(AtomicU32::new(0));
790        let mut registry = TemporalRegistry::new();
791
792        registry.register(TemporalPattern::new(
793            "turn-count",
794            Box::new(TurnCountDetector::new(Arc::new(|_: &State| true), 3)),
795            counting_action(counter.clone()),
796            None,
797        ));
798
799        registry.register(TemporalPattern::new(
800            "rate",
801            Box::new(RateDetector::new(
802                Arc::new(|_: &SessionEvent| true),
803                5,
804                Duration::from_secs(10),
805            )),
806            counting_action(counter),
807            None,
808        ));
809
810        assert!(!registry.needs_timer());
811    }
812
813    // ── Additional: Default creates empty registry ────────────────────────
814
815    #[test]
816    fn default_creates_empty_registry() {
817        let registry = TemporalRegistry::default();
818        assert!(!registry.needs_timer());
819    }
820
821    // ── Additional: RateDetector reset clears timestamps ──────────────────
822
823    #[test]
824    fn rate_reset_clears_timestamps() {
825        let state = State::new();
826        let detector = RateDetector::new(
827            Arc::new(|evt: &SessionEvent| matches!(evt, SessionEvent::TurnComplete)),
828            2,
829            Duration::from_secs(10),
830        );
831
832        let t0 = Instant::now();
833        let event = SessionEvent::TurnComplete;
834
835        assert!(!detector.check(&state, Some(&event), t0));
836        detector.reset();
837        // After reset, first event should not be enough.
838        assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(1)));
839        // Second event after reset fires.
840        assert!(detector.check(&state, Some(&event), t0 + Duration::from_secs(2)));
841    }
842
843    // ── Additional: TurnCountDetector reset clears counter ────────────────
844
845    #[test]
846    fn turn_count_reset_clears_counter() {
847        let state = State::new();
848        let _ = state.set("confused", true);
849
850        let detector = TurnCountDetector::new(
851            Arc::new(|s: &State| s.get::<bool>("confused").unwrap_or(false)),
852            3,
853        );
854
855        let t0 = Instant::now();
856
857        assert!(!detector.check(&state, None, t0));
858        assert!(!detector.check(&state, None, t0));
859        // Two consecutive trues accumulated.
860
861        detector.reset();
862
863        // After reset, need 3 more.
864        assert!(!detector.check(&state, None, t0));
865        assert!(!detector.check(&state, None, t0));
866        assert!(detector.check(&state, None, t0));
867    }
868
869    // ── Additional: ConsecutiveFailureDetector reset clears counter ───────
870
871    #[test]
872    fn consecutive_failure_reset_clears_counter() {
873        let state = State::new();
874        let _ = state.set("bg:search_failed", true);
875
876        let detector = ConsecutiveFailureDetector::new("search", 3);
877        let t0 = Instant::now();
878
879        assert!(!detector.check(&state, None, t0));
880        assert!(!detector.check(&state, None, t0));
881
882        detector.reset();
883
884        assert!(!detector.check(&state, None, t0));
885        assert!(!detector.check(&state, None, t0));
886        assert!(detector.check(&state, None, t0));
887    }
888
889    // ── Additional: SustainedDetector needs_timer is true ─────────────────
890
891    #[test]
892    fn sustained_detector_needs_timer() {
893        let detector = SustainedDetector::new(Arc::new(|_: &State| true), Duration::from_secs(5));
894        assert!(detector.needs_timer());
895    }
896
897    // ── Additional: RateDetector needs_timer is false ─────────────────────
898
899    #[test]
900    fn rate_detector_does_not_need_timer() {
901        let detector = RateDetector::new(
902            Arc::new(|_: &SessionEvent| true),
903            5,
904            Duration::from_secs(10),
905        );
906        assert!(!detector.needs_timer());
907    }
908
909    // ── Additional: TurnCountDetector needs_timer is false ────────────────
910
911    #[test]
912    fn turn_count_detector_does_not_need_timer() {
913        let detector = TurnCountDetector::new(Arc::new(|_: &State| true), 3);
914        assert!(!detector.needs_timer());
915    }
916
917    // ── Additional: Pattern without cooldown fires every time ─────────────
918
919    #[tokio::test]
920    async fn pattern_without_cooldown_fires_every_time() {
921        let counter = Arc::new(AtomicU32::new(0));
922        let state = State::new();
923        let _ = state.set("active", true);
924        let writer = mock_writer();
925
926        let pattern = TemporalPattern::new(
927            "no-cooldown",
928            Box::new(TurnCountDetector::new(
929                Arc::new(|s: &State| s.get::<bool>("active").unwrap_or(false)),
930                1,
931            )),
932            counting_action(counter.clone()),
933            None, // no cooldown
934        );
935
936        let t0 = Instant::now();
937
938        for i in 0..5u32 {
939            let fut = pattern.try_fire(&state, None, &writer, t0 + Duration::from_millis(i as u64));
940            assert!(fut.is_some(), "should fire on iteration {i}");
941            fut.unwrap().await;
942        }
943
944        assert_eq!(counter.load(Ordering::SeqCst), 5);
945    }
946}