loopctl 0.1.0

A trait-based framework for building agent loops with pluggable LLM clients, tools, and memory
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
//! Detection manager — loop and convergence detection for agent behavior.
//!
//! [`DetectionManager`] unifies two complementary
//! detection strategies into a single manager that agents consult after each turn
//! to decide whether they are making progress or spinning in circles:
//!
//! - **Loop detection** (delegated to [`LoopDetector`]) — identifies repeated
//!   sequences of tool calls using tool-specific JSON parsing, result-aware
//!   comparison, Edit-recovery logic, warning deduplication, and configurable
//!   thresholds.
//! - **Convergence detection** (delegated to [`ConvergenceDetector`]) — detects
//!   when the agent's free-text responses have become semantically similar using
//!   Jaccard similarity on word-level tokens, with a configurable window size,
//!   similarity threshold, and convergence action.
//!
//! Together these detectors power the agent framework's "stuck detection" layer.
//! When either detector fires, the framework can inject a warning, force a
//! strategy change, or terminate the session outright.
//!
//! # Architecture
//!
//! `DetectionManager` is a **facade** that owns one `LoopDetector` and one
//! `ConvergenceDetector`, forwarding calls to each and merging their results
//! into a unified [`DetectedPattern`] enum.
//!
//! **Data flow** — On every agent turn the framework feeds two kinds of
//! telemetry into the manager:
//!
//! 1. *Tool calls* are sent to `record_operation` (or its convenience
//!    wrappers `record_tool_call` / `record_tool_call_with_result`), which
//!    hands the operation to the `LoopDetector`. The loop detector compares
//!    consecutive operations by tool name, primary parameter, and optional
//!    result hash; when the same signature repeats ≥ `loop_threshold`
//!    times it reports a loop.
//!
//! 2. *Assistant responses* (free text) are sent to `record_response`,
//!    which hands the text to the `ConvergenceDetector`. The convergence
//!    detector tokenises the text into words, computes Jaccard similarity
//!    against the previous response, and fires when similarity stays above
//!    `convergence_threshold` for `convergence_count` consecutive turns.
//!
//! **Merging** — `check_current_pattern` queries both detectors and
//! returns the first non-`NoPattern` result. Loop detection takes priority
//! over convergence because a tool-calling loop is a stronger signal of
//! being stuck.
//!
//! **Outcome** — The three possible results are carried by [`DetectedPattern`]:
//! `NoPattern` (agent is making progress), `LoopDetected` (repeated tool
//! calls), or `ConvergenceDetected` (semantically similar responses).
//!
//! # Provided Types
//!
//! - [`DetectionManager`] — facade that owns and delegates to both detectors.
//! - [`DetectionConfig`] — unified configuration for loop + convergence tuning.
//! - [`DetectedPattern`] — summary enum returned by every check method.
//! - [`DetectionStats`] — cumulative statistics exposed for observability.
//!
//! # Quick Start
//!
//! ```rust,ignore
//! use loopctl::detection::manager::{
//!     DetectionConfig, DetectionManager, DetectedPattern,
//! };
//!
//! // Create with defaults (loop threshold 3, convergence threshold 0.95)
//! let dm = DetectionManager::new();
//!
//! // Record tool calls each turn
//! dm.record_tool_call("Read", 42);
//! let pattern = dm.record_tool_call("Read", 42);
//! assert!(matches!(pattern, DetectedPattern::NoPattern));
//!
//! // Record assistant responses for convergence checking
//! dm.record_response("I'm working on the file.");
//!
//! // Inspect current state at any time
//! if let DetectedPattern::LoopDetected { repetitions, .. } = dm.check_current_pattern() {
//!     println!("Agent is looping — {repetitions} repetitions seen");
//! }
//!
//! // Reset between tasks
//! dm.reset();
//! ```
//!
//! # See Also
//!
//! - [`ConvergenceDetector`] — the standalone convergence detector module.
//! - [`LoopDetector`] — the standalone loop detector module.

use std::sync::{Arc, Mutex};

use super::convergence::{ConvergenceConfig, ConvergenceDetector, ConvergenceStatus};
use super::loop_detector::{LoopDetector, LoopDetectorConfig, Operation, ToolSignature};

pub use super::convergence::ConvergenceAction;
pub use super::convergence::ConvergenceConfigError;
pub use super::loop_detector::LoopStatus;

// ==================================================
// Detected Pattern
// ==================================================

