1use std::collections::HashMap;
3use std::time::{Duration, Instant};
4
5use super::config::LoopDetectionConfig;
6
7const SEARCH_TOOLS: &[&str] = &["ctx_search", "ctx_semantic_search"];
8
9const SEARCH_SHELL_PREFIXES: &[&str] = &["grep ", "rg ", "find ", "fd ", "ag ", "ack "];
10
11const CORRECTION_WINDOW: Duration = Duration::from_mins(2);
12const MODE_BOUNCE_WINDOW: Duration = Duration::from_secs(30);
13const SHELL_RERUN_WINDOW: Duration = Duration::from_mins(1);
14const COLD_START_CALLS: u32 = 3;
15
16#[derive(Debug, Clone, PartialEq)]
18pub enum CorrectionKind {
19 FreshReRead,
20 ShellReRun,
21 ModeBounce,
22}
23
24#[derive(Debug, Clone)]
26pub struct LoopDetector {
27 call_history: HashMap<String, Vec<Instant>>,
28 duplicate_counts: HashMap<String, u32>,
29 tool_total_counts: HashMap<String, u32>,
30 tool_total_limits: HashMap<String, u32>,
31 search_group_history: Vec<Instant>,
32 recent_search_patterns: Vec<String>,
33 normal_threshold: u32,
34 reduced_threshold: u32,
35 blocked_threshold: u32,
36 window: Duration,
37 search_group_limit: u32,
38 correction_signals: Vec<(Instant, CorrectionKind)>,
40 recent_reads: HashMap<String, (Instant, String)>,
41 recent_commands: HashMap<String, Instant>,
42 total_calls: u32,
43 retrieve_signals: Vec<Instant>,
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub enum ThrottleLevel {
52 Normal,
53 Reduced,
54 Blocked,
55}
56
57#[derive(Debug, Clone)]
59pub struct ThrottleResult {
60 pub level: ThrottleLevel,
61 pub call_count: u32,
62 pub message: Option<String>,
63}
64
65impl Default for ThrottleResult {
66 fn default() -> Self {
67 Self {
68 level: ThrottleLevel::Normal,
69 call_count: 0,
70 message: None,
71 }
72 }
73}
74
75impl Default for LoopDetector {
76 fn default() -> Self {
77 Self::new()
78 }
79}
80
81impl LoopDetector {
82 pub fn new() -> Self {
84 Self::with_config(&LoopDetectionConfig::default())
85 }
86
87 pub fn with_config(cfg: &LoopDetectionConfig) -> Self {
90 Self {
91 call_history: HashMap::new(),
92 duplicate_counts: HashMap::new(),
93 tool_total_counts: HashMap::new(),
94 tool_total_limits: cfg.tool_total_limits.clone(),
95 search_group_history: Vec::new(),
96 recent_search_patterns: Vec::new(),
97 normal_threshold: cfg.normal_threshold.max(1),
98 reduced_threshold: cfg.reduced_threshold.max(2),
99 blocked_threshold: cfg.blocked_threshold,
100 window: Duration::from_secs(cfg.window_secs),
101 search_group_limit: if cfg.blocked_threshold == 0 {
102 u32::MAX
103 } else {
104 cfg.search_group_limit.max(3)
105 },
106 correction_signals: Vec::new(),
107 recent_reads: HashMap::new(),
108 recent_commands: HashMap::new(),
109 total_calls: 0,
110 retrieve_signals: Vec::new(),
111 }
112 }
113
114 pub fn record_call(&mut self, tool: &str, args_fingerprint: &str) -> ThrottleResult {
116 let now = Instant::now();
117 self.prune_window(now);
118
119 let total = self.tool_total_counts.entry(tool.to_string()).or_insert(0);
121 *total += 1;
122 let total_count = *total;
123
124 if let Some(&limit) = self.tool_total_limits.get(tool)
125 && total_count > limit
126 {
127 let msg = if crate::core::protocol::meta_visible() {
128 Some(format!(
129 "Warning: {tool} called {total_count}x total (limit: {limit}). \
130 Consider ctx_compress or narrowing scope."
131 ))
132 } else {
133 None
134 };
135 return ThrottleResult {
136 level: ThrottleLevel::Reduced,
137 call_count: total_count,
138 message: msg,
139 };
140 }
141
142 let key = format!("{tool}:{args_fingerprint}");
143 let entries = self.call_history.entry(key.clone()).or_default();
144 entries.push(now);
145 let count = entries.len() as u32;
146 *self.duplicate_counts.entry(key).or_default() = count;
147
148 if self.blocked_threshold > 0 && count > self.blocked_threshold {
149 return ThrottleResult {
150 level: ThrottleLevel::Blocked,
151 call_count: count,
152 message: Some(self.block_message(tool, count)),
153 };
154 }
155 if count > self.reduced_threshold {
156 if !crate::core::protocol::meta_visible() {
157 return ThrottleResult {
158 level: ThrottleLevel::Reduced,
159 call_count: count,
160 message: None,
161 };
162 }
163 return ThrottleResult {
164 level: ThrottleLevel::Reduced,
165 call_count: count,
166 message: Some(format!(
167 "Warning: {tool} called {count}x with same args. \
168 Results reduced. Try a different approach or narrow your scope."
169 )),
170 };
171 }
172 if count > self.normal_threshold {
173 if !crate::core::protocol::meta_visible() {
174 return ThrottleResult {
175 level: ThrottleLevel::Reduced,
176 call_count: count,
177 message: None,
178 };
179 }
180 return ThrottleResult {
181 level: ThrottleLevel::Reduced,
182 call_count: count,
183 message: Some(format!(
184 "Note: {tool} called {count}x with similar args. Consider narrowing scope."
185 )),
186 };
187 }
188 ThrottleResult {
189 level: ThrottleLevel::Normal,
190 call_count: count,
191 message: None,
192 }
193 }
194
195 pub fn record_error_outcome(&mut self, tool: &str, args_fingerprint: &str) {
198 let key = format!("{tool}:{args_fingerprint}");
199 if let Some(entries) = self.call_history.get_mut(&key) {
200 entries.pop();
201 let count = entries.len() as u32;
202 self.duplicate_counts.insert(key, count);
203 }
204 }
205
206 pub fn record_search(
209 &mut self,
210 tool: &str,
211 args_fingerprint: &str,
212 search_pattern: Option<&str>,
213 ) -> ThrottleResult {
214 let now = Instant::now();
215
216 self.search_group_history.push(now);
217 let search_count = self.search_group_history.len() as u32;
218
219 let similar_count = if let Some(pat) = search_pattern {
220 let sc = self.count_similar_patterns(pat);
221 if !pat.is_empty() {
222 self.recent_search_patterns.push(pat.to_string());
223 if self.recent_search_patterns.len() > 15 {
224 self.recent_search_patterns.remove(0);
225 }
226 }
227 sc
228 } else {
229 0
230 };
231
232 if self.blocked_threshold > 0 && similar_count >= self.blocked_threshold {
234 return ThrottleResult {
235 level: ThrottleLevel::Blocked,
236 call_count: similar_count,
237 message: Some(self.search_block_message(similar_count)),
238 };
239 }
240
241 if self.blocked_threshold > 0 && search_count > self.search_group_limit {
243 return ThrottleResult {
244 level: ThrottleLevel::Blocked,
245 call_count: search_count,
246 message: Some(self.search_group_block_message(search_count)),
247 };
248 }
249
250 if similar_count >= self.reduced_threshold {
251 if !crate::core::protocol::meta_visible() {
252 return ThrottleResult {
253 level: ThrottleLevel::Reduced,
254 call_count: similar_count,
255 message: None,
256 };
257 }
258 return ThrottleResult {
259 level: ThrottleLevel::Reduced,
260 call_count: similar_count,
261 message: Some(format!(
262 "Warning: You've searched for similar patterns {similar_count}x. \
263 Narrow your search with the 'path' parameter or try ctx_tree first."
264 )),
265 };
266 }
267
268 if search_count > self.search_group_limit.saturating_sub(3) {
269 let per_fp = self.record_call(tool, args_fingerprint);
270 if per_fp.level != ThrottleLevel::Normal {
271 return per_fp;
272 }
273 if !crate::core::protocol::meta_visible() {
274 return ThrottleResult {
275 level: ThrottleLevel::Reduced,
276 call_count: search_count,
277 message: None,
278 };
279 }
280 return ThrottleResult {
281 level: ThrottleLevel::Reduced,
282 call_count: search_count,
283 message: Some(format!(
284 "Note: {search_count} search calls in the last {}s. \
285 Use ctx_tree to orient first, then scope searches with 'path'.",
286 self.window.as_secs()
287 )),
288 };
289 }
290
291 self.record_call(tool, args_fingerprint)
292 }
293
294 pub fn is_search_tool(tool: &str) -> bool {
296 SEARCH_TOOLS.contains(&tool)
297 }
298
299 pub fn is_search_shell_command(command: &str) -> bool {
301 let cmd = command.trim_start();
302 SEARCH_SHELL_PREFIXES.iter().any(|p| cmd.starts_with(p))
303 }
304
305 pub fn fingerprint(args: &serde_json::Value) -> String {
307 use std::collections::hash_map::DefaultHasher;
308 use std::hash::{Hash, Hasher};
309
310 let canonical = canonical_json(args);
311 let mut hasher = DefaultHasher::new();
312 canonical.hash(&mut hasher);
313 format!("{:016x}", hasher.finish())
314 }
315
316 pub fn stats(&self) -> Vec<(String, u32)> {
318 let mut entries: Vec<(String, u32)> = self
319 .duplicate_counts
320 .iter()
321 .filter(|&(_, &count)| count > 1)
322 .map(|(k, &v)| (k.clone(), v))
323 .collect();
324 entries.sort_by_key(|x| std::cmp::Reverse(x.1));
325 entries
326 }
327
328 pub fn record_read_for_correction(&mut self, path: &str, mode: &str, fresh: bool) {
332 self.total_calls += 1;
333 let now = Instant::now();
334
335 if self.total_calls <= COLD_START_CALLS {
336 self.recent_reads
337 .insert(path.to_string(), (now, mode.to_string()));
338 return;
339 }
340
341 if fresh
342 && let Some((prev_time, _)) = self.recent_reads.get(path)
343 && now.duration_since(*prev_time) < CORRECTION_WINDOW
344 {
345 self.correction_signals
346 .push((now, CorrectionKind::FreshReRead));
347 }
348
349 if mode == "full"
350 && let Some((prev_time, prev_mode)) = self.recent_reads.get(path)
351 {
352 let is_bounce = (prev_mode == "map" || prev_mode == "signatures")
353 && now.duration_since(*prev_time) < MODE_BOUNCE_WINDOW;
354 if is_bounce {
355 self.correction_signals
356 .push((now, CorrectionKind::ModeBounce));
357 }
358 }
359
360 self.recent_reads
361 .insert(path.to_string(), (now, mode.to_string()));
362 }
363
364 pub fn record_shell_for_correction(&mut self, command: &str) {
366 self.total_calls += 1;
367 let now = Instant::now();
368
369 if self.total_calls <= COLD_START_CALLS {
370 self.recent_commands.insert(command.to_string(), now);
371 return;
372 }
373
374 let key = normalize_shell_command(command);
375 if let Some(prev_time) = self.recent_commands.get(&key)
376 && now.duration_since(*prev_time) < SHELL_RERUN_WINDOW
377 {
378 self.correction_signals
379 .push((now, CorrectionKind::ShellReRun));
380 }
381 self.recent_commands.insert(key, now);
382 }
383
384 pub fn correction_count(&self) -> u32 {
386 let now = Instant::now();
387 self.correction_signals
388 .iter()
389 .filter(|(t, _)| now.duration_since(*t) < CORRECTION_WINDOW)
390 .count() as u32
391 }
392
393 pub fn record_retrieve(&mut self) {
397 self.retrieve_signals.push(Instant::now());
398 }
399
400 pub fn retrieve_count(&self) -> u32 {
402 let now = Instant::now();
403 self.retrieve_signals
404 .iter()
405 .filter(|t| now.duration_since(**t) < CORRECTION_WINDOW)
406 .count() as u32
407 }
408
409 pub fn correction_rate(&self) -> f64 {
411 let count = self.correction_count();
412 if count == 0 {
413 return 0.0;
414 }
415 let window_mins = CORRECTION_WINDOW.as_secs_f64() / 60.0;
416 f64::from(count) / window_mins
417 }
418
419 pub fn prune_corrections(&mut self) {
421 let now = Instant::now();
422 self.correction_signals
423 .retain(|(t, _)| now.duration_since(*t) < CORRECTION_WINDOW);
424 self.recent_reads
425 .retain(|_, (t, _)| now.duration_since(*t) < CORRECTION_WINDOW);
426 self.recent_commands
427 .retain(|_, t| now.duration_since(*t) < CORRECTION_WINDOW);
428 self.retrieve_signals
429 .retain(|t| now.duration_since(*t) < CORRECTION_WINDOW);
430 }
431
432 pub fn reset(&mut self) {
434 self.call_history.clear();
435 self.duplicate_counts.clear();
436 self.search_group_history.clear();
437 self.recent_search_patterns.clear();
438 self.correction_signals.clear();
439 self.recent_reads.clear();
440 self.recent_commands.clear();
441 self.total_calls = 0;
442 self.retrieve_signals.clear();
443 }
444
445 fn prune_window(&mut self, now: Instant) {
446 for entries in self.call_history.values_mut() {
447 entries.retain(|t| now.duration_since(*t) < self.window);
448 }
449 self.call_history.retain(|_, v| !v.is_empty());
455 let live = &self.call_history;
456 self.duplicate_counts.retain(|k, _| live.contains_key(k));
457 self.search_group_history
458 .retain(|t| now.duration_since(*t) < self.window);
459 }
460
461 fn count_similar_patterns(&self, new_pattern: &str) -> u32 {
462 let new_lower = new_pattern.to_lowercase();
463 let new_root = extract_alpha_root(&new_lower);
464
465 let mut count = 0u32;
466 for existing in &self.recent_search_patterns {
467 let existing_lower = existing.to_lowercase();
468 if patterns_are_similar(&new_lower, &existing_lower) {
469 count += 1;
470 } else if new_root.len() >= 4 {
471 let existing_root = extract_alpha_root(&existing_lower);
472 if existing_root.len() >= 4
473 && (new_root.starts_with(&existing_root)
474 || existing_root.starts_with(&new_root))
475 {
476 count += 1;
477 }
478 }
479 }
480 count
481 }
482
483 fn block_message(&self, tool: &str, count: u32) -> String {
484 if Self::is_search_tool(tool) {
485 self.search_block_message(count)
486 } else {
487 format!(
488 "LOOP DETECTED: {tool} called {count}x with same/similar args. \
489 Call blocked. Change your approach — the current strategy is not working."
490 )
491 }
492 }
493
494 #[allow(clippy::unused_self)]
495 fn search_block_message(&self, count: u32) -> String {
496 format!(
497 "LOOP DETECTED: You've searched {count}x with similar patterns. STOP searching and change strategy. \
498 1) Use ctx_tree to understand the project structure first. \
499 2) Narrow your search with the 'path' parameter to a specific directory. \
500 3) Use ctx_read with mode='map' to understand a file before searching more."
501 )
502 }
503
504 fn search_group_block_message(&self, count: u32) -> String {
505 format!(
506 "LOOP DETECTED: {count} search calls in {}s — too many. STOP and rethink. \
507 1) Use ctx_tree to map the project structure. \
508 2) Pick ONE specific directory and search there with the 'path' parameter. \
509 3) Read files with ctx_read mode='map' instead of searching blindly.",
510 self.window.as_secs()
511 )
512 }
513}
514
515fn normalize_shell_command(cmd: &str) -> String {
516 cmd.split_whitespace()
517 .take(5)
518 .collect::<Vec<_>>()
519 .join(" ")
520 .to_lowercase()
521}
522
523fn extract_alpha_root(pattern: &str) -> String {
524 pattern
525 .chars()
526 .take_while(|c| c.is_alphanumeric())
527 .collect()
528}
529
530fn patterns_are_similar(a: &str, b: &str) -> bool {
531 if a == b {
532 return true;
533 }
534 if a.contains(b) || b.contains(a) {
535 return true;
536 }
537 let a_alpha: String = a.chars().filter(|c| c.is_alphanumeric()).collect();
538 let b_alpha: String = b.chars().filter(|c| c.is_alphanumeric()).collect();
539 a_alpha.len() >= 3
540 && b_alpha.len() >= 3
541 && (a_alpha.contains(&b_alpha) || b_alpha.contains(&a_alpha))
542}
543
544fn canonical_json(value: &serde_json::Value) -> String {
545 match value {
546 serde_json::Value::Object(map) => {
547 let mut keys: Vec<&String> = map.keys().collect();
548 keys.sort();
549 let entries: Vec<String> = keys
550 .iter()
551 .map(|k| format!("{}:{}", k, canonical_json(&map[*k])))
552 .collect();
553 format!("{{{}}}", entries.join(","))
554 }
555 serde_json::Value::Array(arr) => {
556 let entries: Vec<String> = arr.iter().map(canonical_json).collect();
557 format!("[{}]", entries.join(","))
558 }
559 _ => value.to_string(),
560 }
561}
562
563#[cfg(test)]
564mod tests {
565 use super::*;
566
567 fn test_config(normal: u32, reduced: u32, blocked: u32) -> LoopDetectionConfig {
568 LoopDetectionConfig {
569 normal_threshold: normal,
570 reduced_threshold: reduced,
571 blocked_threshold: blocked,
572 window_secs: 300,
573 search_group_limit: 10,
574 tool_total_limits: std::collections::HashMap::new(),
575 }
576 }
577
578 #[test]
579 fn normal_calls_pass_through() {
580 let mut detector = LoopDetector::new();
581 let r1 = detector.record_call("ctx_read", "abc123");
582 assert_eq!(r1.level, ThrottleLevel::Normal);
583 assert_eq!(r1.call_count, 1);
584 assert!(r1.message.is_none());
585 }
586
587 #[test]
588 fn repeated_calls_trigger_reduced() {
589 let _lock = crate::core::data_dir::test_env_lock();
590 crate::test_env::set_var("LEAN_CTX_META", "1");
591 let cfg = LoopDetectionConfig::default();
592 let mut detector = LoopDetector::with_config(&cfg);
593 for _ in 0..cfg.normal_threshold {
594 detector.record_call("ctx_read", "same_fp");
595 }
596 let result = detector.record_call("ctx_read", "same_fp");
597 assert_eq!(result.level, ThrottleLevel::Reduced);
598 assert!(result.message.is_some());
599 crate::test_env::remove_var("LEAN_CTX_META");
600 }
601
602 #[test]
603 fn excessive_calls_get_blocked_when_enabled() {
604 let cfg = LoopDetectionConfig {
606 blocked_threshold: 6,
607 ..Default::default()
608 };
609 let mut detector = LoopDetector::with_config(&cfg);
610 for _ in 0..cfg.blocked_threshold {
611 detector.record_call("ctx_shell", "same_fp");
612 }
613 let result = detector.record_call("ctx_shell", "same_fp");
614 assert_eq!(result.level, ThrottleLevel::Blocked);
615 assert!(result.message.unwrap().contains("LOOP DETECTED"));
616 }
617
618 #[test]
619 fn blocking_disabled_by_default() {
620 let cfg = LoopDetectionConfig::default();
622 assert_eq!(cfg.blocked_threshold, 0);
623 let mut detector = LoopDetector::with_config(&cfg);
624 for _ in 0..100 {
626 detector.record_call("ctx_shell", "same_fp");
627 }
628 let result = detector.record_call("ctx_shell", "same_fp");
629 assert_ne!(result.level, ThrottleLevel::Blocked);
631 }
632
633 #[test]
634 fn different_args_tracked_separately() {
635 let mut detector = LoopDetector::new();
636 for _ in 0..10 {
637 detector.record_call("ctx_read", "fp_a");
638 }
639 let result = detector.record_call("ctx_read", "fp_b");
640 assert_eq!(result.level, ThrottleLevel::Normal);
641 assert_eq!(result.call_count, 1);
642 }
643
644 #[test]
645 fn fingerprint_deterministic() {
646 let args = serde_json::json!({"path": "test.rs", "mode": "full"});
647 let fp1 = LoopDetector::fingerprint(&args);
648 let fp2 = LoopDetector::fingerprint(&args);
649 assert_eq!(fp1, fp2);
650 }
651
652 #[test]
653 fn fingerprint_order_independent() {
654 let a = serde_json::json!({"mode": "full", "path": "test.rs"});
655 let b = serde_json::json!({"path": "test.rs", "mode": "full"});
656 assert_eq!(LoopDetector::fingerprint(&a), LoopDetector::fingerprint(&b));
657 }
658
659 #[test]
660 fn stats_shows_duplicates() {
661 let mut detector = LoopDetector::new();
662 for _ in 0..5 {
663 detector.record_call("ctx_read", "fp_a");
664 }
665 detector.record_call("ctx_shell", "fp_b");
666 let stats = detector.stats();
667 assert_eq!(stats.len(), 1);
668 assert_eq!(stats[0].1, 5);
669 }
670
671 #[test]
672 fn reset_clears_state() {
673 let mut detector = LoopDetector::new();
674 for _ in 0..5 {
675 detector.record_call("ctx_read", "fp_a");
676 }
677 detector.reset();
678 let result = detector.record_call("ctx_read", "fp_a");
679 assert_eq!(result.call_count, 1);
680 }
681
682 #[test]
683 fn custom_thresholds_from_config() {
684 let cfg = test_config(1, 2, 3);
685 let mut detector = LoopDetector::with_config(&cfg);
686 detector.record_call("ctx_read", "fp");
687 let r = detector.record_call("ctx_read", "fp");
688 assert_eq!(r.level, ThrottleLevel::Reduced);
689 detector.record_call("ctx_read", "fp");
690 let r = detector.record_call("ctx_read", "fp");
691 assert_eq!(r.level, ThrottleLevel::Blocked);
692 }
693
694 #[test]
695 fn similar_patterns_detected() {
696 assert!(patterns_are_similar("compress", "compress"));
697 assert!(patterns_are_similar("compress", "compression"));
698 assert!(patterns_are_similar("compress.*data", "compress"));
699 assert!(!patterns_are_similar("foo", "bar"));
700 assert!(!patterns_are_similar("ab", "cd"));
701 }
702
703 #[test]
704 fn search_group_tracking_when_blocking_enabled() {
705 let cfg = LoopDetectionConfig {
707 search_group_limit: 5,
708 blocked_threshold: 6, ..Default::default()
710 };
711 let mut detector = LoopDetector::with_config(&cfg);
712 for i in 0..5 {
713 let fp = format!("fp_{i}");
714 let r = detector.record_search("ctx_search", &fp, Some(&format!("pattern_{i}")));
715 assert_ne!(r.level, ThrottleLevel::Blocked, "call {i} should not block");
716 }
717 let r = detector.record_search("ctx_search", "fp_5", Some("pattern_5"));
718 assert_eq!(r.level, ThrottleLevel::Blocked);
719 assert!(r.message.unwrap().contains("search calls"));
720 }
721
722 #[test]
723 fn similar_search_patterns_trigger_block_when_enabled() {
724 let cfg = LoopDetectionConfig {
726 blocked_threshold: 6,
727 ..Default::default()
728 };
729 let mut detector = LoopDetector::with_config(&cfg);
730 let variants = [
731 "compress",
732 "compression",
733 "compress.*data",
734 "compress_output",
735 "compressor",
736 "compress_result",
737 "compress_file",
738 ];
739 for (i, pat) in variants
740 .iter()
741 .enumerate()
742 .take(cfg.blocked_threshold as usize)
743 {
744 detector.record_search("ctx_search", &format!("fp_{i}"), Some(pat));
745 }
746 let r = detector.record_search("ctx_search", "fp_new", Some("compress_all"));
747 assert_eq!(r.level, ThrottleLevel::Blocked);
748 }
749
750 #[test]
751 fn is_search_tool_detection() {
752 assert!(LoopDetector::is_search_tool("ctx_search"));
753 assert!(LoopDetector::is_search_tool("ctx_semantic_search"));
754 assert!(!LoopDetector::is_search_tool("ctx_read"));
755 assert!(!LoopDetector::is_search_tool("ctx_shell"));
756 }
757
758 #[test]
759 fn is_search_shell_command_detection() {
760 assert!(LoopDetector::is_search_shell_command("grep -r foo ."));
761 assert!(LoopDetector::is_search_shell_command("rg pattern src/"));
762 assert!(LoopDetector::is_search_shell_command("find . -name '*.rs'"));
763 assert!(!LoopDetector::is_search_shell_command("cargo build"));
764 assert!(!LoopDetector::is_search_shell_command("git status"));
765 }
766
767 #[test]
768 fn correction_fresh_reread_detected() {
769 let mut detector = LoopDetector::new();
770 detector.record_read_for_correction("src/main.rs", "full", false);
772 detector.record_read_for_correction("src/lib.rs", "full", false);
773 detector.record_read_for_correction("src/util.rs", "full", false);
774 detector.record_read_for_correction("src/main.rs", "full", false);
776 assert_eq!(detector.correction_count(), 0);
777 detector.record_read_for_correction("src/main.rs", "full", true);
779 assert_eq!(detector.correction_count(), 1);
780 }
781
782 #[test]
783 fn correction_mode_bounce_detected() {
784 let mut detector = LoopDetector::new();
785 for i in 0..COLD_START_CALLS {
787 detector.record_read_for_correction(&format!("f{i}.rs"), "full", false);
788 }
789 detector.record_read_for_correction("src/cache.rs", "map", false);
791 assert_eq!(detector.correction_count(), 0);
792 detector.record_read_for_correction("src/cache.rs", "full", false);
794 assert_eq!(detector.correction_count(), 1);
795 }
796
797 #[test]
798 fn retrieve_count_tracks_signals_and_resets() {
799 let mut detector = LoopDetector::new();
802 assert_eq!(detector.retrieve_count(), 0);
803 detector.record_retrieve();
804 detector.record_retrieve();
805 detector.record_retrieve();
806 assert_eq!(detector.retrieve_count(), 3, "three re-fetches counted");
807 assert_eq!(detector.correction_count(), 0);
809 detector.reset();
810 assert_eq!(
811 detector.retrieve_count(),
812 0,
813 "reset clears retrieve signals"
814 );
815 }
816
817 #[test]
818 fn correction_shell_rerun_detected() {
819 let mut detector = LoopDetector::new();
820 for i in 0..COLD_START_CALLS {
822 detector.record_shell_for_correction(&format!("echo {i}"));
823 }
824 detector.record_shell_for_correction("cargo test --lib");
826 assert_eq!(detector.correction_count(), 0);
827 detector.record_shell_for_correction("cargo test --lib");
829 assert_eq!(detector.correction_count(), 1);
830 }
831
832 #[test]
833 fn correction_rate_calculation() {
834 let mut detector = LoopDetector::new();
835 for i in 0..COLD_START_CALLS {
836 detector.record_shell_for_correction(&format!("init{i}"));
837 }
838 detector.record_shell_for_correction("cargo check");
839 detector.record_shell_for_correction("cargo check");
840 detector.record_shell_for_correction("cargo check");
841 assert_eq!(detector.correction_count(), 2);
843 assert!(detector.correction_rate() > 0.0);
844 }
845
846 #[test]
847 fn correction_cold_start_ignored() {
848 let mut detector = LoopDetector::new();
849 detector.record_shell_for_correction("cargo check");
851 detector.record_shell_for_correction("cargo check");
852 detector.record_shell_for_correction("cargo check");
853 assert_eq!(detector.correction_count(), 0);
854 }
855
856 #[test]
857 fn search_block_message_has_guidance_when_blocking_enabled() {
858 let cfg = LoopDetectionConfig {
860 blocked_threshold: 6,
861 search_group_limit: 8,
862 ..Default::default()
863 };
864 let mut detector = LoopDetector::with_config(&cfg);
865 for i in 0..10 {
866 detector.record_search("ctx_search", &format!("fp_{i}"), Some("compress"));
867 }
868 let r = detector.record_search("ctx_search", "fp_new", Some("compress"));
869 assert_eq!(r.level, ThrottleLevel::Blocked);
870 let msg = r.message.unwrap();
871 assert!(msg.contains("ctx_tree"));
872 assert!(msg.contains("path"));
873 assert!(msg.contains("ctx_read"));
874 }
875
876 #[test]
877 fn error_outcome_undoes_pre_dispatch_count() {
878 let cfg = test_config(2, 4, 0);
879 let mut detector = LoopDetector::with_config(&cfg);
880
881 detector.record_call("ctx_read", "fp1");
882 detector.record_call("ctx_read", "fp1");
883 detector.record_error_outcome("ctx_read", "fp1");
884
885 let r = detector.record_call("ctx_read", "fp1");
886 assert_eq!(r.call_count, 2, "error should have undone one count");
887 assert_eq!(r.level, ThrottleLevel::Normal);
888 }
889
890 #[test]
891 fn repeated_errors_dont_trigger_reduced() {
892 let cfg = test_config(2, 4, 0);
893 let mut detector = LoopDetector::with_config(&cfg);
894
895 for _ in 0..5 {
896 detector.record_call("ctx_read", "fp1");
897 detector.record_error_outcome("ctx_read", "fp1");
898 }
899
900 let r = detector.record_call("ctx_read", "fp1");
901 assert_eq!(
902 r.level,
903 ThrottleLevel::Normal,
904 "5 failed retries should not throttle"
905 );
906 }
907
908 #[test]
909 fn mixed_success_and_error_correct_count() {
910 let cfg = test_config(2, 4, 0);
911 let mut detector = LoopDetector::with_config(&cfg);
912
913 detector.record_call("ctx_read", "fp1");
914 detector.record_error_outcome("ctx_read", "fp1");
915 detector.record_call("ctx_read", "fp1");
916 detector.record_error_outcome("ctx_read", "fp1");
917 detector.record_call("ctx_read", "fp1");
918 assert_eq!(detector.record_call("ctx_read", "fp1").call_count, 2);
920 }
921
922 #[test]
923 fn error_outcome_on_nonexistent_key_is_noop() {
924 let mut detector = LoopDetector::new();
925 detector.record_error_outcome("ctx_read", "never_called");
926 let r = detector.record_call("ctx_read", "never_called");
927 assert_eq!(r.call_count, 1);
928 }
929
930 #[test]
931 fn error_outcome_doesnt_go_negative() {
932 let mut detector = LoopDetector::new();
933 detector.record_call("ctx_read", "fp1");
934 detector.record_error_outcome("ctx_read", "fp1");
935 detector.record_error_outcome("ctx_read", "fp1");
936 let r = detector.record_call("ctx_read", "fp1");
937 assert_eq!(r.call_count, 1, "count should never go below 0");
938 }
939
940 #[test]
941 fn error_in_tool_a_doesnt_affect_tool_b() {
942 let cfg = test_config(2, 4, 0);
943 let mut detector = LoopDetector::with_config(&cfg);
944
945 for _ in 0..5 {
946 detector.record_call("ctx_read", "fp1");
947 detector.record_error_outcome("ctx_read", "fp1");
948 }
949
950 let r = detector.record_call("ctx_shell", "fp_shell");
951 assert_eq!(r.call_count, 1);
952 assert_eq!(r.level, ThrottleLevel::Normal);
953 }
954
955 #[test]
956 fn different_fingerprints_independent_after_errors() {
957 let cfg = test_config(2, 4, 0);
958 let mut detector = LoopDetector::with_config(&cfg);
959
960 detector.record_call("ctx_read", "fp_a");
961 detector.record_error_outcome("ctx_read", "fp_a");
962
963 detector.record_call("ctx_read", "fp_b");
964 let r = detector.record_call("ctx_read", "fp_b");
965 assert_eq!(r.call_count, 2);
966
967 let r_a = detector.record_call("ctx_read", "fp_a");
968 assert_eq!(r_a.call_count, 1, "fp_a count should be reset to 0 then +1");
969 }
970
971 #[test]
972 fn correction_degrade_recovery_after_prune() {
973 let mut detector = LoopDetector::new();
974 for i in 0..4u32 {
975 detector.record_read_for_correction(&format!("warmup{i}.rs"), "full", false);
976 }
977 detector.record_read_for_correction("target.rs", "full", false);
978 detector.record_read_for_correction("target.rs", "full", true);
979 assert!(detector.correction_count() > 0);
980 detector.prune_corrections();
981 assert!(detector.correction_count() >= 1);
984 }
985
986 #[test]
987 fn success_after_errors_resets_to_normal() {
988 let cfg = test_config(2, 4, 0);
989 let mut detector = LoopDetector::with_config(&cfg);
990
991 for _ in 0..3 {
992 detector.record_call("ctx_read", "fp1");
993 detector.record_error_outcome("ctx_read", "fp1");
994 }
995
996 let r = detector.record_call("ctx_read", "fp1");
997 assert_eq!(r.level, ThrottleLevel::Normal);
998 assert_eq!(r.call_count, 1);
999 }
1000
1001 #[test]
1002 fn throttle_result_default_is_normal() {
1003 let r = ThrottleResult::default();
1004 assert_eq!(r.level, ThrottleLevel::Normal);
1005 assert_eq!(r.call_count, 0);
1006 assert!(r.message.is_none());
1007 }
1008}