1use 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
22pub trait PatternDetector: Send + Sync {
30 fn check(&self, state: &State, event: Option<&SessionEvent>, now: Instant) -> bool;
36
37 fn reset(&self);
39
40 fn needs_timer(&self) -> bool {
45 false
46 }
47}
48
49pub struct TemporalPattern {
53 pub name: String,
55 pub detector: Box<dyn PatternDetector>,
57 pub action: super::SessionHook,
60 pub cooldown: Option<Duration>,
62 last_triggered: parking_lot::Mutex<Option<Instant>>,
64}
65
66impl TemporalPattern {
67 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 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
128pub 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 pub fn new() -> Self {
144 Self {
145 patterns: Vec::new(),
146 }
147 }
148
149 pub fn is_empty(&self) -> bool {
151 self.patterns.is_empty()
152 }
153
154 pub fn register(&mut self, pattern: TemporalPattern) {
156 self.patterns.push(pattern);
157 }
158
159 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 pub fn needs_timer(&self) -> bool {
179 self.patterns.iter().any(|p| p.detector.needs_timer())
180 }
181}
182
183pub 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 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
241pub 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 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 if let Some(evt) = event
283 && (self.filter)(evt)
284 {
285 ts.push_back(now);
286 }
287
288 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 }
306
307pub struct TurnCountDetector {
315 condition: Arc<dyn Fn(&State) -> bool + Send + Sync>,
316 required: u32,
317 consecutive: AtomicU32,
318}
319
320impl TurnCountDetector {
321 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
350pub struct ConsecutiveFailureDetector {
358 tool_name: String,
359 threshold: u32,
360 consecutive: AtomicU32,
361}
362
363impl ConsecutiveFailureDetector {
364 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#[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 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 #[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 assert!(!detector.check(&state, None, t0));
434
435 assert!(!detector.check(&state, None, t0 + Duration::from_secs(3)));
437
438 assert!(detector.check(&state, None, t0 + Duration::from_secs(5)));
440
441 assert!(detector.check(&state, None, t0 + Duration::from_secs(6)));
443 }
444
445 #[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 assert!(!detector.check(&state, None, t0));
461
462 let _ = state.set("hot", false);
464 assert!(!detector.check(&state, None, t0 + Duration::from_secs(2)));
465
466 let _ = state.set("hot", true);
468 assert!(!detector.check(&state, None, t0 + Duration::from_secs(3)));
469
470 assert!(!detector.check(&state, None, t0 + Duration::from_secs(7)));
472
473 assert!(detector.check(&state, None, t0 + Duration::from_secs(8)));
475 }
476
477 #[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 assert!(!detector.check(&state, None, t0));
493
494 detector.reset();
496
497 assert!(!detector.check(&state, None, t0 + Duration::from_secs(4)));
499 assert!(detector.check(&state, None, t0 + Duration::from_secs(9)));
500 }
501
502 #[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 assert!(detector.check(&state, Some(&event), t0 + Duration::from_secs(2)));
520 }
521
522 #[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 assert!(!detector.check(&state, Some(&event), t0));
538 assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(1)));
539
540 assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(10)));
542 }
543
544 #[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 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 assert!(!detector.check(&state, None, t0 + Duration::from_secs(3)));
565 }
566
567 #[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 assert!(detector.check(&state, None, t0));
585 }
586
587 #[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 let _ = state.set("confused", false);
606 assert!(!detector.check(&state, None, t0));
607
608 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 #[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 assert!(detector.check(&state, None, t0));
630 }
631
632 #[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 let _ = state.set("bg:search_failed", false);
648 assert!(!detector.check(&state, None, t0));
649
650 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 #[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), )),
672 counting_action(counter.clone()),
673 Some(Duration::from_secs(10)), );
675
676 let t0 = Instant::now();
677
678 assert!(pattern.try_fire(&state, None, &writer, t0).is_none());
681
682 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 assert!(
690 pattern
691 .try_fire(&state, None, &writer, t0 + Duration::from_millis(2))
692 .is_none()
693 );
694
695 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 #[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 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 #[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 #[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 #[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 #[test]
816 fn default_creates_empty_registry() {
817 let registry = TemporalRegistry::default();
818 assert!(!registry.needs_timer());
819 }
820
821 #[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 assert!(!detector.check(&state, Some(&event), t0 + Duration::from_secs(1)));
839 assert!(detector.check(&state, Some(&event), t0 + Duration::from_secs(2)));
841 }
842
843 #[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 detector.reset();
862
863 assert!(!detector.check(&state, None, t0));
865 assert!(!detector.check(&state, None, t0));
866 assert!(detector.check(&state, None, t0));
867 }
868
869 #[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 #[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 #[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 #[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 #[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, );
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}