/// Represents a pattern detected in agent behavior.
///
/// Returned by [`DetectionManager::record_operation`],
/// [`DetectionManager::record_response`], and
/// [`DetectionManager::check_current_pattern`] to summarise what — if
/// anything — the detector found. Callers typically match on this enum to
/// decide whether to inject a warning, switch strategies, or halt the
/// session.
///
/// # Variants
///
/// - [`LoopDetected`](Self::LoopDetected) — repeated tool-call pattern.
/// - [`ConvergenceDetected`](Self::ConvergenceDetected) — semantically similar responses.
/// - [`NoPattern`](Self::NoPattern) — agent is making progress.
///
/// # Matching Strategy
///
/// The recommended approach is to handle each variant explicitly:
///
/// ```rust,ignore
/// match pattern {
///     DetectedPattern::LoopDetected { repetitions, pattern_description } => {
///         tracing::warn!("Loop detected: {pattern_description} (×{repetitions})");
///     }
///     DetectedPattern::ConvergenceDetected { similarity, consecutive_count } => {
///         tracing::info!("Responses converged (similarity={similarity:.2})");
///     }
///     DetectedPattern::NoPattern => { /* agent is making progress */ }
/// }
/// ```
///
/// # See Also
///
/// - [`DetectionManager::check_current_pattern`] — unified check.
/// - [`DetectionStats`] — cumulative detection counters.
#[derive(Debug, Clone)]
pub enum DetectedPattern {
    /// Repeated tool-call pattern detected.
    ///
    /// Emitted by [`DetectionManager::record_operation`] (and the
    /// convenience wrappers [`DetectionManager::record_tool_call`] /
    /// [`DetectionManager::record_tool_call_with_result`]) when the
    /// [`LoopDetector`] observes the same operation at least
    /// [`DetectionConfig::loop_threshold`] times in a row.
    ///
    /// A "loop" does not mean the agent is calling the *exact same*
    /// tool every time — it means the operation signature (tool name +
    /// primary parameter + optional result hash) has been seen repeatedly.
    /// The loop detector uses result-aware comparison so that calling
    /// the same file with different results is *not* flagged.
    ///
    /// # Fields
    ///
    /// - `repetitions` — how many times the pattern has repeated so far.
    /// - `pattern_description` — a human-readable summary like `"Read(/etc/hosts)"`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // After calling Read("/etc/hosts") 3 times with identical results:
    /// if let DetectedPattern::LoopDetected { repetitions, pattern_description } = pattern {
    ///     assert_eq!(pattern_description, "Read(/etc/hosts)");
    ///     assert!(repetitions >= 3);
    /// }
    /// ```
    LoopDetected {
        /// Equal to [`LoopStatus::repetition_count`].
        repetitions: usize,
        /// Formatted as `"ToolName(primary_param)"`.
        pattern_description: String,
    },
    /// The agent's responses have become semantically similar.
    ///
    /// Emitted by [`DetectionManager::record_response`] when the internal
    /// [`ConvergenceDetector`] finds that the last *N* assistant messages
    /// exceed [`DetectionConfig::convergence_threshold`] in Jaccard
    /// similarity, where *N* equals [`DetectionConfig::convergence_count`].
    ///
    /// Unlike [`LoopDetected`](Self::LoopDetected), which monitors tool
    /// call patterns, this variant tracks the *content* of the agent's
    /// free-text replies. It fires when the agent keeps saying
    /// the same thing in different words — a strong signal that it is
    /// stuck even if it is calling different tools each time.
    ///
    /// # Fields
    ///
    /// - `similarity` — the Jaccard similarity score of the most recent
    ///   pair of responses (0.0–1.0).
    /// - `consecutive_count` — how many consecutive response pairs exceeded
    ///   the threshold.
    ConvergenceDetected {
        /// Jaccard similarity (0.0–1.0) of the most recent response pair.
        similarity: f32,
        /// Consecutive similar responses.
        consecutive_count: usize,
    },
    /// Neither the loop detector nor the convergence detector has fired.
    ///
    /// The agent's tool calls are varying and/or its responses are diverging,
    /// which indicates forward progress. Callers should continue the
    /// turn loop when they receive this variant.
    NoPattern,
}

// ==================================================
// Configuration
// ==================================================

/// Configuration for the [`DetectionManager`].
///
/// Groups all tunables for loop detection and convergence detection in a
/// single struct so consumers can construct a [`DetectionManager`] with
/// one call to [`DetectionManager::new_with_config`].
///
/// The [`Default`] implementation provides sensible production values:
/// loop threshold 3, stop threshold 10, convergence threshold 0.95, and
/// convergence count 3.
///
/// # Sections
///
/// The configuration is divided into two groups:
///
/// - **Loop detection** — [`loop_threshold`](Self::loop_threshold),
///   [`stop_threshold`](Self::stop_threshold),
///   [`enable_loop_detection`](Self::enable_loop_detection),
///   [`max_history`](Self::max_history).
/// - **Convergence detection** —
///   [`convergence_threshold`](Self::convergence_threshold),
///   [`convergence_count`](Self::convergence_count),
///   [`enable_convergence_detection`](Self::enable_convergence_detection),
///   [`on_converge`](Self::on_converge).
///
/// # Example
///
/// ```rust,ignore
/// let config = DetectionConfig {
///     loop_threshold: 5,          // allow more repetition before flagging
///     convergence_threshold: 0.9, // looser similarity threshold
///     ..DetectionConfig::default()
/// };
/// let dm = DetectionManager::new_with_config(config);
/// ```
///
/// # See Also
///
/// - [`DetectionConfig::to_convergence_config`] — converts to [`ConvergenceConfig`].
/// - [`DetectionConfig::to_loop_detector_config`] — converts to [`LoopDetectorConfig`].
#[derive(Debug, Clone)]
pub struct DetectionConfig {
    /// Consecutive similar operations before declaring a loop. Default: **3**.
    pub loop_threshold: usize,
    /// Repetitions triggering forced stop (0 = disabled). Default: **10**.
    pub stop_threshold: usize,
    /// Whether loop detection is enabled. Default: **true**.
    pub enable_loop_detection: bool,
    /// Max operations kept in loop detector history. Default: **100**.
    pub max_history: usize,
    /// Jaccard similarity threshold for convergence (0.0–1.0). Default: **0.95**.
    pub convergence_threshold: f32,
    /// Consecutive similar responses for convergence. Default: **3**.
    pub convergence_count: usize,
    /// Whether convergence detection is enabled. Default: **true**.
    pub enable_convergence_detection: bool,
    /// Action on convergence. Default: [`ConvergenceAction::default()`].
    pub on_converge: ConvergenceAction,
}

impl Default for DetectionConfig {
    fn default() -> Self {
        Self {
            loop_threshold: 3,
            stop_threshold: 10,
            enable_loop_detection: true,
            max_history: 100,
            convergence_threshold: 0.95,
            convergence_count: 3,
            enable_convergence_detection: true,
            on_converge: ConvergenceAction::default(),
        }
    }
}

impl DetectionConfig {
    /// Convert convergence settings into a [`ConvergenceConfig`].
    ///
    /// # Field Mapping
    ///
    /// | `DetectionConfig` field        | [`ConvergenceConfig`] field            |
    /// |--------------------------------|----------------------------------------|
    /// | `enable_convergence_detection` | `enabled`                              |
    /// | `convergence_count`            | `window_size`                          |
    /// | `convergence_threshold`        | `similarity_threshold`                 |
    /// | `on_converge`                  | `on_converge`                          |
    #[must_use]
    pub fn to_convergence_config(&self) -> ConvergenceConfig {
        ConvergenceConfig {
            enabled: self.enable_convergence_detection,
            window_size: self.convergence_count,
            similarity_threshold: self.convergence_threshold,
            on_converge: self.on_converge,
        }
    }

    /// Convert the loop-related settings into a [`LoopDetectorConfig`].
    ///
    /// # Field Mapping
    ///
    /// | `DetectionConfig` field | [`LoopDetectorConfig`] field |
    /// |-------------------------|------------------------------|
    /// | `max_history`           | `window_size`                |
    /// | `loop_threshold`        | `repetition_threshold`       |
    /// | `stop_threshold`        | `stop_threshold`             |
    #[must_use]
    pub fn to_loop_detector_config(&self) -> LoopDetectorConfig {
        LoopDetectorConfig {
            window_size: self.max_history,
            repetition_threshold: self.loop_threshold,
            stop_threshold: self.stop_threshold,
            ..LoopDetectorConfig::default()
        }
    }
}

// ==================================================
// Statistics
// ==================================================

/// Cumulative statistics from the [`DetectionManager`].
///
/// Returned by [`DetectionManager::stats`] for observability and
/// debugging. All counters are monotonically increasing within a session
/// (until [`DetectionManager::reset`] is called).
///
/// [`Clone`] and [`Default`] — can be cheaply snapshot
/// and serialised for logging or UI display.
///
/// # Example
///
/// ```rust,ignore
/// let stats = dm.stats();
/// println!("Turns: {}", stats.turns_analyzed);
/// println!("Loops: {}", stats.loops_detected);
/// println!("Convergences: {}", stats.convergences_detected);
/// println!("Current streak: {}", stats.current_streak);
/// ```
///
/// # See Also
///
/// - [`DetectionManager::stats`] — the accessor that returns snapshots of this type.
/// - [`DetectionManager::reset`] — zeroes all counters.
#[derive(Debug, Clone, Default)]
pub struct DetectionStats {
    /// Tool-call operations recorded via `record_operation`. Reset by `reset`.
    pub turns_analyzed: usize,
    /// Subset of `turns_analyzed` that returned `LoopDetected`. Reset by `reset`.
    pub loops_detected: usize,
    /// Times `record_response` returned `ConvergenceDetected`. Reset by `reset`.
    pub convergences_detected: usize,
    /// Mirrors `LoopStatus::repetition_count`. Triggers `LoopDetected` at `loop_threshold`. Reset by `reset`.
    pub current_streak: usize,
}

// ==================================================
// Detection Manager
// ==================================================

/// Unified manager combining loop detection and convergence detection.
///
/// [`DetectionManager`] is the primary entry point for the detection
/// subsystem. It owns a [`LoopDetector`] (wrapped in `Arc` for cheap
/// sharing across compaction and response-analysis phases) and a
/// [`ConvergenceDetector`] (wrapped in `Mutex` for interior mutability).
///
/// # Construction
///
/// Choose a constructor based on your needs:
///
/// | Constructor                              | Use case                                  |
/// |------------------------------------------|-------------------------------------------|
/// | [`DetectionManager::new`]                | Quick start with defaults                 |
/// | [`DetectionManager::new_with_config`]        | Custom thresholds via [`DetectionConfig`] |
/// | [`DetectionManager::new_with_loop_detector`] | Inject a pre-built [`LoopDetector`]       |
/// | [`DetectionManager::new_with_signature`]     | Custom [`ToolSignature`] for JSON parsing |
///
/// # Loop Detection
///
/// Use [`Self::record_operation`] to record tool calls. Loop status is
/// checked via [`Self::check_loop`], which delegates to the internal
/// [`LoopDetector`].
///
/// # Convergence Detection
///
/// Record assistant responses via [`Self::record_response`] and check
/// for semantic similarity using [`Self::check_convergence`]. Both
/// delegate to the [`ConvergenceDetector`].
///
/// # Direct Access
///
/// For consumers that need direct access to the underlying detectors
/// (e.g., for compaction phases or response analysis phases), use
/// [`Self::loop_detector`] and [`Self::convergence_detector`].
///
/// # Lifecycle
///
/// The manager progresses through a simple per-turn cycle:
///
/// 1. **Construct** — `new()` or `new_with_config()`.
/// 2. **Feed** — call `record_operation(op)` for each tool invocation and
///    `record_response(text)` for each assistant reply.
/// 3. **Check** — call `check_loop()`, `check_convergence()`, or the
///    combined `check_current_pattern()` after each turn.
/// 4. **Observe** — call `stats()` at any time for cumulative counters.
/// 5. **Reset** — call `reset()` between tasks to clear all history.
///
/// # Example
///
/// ```rust,ignore
/// let dm = DetectionManager::new();
///
/// // Record tool calls
/// let pattern = dm.record_tool_call("Read", file_hash);
/// if let DetectedPattern::LoopDetected { repetitions, .. } = pattern {
///     tracing::warn!("Loop after {repetitions} reps");
/// }
///
/// // Record responses
/// dm.record_response("Working on step 1...");
///
/// // Query at any time
/// let stats = dm.stats();
/// println!("Turns: {}, Loops: {}", stats.turns_analyzed, stats.loops_detected);
///
/// // Reset between tasks
/// dm.reset();
/// ```
///
/// # Thread Safety
///
/// All public methods take `&self`. The two `Mutex` fields
/// (`convergence_detector` and `stats`) provide interior mutability,
/// so the manager can be shared across threads without a `mut` reference.
///
/// # See Also
///
/// - [`DetectionConfig`] — construction configuration.
/// - [`DetectedPattern`] — the result type returned by check methods.
/// - [`DetectionStats`] — cumulative observability counters.
pub struct DetectionManager {
    /// Configuration thresholds and feature flags.
    config: DetectionConfig,
    /// Loop detector shared across compaction and analysis phases.
    loop_detector: Arc<LoopDetector>,
    /// Convergence detector guarded by interior mutability.
    convergence_detector: Mutex<ConvergenceDetector>,
    /// Cumulative detection statistics.
    stats: Mutex<DetectionStats>,
}

impl DetectionManager {
    /// Create a new detection manager with default configuration.
    ///
    /// Convenience wrapper around [`Self::new_with_config`] that passes
    /// [`DetectionConfig::default`]. Suitable for quick prototyping or
    /// when the default thresholds (loop=3, stop=10, convergence=0.95)
    /// are acceptable.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let dm = DetectionManager::new();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ConvergenceConfigError`] if the convergence configuration
    /// is invalid (e.g., threshold out of range, window too small).
    pub fn new() -> Result<Self, ConvergenceConfigError> {
        Self::new_with_config(DetectionConfig::default())
    }

    /// Create a new detection manager with custom configuration.
    ///
    /// For tool-specific JSON parsing, use [`Self::new_with_signature`] or
    /// [`Self::new_with_loop_detector`] instead.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = DetectionConfig {
    ///     loop_threshold: 5,
    ///     ..DetectionConfig::default()
    /// };
    /// let dm = DetectionManager::new_with_config(config);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ConvergenceConfigError`] if the convergence configuration
    /// is invalid (e.g., threshold out of range, window too small).
    pub fn new_with_config(config: DetectionConfig) -> Result<Self, ConvergenceConfigError> {
        let loop_detector = Arc::new(LoopDetector::new(
            config.to_loop_detector_config(),
            Arc::new(super::loop_detector::NoOpToolSignature),
        ));
        let convergence_detector =
            Mutex::new(ConvergenceDetector::new(config.to_convergence_config())?);
        Ok(Self {
            config,
            loop_detector,
            convergence_detector,
            stats: Mutex::new(DetectionStats::default()),
        })
    }

    /// Create with an explicit [`LoopDetector`] instance.
    ///
    /// Use this when the caller has already constructed a [`LoopDetector`]
    /// with a custom [`ToolSignature`] or non-default thresholds and wants
    /// to inject it directly.
    ///
    /// This constructor **does not** use the `loop_threshold`, `stop_threshold`,
    /// or `max_history` fields from `config` — those are already baked into
    /// the provided `loop_detector`. Only the convergence-related fields
    /// are read from `config`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let ld = LoopDetector::new(ld_config, my_signature);
    /// let dm = DetectionManager::new_with_loop_detector(config, ld);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ConvergenceConfigError`] if the convergence configuration
    /// is invalid (e.g., threshold out of range, window too small).
    pub fn new_with_loop_detector(
        config: DetectionConfig,
        loop_detector: LoopDetector,
    ) -> Result<Self, ConvergenceConfigError> {
        let convergence_detector =
            Mutex::new(ConvergenceDetector::new(config.to_convergence_config())?);
        Ok(Self {
            config,
            loop_detector: Arc::new(loop_detector),
            convergence_detector,
            stats: Mutex::new(DetectionStats::default()),
        })
    }

    /// Create with a specific [`ToolSignature`] for tool-specific parsing.
    ///
    /// Useful when the consumer provides its own tool-aware signature
    /// (e.g., `DchToolSignature` for dch.sh tools that extracts
    /// `file_path` from JSON inputs).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let signature = Arc::new(MyToolSignature);
    /// let dm = DetectionManager::new_with_signature(signature);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`ToolSignature`] — the trait for tool-specific JSON parsing.
    /// - [`Operation::from_input_with_signature`] — creates operations using a signature.
    ///
    /// # Errors
    ///
    /// Returns [`ConvergenceConfigError`] if the convergence configuration
    /// is invalid (e.g., threshold out of range, window too small).
    pub fn new_with_signature(
        signature: Arc<dyn ToolSignature>,
    ) -> Result<Self, ConvergenceConfigError> {
        let config = DetectionConfig::default();
        let mut ldc = config.to_loop_detector_config();
        ldc.tool_thresholds = signature.tool_thresholds();
        let loop_detector = Arc::new(LoopDetector::new(ldc, signature));
        let convergence_detector =
            Mutex::new(ConvergenceDetector::new(config.to_convergence_config())?);
        let stats = Mutex::new(DetectionStats::default());
        Ok(Self {
            config,
            loop_detector,
            convergence_detector,
            stats,
        })
    }

    // ==================================================
    // Loop detection (delegated to LoopDetector)
    // ==================================================

    /// Record an [`Operation`] for loop detection and return the current
    /// [`DetectedPattern`].
    ///
    /// Primary entry point for feeding data into the loop
    /// detector. It performs three steps:
    ///
    /// 1. Forwards `operation` to [`LoopDetector::record`].
    /// 2. Calls [`LoopDetector::check_loop`] to evaluate the new state.
    /// 3. Updates [`DetectionStats`] and returns the appropriate
    ///    [`DetectedPattern`] variant.
    ///
    /// When [`DetectionConfig::enable_loop_detection`] is `false`, this
    /// method short-circuits and returns [`DetectedPattern::NoPattern`]
    /// without touching the loop detector or statistics.
    ///
    /// # When called
    ///
    /// After every tool invocation during an agent turn — typically by the
    /// framework's turn-processing loop or by the convenience wrappers
    /// [`Self::record_tool_call`] / [`Self::record_tool_call_with_result`].
    ///
    /// # Returns
    ///
    /// - [`DetectedPattern::LoopDetected`] if the same operation has been
    ///   seen ≥ [`DetectionConfig::loop_threshold`] times consecutively.
    /// - [`DetectedPattern::NoPattern`] otherwise.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let op = Operation::new("Read", "/etc/hosts");
    /// match dm.record_operation(op) {
    ///     DetectedPattern::LoopDetected { repetitions, pattern_description } => {
    ///         tracing::warn!("Loop: {pattern_description} (×{repetitions})");
    ///     }
    ///     _ => { /* no loop yet */ }
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::record_tool_call`] — convenience wrapper for hash-based calls.
    /// - [`Self::record_tool_call_with_result`] — result-aware variant.
    /// - [`Self::check_loop`] — read-only query without recording.
    pub fn record_operation(&self, operation: Operation) -> DetectedPattern {
        if !self.config.enable_loop_detection {
            return DetectedPattern::NoPattern;
        }

        self.loop_detector.record(operation);

        let status = self.loop_detector.check_loop();
        if status.is_looping {
            let mut guard = self.stats.lock().unwrap_or_else(|e| {
                tracing::warn!("stats lock poisoned, recovering");
                e.into_inner()
            });
            guard.turns_analyzed = guard.turns_analyzed.saturating_add(1);
            guard.loops_detected = guard.loops_detected.saturating_add(1);
            guard.current_streak = status.repetition_count;
            DetectedPattern::LoopDetected {
                repetitions: status.repetition_count,
                pattern_description: status
                    .repeated_operations
                    .first()
                    .map(|op| format!("{}({})", op.tool, op.primary_param))
                    .unwrap_or_default(),
            }
        } else {
            let mut guard = self.stats.lock().unwrap_or_else(|e| {
                tracing::warn!("stats lock poisoned, recovering");
                e.into_inner()
            });
            guard.turns_analyzed = guard.turns_analyzed.saturating_add(1);
            DetectedPattern::NoPattern
        }
    }

    /// Returns the tool signature used for extracting primary parameters.
    ///
    /// Useful when callers need to construct [`Operation`]s directly using
    /// the configured [`ToolSignature`].
    pub fn signature(&self) -> &dyn ToolSignature {
        self.loop_detector.signature()
    }

    /// Record a tool call for loop detection by tool name and input hash.
    ///
    /// Creates an [`Operation`] from a `tool` name and `input_hash`, then
    /// delegates to [`Self::record_operation`]. Easiest way to
    /// feed data into the loop detector when you only need a numeric hash
    /// as the primary parameter rather than a full JSON-based signature.
    ///
    /// The resulting [`Operation`] will have `primary_param` set to
    /// `"hash:{input_hash}"` and no result hash.
    ///
    /// For richer tool-specific parsing (e.g., extracting `file_path` from
    /// a JSON input), construct an [`Operation`] with
    /// [`Operation::from_input_with_signature`] and call
    /// [`Self::record_operation`] directly.
    ///
    /// # When called
    ///
    /// After each tool invocation during an agent turn when only a hash
    /// identity is available.
    ///
    /// # Returns
    ///
    /// Same as [`Self::record_operation`] — either
    /// [`DetectedPattern::LoopDetected`] or [`DetectedPattern::NoPattern`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let pattern = dm.record_tool_call("Bash", 0xABCD);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::record_tool_call_with_result`] — adds result hashing for progress detection.
    /// - [`Self::record_operation`] — full API with arbitrary [`Operation`] values.
    pub fn record_tool_call(&self, tool: &str, input_hash: u64) -> DetectedPattern {
        let operation = Operation::new(tool, format!("hash:{input_hash}"));
        self.record_operation(operation)
    }

    /// Record a tool call with a result hash for result-aware loop detection.
    ///
    /// Behaves like [`Self::record_tool_call`] but also accepts an optional
    /// `result_hash`. When the same tool + input produces *different* result
    /// hashes across turns, the loop detector considers the agent to be
    /// making progress — even though the tool and input are identical. Only
    /// when both input and result match across consecutive calls is a loop
    /// flagged.
    ///
    /// Important for tools like `Read` where calling the same file
    /// is perfectly fine if the file content is changing (e.g., the agent
    /// is editing it).
    ///
    /// # How it works
    ///
    /// With result hashing, the detector distinguishes between a tool
    /// that returns the same output every time (a genuine loop) and one
    /// whose output changes between calls (the agent is making progress).
    /// For example, calling `Read("/foo.txt")` three times with the same
    /// result hash is flagged as a loop, but if the file is being edited
    /// between reads the result hashes will differ and no loop is
    /// reported.
    ///
    /// # When called
    ///
    /// After each tool invocation when the caller has access to the tool's
    /// output and can compute a representative hash (e.g., via
    /// [`hash_result`](super::loop_detector::hash_result)).
    ///
    /// # Returns
    ///
    /// Same as [`Self::record_operation`] — either
    /// [`DetectedPattern::LoopDetected`] or [`DetectedPattern::NoPattern`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Same tool + input, different results → not a loop
    /// for i in 0..5 {
    ///     let result = hash_result(&format!("output {i}"));
    ///     dm.record_tool_call_with_result("Bash", 42, result);
    /// }
    /// assert!(matches!(dm.check_loop().is_looping, false));
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Operation::with_result_hash`] — attaches a result hash to an operation.
    /// - [`hash_result`] — utility for computing result hashes.
    ///
    /// [`hash_result`]: super::loop_detector::hash_result
    pub fn record_tool_call_with_result(
        &self,
        tool: &str,
        input_hash: u64,
        result_hash: Option<u64>,
    ) -> DetectedPattern {
        let operation =
            Operation::new(tool, format!("hash:{input_hash}")).with_result_hash(result_hash);
        self.record_operation(operation)
    }

    /// Query the [`LoopDetector`] for the current loop status.
    ///
    /// Returns a full [`LoopStatus`] snapshot including repetition counts,
    /// the `should_stop` flag, and any warning message. Unlike
    /// [`Self::record_operation`], this method does **not** modify any
    /// state — it is a pure read.
    ///
    /// # When called
    ///
    /// By the framework's turn-processing loop after each turn, or by
    /// any observability layer that needs to report loop status without
    /// side effects.
    ///
    /// # Returns
    ///
    /// A [`LoopStatus`] with [`LoopStatus::is_looping`] set to `true` if
    /// the repetition count has reached [`DetectionConfig::loop_threshold`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let status = dm.check_loop();
    /// if status.should_stop {
    ///     tracing::error!("Forcing stop — loop detected: {:?}", status.warning);
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::record_operation`] — records an operation *and* checks for loops.
    /// - [`Self::check_current_pattern`] — checks both loop and convergence.
    #[must_use]
    pub fn check_loop(&self) -> LoopStatus {
        self.loop_detector.check_loop()
    }

    /// Obtain a shared reference to the [`LoopDetector`].
    ///
    /// Useful for direct access to loop state, e.g. inspecting
    /// the turn count or history during diagnostics.
    ///
    /// # When called
    ///
    /// By internal subsystems that need direct access to the loop
    /// detector's methods (e.g., to query [`LoopDetector::turn_count`])
    /// without going through the [`DetectionManager`] facade.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let ld = dm.loop_detector();
    /// println!("Turns seen by loop detector: {}", ld.turn_count());
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::convergence_detector`] — access to the convergence detector.
    #[must_use]
    pub fn loop_detector(&self) -> &LoopDetector {
        &self.loop_detector
    }

    /// Obtain a shared reference to the [`ConvergenceDetector`].
    ///
    /// Returns `&Mutex<ConvergenceDetector>` so callers can lock and
    /// invoke methods on the convergence detector directly — for example
    /// to call [`ConvergenceDetector::check_convergence`] or inspect its
    /// internal window during a response-analysis phase.
    ///
    /// # Thread safety
    ///
    /// The returned `Mutex` guards the detector's mutable state. Callers
    /// must lock before accessing. If the lock is poisoned (due to a panic
    /// in another thread), the framework recovers automatically in
    /// [`Self::record_response`] and [`Self::check_convergence`].
    ///
    /// # When called
    ///
    /// By internal subsystems that need direct access to the convergence
    /// detector without going through the [`DetectionManager`] facade.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cd = dm.convergence_detector();
    /// let status = cd.lock().unwrap().check_convergence();
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::loop_detector`] — access to the loop detector.
    #[must_use]
    pub fn convergence_detector(&self) -> &Mutex<ConvergenceDetector> {
        &self.convergence_detector
    }

    // ==================================================
    // Convergence detection
    // ==================================================

    /// Record an assistant response for convergence detection.
    ///
    /// Forwards `response` to the [`ConvergenceDetector`] via
    /// [`ConvergenceDetector::add_response`], which computes Jaccard
    /// similarity against the previous response and updates the
    /// consecutive-similarity counter.
    ///
    /// If the similarity score exceeds
    /// [`DetectionConfig::convergence_threshold`] for
    /// [`DetectionConfig::convergence_count`] consecutive turns, this
    /// method returns [`DetectedPattern::ConvergenceDetected`] and
    /// increments [`DetectionStats::convergences_detected`].
    ///
    /// When [`DetectionConfig::enable_convergence_detection`] is `false`,
    /// this method short-circuits and returns [`DetectedPattern::NoPattern`]
    /// without touching the convergence detector or statistics.
    ///
    /// # When called
    ///
    /// After each assistant response during an agent turn — typically by
    /// the framework's turn-processing loop.
    ///
    /// # Returns
    ///
    /// - [`DetectedPattern::ConvergenceDetected`] if the last *N*
    ///   responses exceed the similarity threshold.
    /// - [`DetectedPattern::NoPattern`] otherwise.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let pattern = dm.record_response("I'm still working on the task.");
    /// if let DetectedPattern::ConvergenceDetected { similarity, .. } = pattern {
    ///     tracing::warn!("Responses converging (similarity={similarity:.2})");
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::check_convergence`] — read-only check without recording.
    /// - [`Self::record_operation`] — the loop-detection counterpart for tool calls.
    pub fn record_response(&self, response: &str) -> DetectedPattern {
        if !self.config.enable_convergence_detection {
            return DetectedPattern::NoPattern;
        }

        let status = self
            .convergence_detector
            .lock()
            .unwrap_or_else(|e| {
                tracing::warn!("convergence detector lock poisoned, recovering");
                e.into_inner()
            })
            .add_response(response);

        if status.detected {
            let mut guard = self.stats.lock().unwrap_or_else(|e| {
                tracing::warn!("stats lock poisoned, recovering");
                e.into_inner()
            });
            guard.convergences_detected = guard.convergences_detected.saturating_add(1);
            return DetectedPattern::ConvergenceDetected {
                similarity: status.similarity_score,
                consecutive_count: status.consecutive_count,
            };
        }
        DetectedPattern::NoPattern
    }

    /// Query the [`ConvergenceDetector`] for the current
    /// convergence status.
    ///
    /// Returns a full [`ConvergenceStatus`] snapshot including the
    /// similarity score, consecutive count, and detection flag. Unlike
    /// [`Self::record_response`], this method does **not** add a new
    /// response — it is a pure read of the detector's current state.
    ///
    /// # When called
    ///
    /// By the framework's turn-processing loop or observability layers
    /// that need to inspect convergence state without side effects.
    ///
    /// # Returns
    ///
    /// A [`ConvergenceStatus`] with [`ConvergenceStatus::detected`] set
    /// to `true` if the similarity threshold has been exceeded for enough
    /// consecutive turns.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let status = dm.check_convergence();
    /// println!("Similarity: {:.2}", status.similarity_score);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::record_response`] — records a response *and* checks convergence.
    /// - [`Self::check_current_pattern`] — checks both loop and convergence.
    #[must_use]
    pub fn check_convergence(&self) -> ConvergenceStatus {
        self.convergence_detector
            .lock()
            .unwrap_or_else(|e| {
                tracing::warn!("convergence detector lock poisoned, recovering");
                e.into_inner()
            })
            .check_convergence()
    }

    // ==================================================
    // Pattern check
    // ==================================================

    /// Inspect the current detection state without recording new data.
    ///
    /// Checks both the loop detector and the convergence detector in
    /// sequence and returns the first non-`NoPattern` result (loop takes
    /// priority over convergence). **Read-only** operation —
    /// no statistics are updated and no new data is recorded.
    ///
    /// # Priority order
    ///
    /// Loop detection is checked first. If the loop detector reports a
    /// loop, `LoopDetected` is returned immediately. Only when no loop is
    /// found does the manager query the convergence detector. If neither
    /// detector has fired, `NoPattern` is returned. Loop takes priority
    /// because a tool-calling loop is a stronger and more urgent signal
    /// that the agent is stuck.
    ///
    /// # When called
    ///
    /// By the framework when it needs a quick snapshot of whether anything
    /// has been detected so far — for example before deciding whether to
    /// inject a warning into the agent's context or terminate the session.
    ///
    /// # Returns
    ///
    /// - [`DetectedPattern::LoopDetected`] if the loop detector is
    ///   currently flagging a loop.
    /// - [`DetectedPattern::ConvergenceDetected`] if no loop was found
    ///   but the convergence detector has fired.
    /// - [`DetectedPattern::NoPattern`] if neither detector has fired.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// match dm.check_current_pattern() {
    ///     DetectedPattern::LoopDetected { repetitions, .. } => {
    ///         tracing::warn!("Loop detected: {repetitions} reps");
    ///     }
    ///     DetectedPattern::ConvergenceDetected { similarity, .. } => {
    ///         tracing::info!("Converging: similarity={similarity:.2}");
    ///     }
    ///     DetectedPattern::NoPattern => { /* all clear */ }
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::check_loop`] — loop-only check.
    /// - [`Self::check_convergence`] — convergence-only check.
    #[must_use]
    pub fn check_current_pattern(&self) -> DetectedPattern {
        let loop_status = self.loop_detector.check_loop();
        if loop_status.is_looping {
            return DetectedPattern::LoopDetected {
                repetitions: loop_status.repetition_count,
                pattern_description: loop_status
                    .repeated_operations
                    .first()
                    .map(|op| format!("{}({})", op.tool, op.primary_param))
                    .unwrap_or_default(),
            };
        }
        let convergence = self.check_convergence();
        if convergence.detected {
            return DetectedPattern::ConvergenceDetected {
                similarity: convergence.similarity_score,
                consecutive_count: convergence.consecutive_count,
            };
        }
        DetectedPattern::NoPattern
    }

    // ==================================================
    // Accessors
    // ==================================================

    /// Take a snapshot of the cumulative detection statistics.
    ///
    /// Clones the [`DetectionStats`] struct via the `Mutex`,
    /// and returns it. The snapshot reflects all operations recorded since
    /// the last [`Self::reset`] call (or since construction).
    ///
    /// # When called
    ///
    /// By observability layers, logging, or UI code that needs to display
    /// detection metrics.
    ///
    /// # Returns
    ///
    /// A cloned [`DetectionStats`] with current counter values.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let stats = dm.stats();
    /// println!("Turns: {}, Loops: {}, Convergences: {}",
    ///     stats.turns_analyzed,
    ///     stats.loops_detected,
    ///     stats.convergences_detected,
    /// );
    /// ```
    ///
    /// # See Also
    ///
    /// - [`DetectionStats`] — the struct returned by this method.
    /// - [`Self::reset`] — zeroes all counters.
    #[must_use]
    pub fn stats(&self) -> DetectionStats {
        self.stats
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    /// Obtain a reference to the configuration snapshot.
    ///
    /// The returned [`DetectionConfig`] is the same one passed at
    /// construction time. Because it is stored immutably inside the
    /// [`DetectionManager`], it can be read without taking any locks.
    ///
    /// # When called
    ///
    /// By any code that needs to inspect the current thresholds or
    /// feature flags — for example to log them at startup or to decide
    /// whether to skip a detection step.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cfg = dm.config();
    /// if !cfg.enable_loop_detection {
    ///     tracing::info!("Loop detection is disabled");
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`DetectionConfig`] — full description of all config fields.
    /// - [`Self::new_with_config`] — the constructor that accepts a config.
    #[must_use]
    pub fn config(&self) -> &DetectionConfig {
        &self.config
    }

    // ==================================================
    // Reset
    // ==================================================

    /// Reset all internal detection state, as if the manager were freshly
    /// constructed.
    ///
    /// Clears the [`LoopDetector`] history via [`LoopDetector::reset`],
    /// wipes the [`ConvergenceDetector`] window via
    /// [`ConvergenceDetector::clear`], and zeroes out all counters in
    /// [`DetectionStats`]. Use this between independent tasks or when the
    /// agent starts a new sub-goal.
    ///
    /// # What is reset
    ///
    /// | Component | Effect |
    /// |-----------|--------|
    /// | [`LoopDetector`] | History, repetition counts, warnings |
    /// | [`ConvergenceDetector`] | Response window, similarity scores |
    /// | [`DetectionStats`] | All counters zeroed |
    /// | [`DetectionConfig`] | **Not** reset — preserved from construction |
    ///
    /// # When called
    ///
    /// By the framework when transitioning between tasks, or manually by
    /// test code that needs a clean slate.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// dm.record_tool_call("Read", 42);
    /// dm.record_response("Working on step 1...");
    /// dm.reset();
    /// assert!(matches!(dm.check_current_pattern(), DetectedPattern::NoPattern));
    /// assert_eq!(dm.stats().turns_analyzed, 0);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`Self::stats`] — check the stats before resetting.
    /// - [`LoopDetector::reset`] — the underlying reset.
    pub fn reset(&self) {
        self.loop_detector.reset();
        self.convergence_detector
            .lock()
            .unwrap_or_else(|e| {
                tracing::warn!("convergence detector lock poisoned, recovering");
                e.into_inner()
            })
            .clear();
        *self
            .stats
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = DetectionStats::default();
    }
}

impl Default for DetectionManager {
    fn default() -> Self {
        let config = DetectionConfig::default();
        let loop_config = config.to_loop_detector_config();
        let loop_detector = Arc::new(LoopDetector::new(
            loop_config,
            Arc::new(super::loop_detector::NoOpToolSignature),
        ));
        let convergence_detector = Mutex::new(ConvergenceDetector::default());
        Self {
            config,
            loop_detector,
            convergence_detector,
            stats: Mutex::new(DetectionStats::default()),
        }
    }
}

// ==================================================
// Tests
// ==================================================

/// Tests for [`DetectionManager`].
///
/// Verifies loop detection, convergence detection, result-aware detection,
/// reset behaviour, feature-flag toggling, stop thresholds, rich [`Operation`]
/// recording, and config mapping.
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_no_pattern_initially() {
        let dm = DetectionManager::new().unwrap();
        assert!(matches!(
            dm.check_current_pattern(),
            DetectedPattern::NoPattern
        ));
    }

    #[test]
    fn test_loop_detection() {
        let dm = DetectionManager::new().unwrap();
        // Same operation repeated many times
        for _ in 0..5 {
            let result = dm.record_tool_call("read_file", 42);
            if matches!(result, DetectedPattern::LoopDetected { .. }) {
                return; // test passes
            }
        }
        panic!("Expected loop detection after 5 identical calls");
    }

    #[test]
    fn test_convergence_detection() {
        let dm = DetectionManager::new().unwrap();
        let response = "I am working on the task and making progress";
        for _ in 0..5 {
            let result = dm.record_response(response);
            if matches!(result, DetectedPattern::ConvergenceDetected { .. }) {
                return; // test passes
            }
        }
        panic!("Expected convergence detection after 5 identical responses");
    }

    #[test]
    fn test_reset() {
        let dm = DetectionManager::new().unwrap();
        dm.record_tool_call("read_file", 42);
        dm.record_response("hello");
        dm.reset();
        assert!(matches!(
            dm.check_current_pattern(),
            DetectedPattern::NoPattern
        ));
        let stats = dm.stats();
        assert_eq!(stats.turns_analyzed, 0);
    }

    #[test]
    fn test_no_detection_when_disabled() {
        let config = DetectionConfig {
            enable_loop_detection: false,
            enable_convergence_detection: false,
            ..Default::default()
        };
        let dm = DetectionManager::new_with_config(config).unwrap();
        for _ in 0..10 {
            let result = dm.record_tool_call("read_file", 42);
            assert!(matches!(result, DetectedPattern::NoPattern));
        }
    }

    #[test]
    fn test_loop_status_should_stop() {
        let config = DetectionConfig {
            loop_threshold: 3,
            stop_threshold: 5,
            ..Default::default()
        };
        let dm = DetectionManager::new_with_config(config).unwrap();

        // Record 5 identical operations
        for _ in 0..5 {
            dm.record_tool_call("read_file", 42);
        }

        let status = dm.check_loop();
        assert!(status.is_looping);
        assert!(status.should_stop);
        assert!(status.warning.is_some());
        assert!(status.warning.unwrap().contains("STOPPING"));
    }

    #[test]
    fn test_record_operation_with_operation_struct() {
        let dm = DetectionManager::new().unwrap();

        // Record operations using the rich Operation API
        for _ in 0..5 {
            dm.record_operation(Operation::new("Read", "/test/file.txt"));
        }

        let status = dm.check_loop();
        assert!(status.is_looping);
        assert!(status.repetition_count >= 3);
    }

    #[test]
    fn test_record_operation_from_input() {
        use super::super::loop_detector::NoOpToolSignature;
        let dm = DetectionManager::new().unwrap();
        let input = serde_json::json!({"file_path": "/test/file.txt"});

        for _ in 0..5 {
            dm.record_operation(Operation::from_input_with_signature(
                "Read",
                &input,
                &NoOpToolSignature,
            ));
        }

        let status = dm.check_loop();
        // With NoOpToolSignature, primary_param is empty, so all "Read" ops
        // with empty param will be identical — loop is detected.
        assert!(status.is_looping);
    }

    #[test]
    fn test_result_aware_detection() {
        let dm = DetectionManager::new().unwrap();

        // Same operation, different results = not a loop
        for i in 0..5 {
            let hash = super::super::loop_detector::hash_result(&format!("output {i}"));
            dm.record_tool_call_with_result("Bash", 42, hash);
        }

        let status = dm.check_loop();
        assert!(!status.is_looping, "Different results should not be a loop");
    }

    #[test]
    fn test_result_aware_same_result_is_loop() {
        let dm = DetectionManager::new().unwrap();

        let hash = super::super::loop_detector::hash_result("same output");
        for _ in 0..5 {
            dm.record_tool_call_with_result("Bash", 42, hash);
        }

        let status = dm.check_loop();
        assert!(status.is_looping, "Same results should be detected as loop");
    }

    #[test]
    fn test_access_loop_detector() {
        let dm = DetectionManager::new().unwrap();
        // Should be able to access the inner LoopDetector
        assert_eq!(dm.loop_detector().turn_count(), 0);
    }

    #[test]
    fn test_config_to_loop_detector_config() {
        let config = DetectionConfig {
            loop_threshold: 5,
            stop_threshold: 15,
            max_history: 200,
            ..Default::default()
        };
        let ldc = config.to_loop_detector_config();
        assert_eq!(ldc.repetition_threshold, 5);
        assert_eq!(ldc.stop_threshold, 15);
        assert_eq!(ldc.window_size, 200);
    }

    #[test]
    fn test_detection_config_default_has_no_max_response_history() {
        let config = DetectionConfig {
            loop_threshold: 3,
            stop_threshold: 5,
            ..Default::default()
        };
        assert_eq!(config.loop_threshold, 3);
        assert_eq!(config.stop_threshold, 5);
        let default = DetectionConfig::default();
        assert_eq!(default.loop_threshold, 3);
        assert_eq!(default.stop_threshold, 10);
        assert!(default.enable_loop_detection);
        assert_eq!(default.max_history, 100);
        assert!((default.convergence_threshold - 0.95).abs() < f32::EPSILON);
        assert_eq!(default.convergence_count, 3);
        assert!(default.enable_convergence_detection);
    }
}