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
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
//! Fallback manager — circuit breaker pattern for automatic API model fallback.
//!
//! When the primary LLM API begins failing repeatedly (rate limits, server errors,
//! timeouts), this module automatically switches to a fallback model and later
//! attempts to recover the primary once it appears healthy again. It implements the
//! classic three-state circuit breaker: **Closed** (primary) → **Open** (fallback) →
//! **Half-Open** (recovering) → back to **Closed**.
//!
//! # Why a circuit breaker?
//!
//! Calling a degraded API repeatedly wastes tokens, increases latency, and can
//! cascade failures. By tripping the circuit after a configurable number of
//! consecutive failures, the agent loop immediately routes subsequent requests to
//! a working fallback model. After a cooldown period, the manager probes the
//! primary with a few trial requests; if they succeed, the circuit closes and
//! normal operation resumes.
//!
//! # Provided types
//!
//! - **[`FallbackState`]** — The three circuit-breaker states (`Primary`, `Fallback`, `Recovering`).
//! - **[`FallbackConfig`]** — Configuration struct with thresholds and timeouts.
//! - **[`FallbackManager`]** — The state machine itself; thread-safe via atomics and `Mutex`.
//!
//! # Quick Start
//!
//! ```rust
//! use loopctl::fallback::{FallbackManager, FallbackConfig};
//!
//! // Create a manager with a trip threshold of 3 failures
//! let mgr = FallbackManager::new(3, 2);
//!
//! // Simulate failures until the circuit trips
//! mgr.record_model_failure();
//! mgr.record_model_failure();
//! assert!(mgr.record_model_failure()); // 3rd failure trips the circuit
//! assert!(mgr.is_using_fallback());
//!
//! // Manually transition to recovering, then record successes to resume primary
//! mgr.transition_to_recovering();
//! mgr.record_model_success(); // 1st success
//! mgr.record_model_success(); // 2nd → back to Primary
//! assert!(!mgr.is_using_fallback());
//! ```

use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tracing::{debug, info, warn};

/// Circuit breaker state for LLM model fallback.
///
/// Models the three classic circuit-breaker phases.
///
/// # Transitions
///
/// | From          | To            | Trigger                                                                                |
/// |---------------|---------------|----------------------------------------------------------------------------------------|
/// | `Primary`     | `Fallback`    | Consecutive failures ≥ [`FallbackConfig::trip_threshold`]                              |
/// | `Fallback`    | `Recovering`  | [`transition_to_recovering`](FallbackManager::transition_to_recovering) after cooldown |
/// | `Recovering`  | `Primary`     | Successes ≥ [`FallbackConfig::recovery_successes_needed`]                              |
/// | `Recovering`  | `Fallback`    | Any single failure during recovery                                                     |
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::FallbackState;
///
/// let state = FallbackState::Primary;
/// assert_eq!(state as u8, 0);
/// assert_eq!(FallbackState::from(1), FallbackState::Fallback);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FallbackState {
    /// Operating on the primary model — no failures have tripped the
    /// circuit breaker yet.
    Primary = 0,

    /// A fallback model is active — the primary model failed and the
    /// breaker tripped. Subsequent failures on the fallback model are
    /// tracked separately.
    Fallback = 1,

    /// Between models — the primary failed, no fallback has been
    /// selected yet, or a fallback also failed and the manager is
    /// searching for another candidate.
    Recovering = 2,
}

/// Converts a raw `u8` back into a [`FallbackState`].
///
/// Inverse of `state as u8`. Unknown values default to
/// [`FallbackState::Primary`] for safety.
///
/// # Safety
///
/// The conversion is infallible — any out-of-range `u8` maps to
/// [`FallbackState::Primary`] so that a corrupted value cannot
/// cause a panic.
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::FallbackState;
///
/// assert_eq!(FallbackState::from(0u8), FallbackState::Primary);
/// assert_eq!(FallbackState::from(1u8), FallbackState::Fallback);
/// assert_eq!(FallbackState::from(2u8), FallbackState::Recovering);
/// assert_eq!(FallbackState::from(255u8), FallbackState::Primary); // unknown → safe default
/// ```
impl From<u8> for FallbackState {
    fn from(value: u8) -> Self {
        match value {
            1 => FallbackState::Fallback,
            2 => FallbackState::Recovering,
            _ => FallbackState::Primary,
        }
    }
}

/// A single failed attempt on a fallback model.
///
/// Records *when* a failure occurred and an optional reason string
/// (e.g. `"rate_limit"`, `"timeout"`, `"500 Internal Server Error"`).
/// Entries accumulate in [`FallbackEntry::attempts`]; once the count
/// reaches [`FallbackEntry::max_fail_count`], the model is considered
/// failed and skipped by [`FallbackManager::fallback_model`].
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::AttemptRecord;
///
/// let record = AttemptRecord::new("rate_limit");
/// assert_eq!(record.reason(), Some("rate_limit"));
/// ```
#[derive(Debug, Clone)]
pub struct AttemptRecord {
    failed_at: Instant,
    reason: Option<String>,
}

impl AttemptRecord {
    /// Create a new attempt record with the given reason.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::AttemptRecord;
    /// let record = AttemptRecord::new("rate_limit");
    /// assert_eq!(record.reason(), Some("rate_limit"));
    /// ```
    #[must_use]
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            failed_at: Instant::now(),
            reason: Some(reason.into()),
        }
    }

    /// Create a new attempt record without a reason.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::AttemptRecord;
    /// let record = AttemptRecord::anonymous();
    /// assert!(record.reason().is_none());
    /// ```
    #[must_use]
    pub fn anonymous() -> Self {
        Self {
            failed_at: Instant::now(),
            reason: None,
        }
    }

    /// Set the reason for this failure record.
    ///
    /// Pass `None` for an anonymous record, or `Some("reason")` for
    /// a labelled one.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::AttemptRecord;
    /// let record = AttemptRecord::new("timeout").with_reason(Some("timeout".to_string()));
    /// assert_eq!(record.reason(), Some("timeout"));
    /// ```
    #[must_use]
    pub fn with_reason(mut self, reason: Option<String>) -> Self {
        self.reason = reason;
        self
    }

    /// When this failure was recorded.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::AttemptRecord;
    /// let record = AttemptRecord::new("timeout");
    /// // failed_at is close to now
    /// assert!(record.failed_at().elapsed().as_secs() < 1);
    /// ```
    #[must_use]
    pub fn failed_at(&self) -> Instant {
        self.failed_at
    }

    /// The optional reason for this failure.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::AttemptRecord;
    /// let record = AttemptRecord::new("rate_limit");
    /// assert_eq!(record.reason(), Some("rate_limit"));
    /// ```
    #[must_use]
    pub fn reason(&self) -> Option<&str> {
        self.reason.as_deref()
    }
}

/// A single model in the fallback chain, with attempt history.
///
/// Each entry has a model name, a list of recorded failure attempts,
/// and a `max_fail_count` threshold. When [`attempts`](Self::attempts)
/// grows to `max_fail_count` entries, the entry is considered
/// [`failed`](Self::failed) and is automatically skipped by
/// [`FallbackManager::fallback_model`].
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::FallbackEntry;
///
/// let mut entry = FallbackEntry::new("llm-70b");
/// assert_eq!(entry.name(), "llm-70b");
/// assert!(!entry.failed());
///
/// entry.record_attempt("timeout");
/// entry.record_attempt("timeout");
/// assert_eq!(entry.attempt_count(), 2);
/// assert!(entry.failed()); // max_fail_count defaults to 2
/// ```
#[derive(Debug, Clone)]
pub struct FallbackEntry {
    /// Model identifier (e.g. `"llm-70b"`). Must match the API client's routing identifier.
    name: String,
    /// Set to `false` to take a model out of rotation independently of failure tracking.
    available: bool,
    /// Recorded failure attempts for this model.
    attempts: Vec<AttemptRecord>,
    /// When `attempts.len()` reaches this threshold the model is taken out of rotation.
    max_fail_count: usize,
}

impl FallbackEntry {
    /// Create a new entry for the given model, not yet failed.
    ///
    /// Uses a default `max_fail_count` of `2`
    /// failure marks the model as failed. Use
    /// [`with_max_fail_count`](Self::with_max_fail_count) to customise.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let entry = FallbackEntry::new("llm-70b");
    /// assert_eq!(entry.name(), "llm-70b");
    /// assert!(!entry.failed());
    /// assert_eq!(entry.max_fail_count(), 2);
    /// ```
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            available: true,
            attempts: Vec::new(),
            max_fail_count: 2,
        }
    }

    /// Set a custom `max_fail_count` threshold.
    ///
    /// The model is only considered failed after this many attempts
    /// have been recorded via [`record_attempt`](Self::record_attempt).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b").with_max_fail_count(3);
    /// assert_eq!(entry.max_fail_count(), 3);
    ///
    /// entry.record_attempt("timeout");
    /// entry.record_attempt("rate_limit");
    /// assert!(!entry.failed()); // only 2 of 3
    ///
    /// entry.record_attempt("server_error");
    /// assert!(entry.failed()); // 3 of 3
    /// ```
    #[must_use]
    pub fn with_max_fail_count(mut self, max_fail_count: usize) -> Self {
        let new_max = max_fail_count.max(1);
        // If the entry was already failed, add attempts to keep it failed
        // under the new threshold.
        while self.attempts.len() < new_max && self.failed() {
            self.attempts.push(AttemptRecord::anonymous());
        }
        self.max_fail_count = new_max;
        self
    }

    /// Create a new entry already marked as failed.
    ///
    /// Useful when initializing from a known-degraded model.
    /// [`failed()`](Self::failed) returns `true` immediately.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let entry = FallbackEntry::new_failed("llm-70b");
    /// assert!(entry.failed());
    /// ```
    #[must_use]
    pub fn new_failed(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            available: true,
            attempts: vec![AttemptRecord::anonymous(), AttemptRecord::anonymous()],
            max_fail_count: 2,
        }
    }

    /// The model name.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let entry = FallbackEntry::new("llm-70b");
    /// assert_eq!(entry.name(), "llm-70b");
    /// ```
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Whether this model should be skipped.
    ///
    /// Returns `true` when the model is not [`available`](Self::available)
    /// or when [`attempt_count`](Self::attempt_count) has reached
    /// [`max_fail_count`](Self::max_fail_count).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// assert!(!entry.failed());
    /// entry.record_attempt("timeout");
    /// entry.record_attempt("timeout"); // max_fail_count defaults to 2
    /// assert!(entry.failed());
    /// ```
    #[must_use]
    pub fn failed(&self) -> bool {
        !self.available || self.attempts.len() >= self.max_fail_count
    }

    /// The configured maximum failure count before this model is skipped.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let entry = FallbackEntry::new("llm-70b").with_max_fail_count(3);
    /// assert_eq!(entry.max_fail_count(), 3);
    /// ```
    #[must_use]
    pub fn max_fail_count(&self) -> usize {
        self.max_fail_count
    }

    /// Whether this model is available for use.
    ///
    /// A model that is not available is always skipped by
    /// [`FallbackManager::fallback_model`], regardless of failure count.
    /// Set to `false` via [`set_available`](Self::set_available) to take
    /// a model out of rotation (e.g. API key revoked, model decommissioned).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// assert!(entry.available());
    /// entry.set_available(false);
    /// assert!(!entry.available());
    /// assert!(entry.failed()); // unavailable ⇒ failed
    /// ```
    #[must_use]
    pub fn available(&self) -> bool {
        self.available
    }

    /// Set whether this model is available for use.
    ///
    /// When set to `false`, [`failed()`](Self::failed) returns `true`
    /// regardless of the attempt count, and the manager skips this model.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// entry.set_available(false);
    /// assert!(entry.failed());
    /// entry.set_available(true);
    /// assert!(!entry.failed()); // no attempts recorded
    /// ```
    pub fn set_available(&mut self, available: bool) {
        self.available = available;
    }

    /// How many failure attempts have been recorded.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// assert_eq!(entry.attempt_count(), 0);
    /// entry.record_attempt("timeout");
    /// assert_eq!(entry.attempt_count(), 1);
    /// ```
    #[must_use]
    pub fn attempt_count(&self) -> usize {
        self.attempts.len()
    }

    /// Access the recorded failure attempts.
    ///
    /// Returns a slice of [`AttemptRecord`] in chronological order
    /// (oldest first).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// entry.record_attempt("timeout");
    /// entry.record_attempt("rate_limit");
    /// let attempts = entry.attempts();
    /// assert_eq!(attempts.len(), 2);
    /// assert_eq!(attempts[0].reason(), Some("timeout"));
    /// ```
    #[must_use]
    pub fn attempts(&self) -> &[AttemptRecord] {
        &self.attempts
    }

    /// Record a new failure attempt with an optional reason.
    ///
    /// If this causes [`attempt_count`](Self::attempt_count) to reach
    /// [`max_fail_count`](Self::max_fail_count), subsequent calls to
    /// [`failed()`](Self::failed) will return `true`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// entry.record_attempt("timeout");
    /// entry.record_attempt("timeout"); // exceeds max_fail_count (default = 2)
    /// assert!(entry.failed());
    /// ```
    pub fn record_attempt(&mut self, reason: impl Into<String>) {
        self.attempts.push(AttemptRecord::new(reason));
    }

    /// Record a new failure attempt without a reason.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// entry.record_attempt_anonymous();
    /// entry.record_attempt_anonymous(); // exceeds max_fail_count (default = 2)
    /// assert!(entry.failed());
    /// ```
    pub fn record_attempt_anonymous(&mut self) {
        self.attempts.push(AttemptRecord::anonymous());
    }

    /// Clear all recorded attempts, resetting [`failed()`](Self::failed)
    /// to `false`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackEntry;
    /// let mut entry = FallbackEntry::new("llm-70b");
    /// entry.record_attempt("timeout");
    /// entry.record_attempt("timeout"); // exceeds max_fail_count (default = 2)
    /// assert!(entry.failed());
    /// entry.clear_attempts();
    /// assert!(!entry.failed());
    /// ```
    pub fn clear_attempts(&mut self) {
        self.attempts.clear();
    }
}

/// Configuration for the [`FallbackManager`] circuit breaker.
///
/// Controls how aggressively the circuit trips and how cautiously it
/// recovers. These values are typically loaded from a config file or
/// environment variables and passed to [`FallbackManager::with_config`].
///
/// # Defaults
///
/// | Field                        | Default |
/// |------------------------------|---------|
/// | `trip_threshold`             | `3`     |
/// | `recovery_timeout`           | 60 s    |
/// | `recovery_successes_needed`  | `2`     |
/// | `max_fail_count`             | `2`     |
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::FallbackConfig;
/// use std::time::Duration;
///
/// let config = FallbackConfig {
///     trip_threshold: 5,
///     recovery_timeout: Duration::from_secs(120),
///     recovery_successes_needed: 3,
///     max_fail_count: 2,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct FallbackConfig {
    /// Consecutive API failures required to trip the circuit open. Defaults to `3`.
    pub trip_threshold: usize,
    /// Minimum time in fallback before probing the primary model again. Defaults to 60 s.
    pub recovery_timeout: Duration,
    /// Consecutive successes during recovering before the circuit fully closes. Defaults to `2`.
    pub recovery_successes_needed: usize,
    /// Per-model failure threshold before a fallback model is skipped. Defaults to `2`.
    pub max_fail_count: usize,
}

/// Produces a [`FallbackConfig`] with sensible production defaults.
///
/// Defaults: `trip_threshold = 3`, `recovery_timeout = 60 s`,
/// `recovery_successes_needed = 2`, `max_fail_count = 2`.
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::FallbackConfig;
///
/// let config = FallbackConfig::default();
/// assert_eq!(config.trip_threshold, 3);
/// assert_eq!(config.max_fail_count, 2);
/// ```
impl Default for FallbackConfig {
    fn default() -> Self {
        Self {
            trip_threshold: 3,
            recovery_timeout: Duration::from_secs(60),
            recovery_successes_needed: 2,
            max_fail_count: 2,
        }
    }
}

/// Manages circuit breaker state and model fallback transitions.
///
/// Tracks failures, transitions between models, and recovers back to
/// the primary model. Supports both config-driven construction via
/// [`FallbackManager::with_config`] and direct threshold control via
/// [`FallbackManager::new`].
///
/// # Thread safety
///
/// `&FallbackManager` is `Send + Sync` and can be freely shared across
/// threads (e.g. via `Arc<FallbackManager>`). No `&mut self` is needed
/// for any public method.
///
/// # Construction
///
/// Prefer [`FallbackManager::with_config`] for production use or
/// [`FallbackManager::for_model`] when you only need the framework-style
/// API. Use [`FallbackManager::new`] when you want fine-grained control
/// over thresholds.
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::{FallbackManager, FallbackConfig};
/// use std::sync::Arc;
/// use std::time::Duration;
///
/// let mgr = Arc::new(FallbackManager::new(5, 3).with_config(&FallbackConfig::default()));
///
/// // Simulate failures
/// assert!(!mgr.record_model_failure()); // 1
/// assert!(!mgr.record_model_failure()); // 2
/// assert!(mgr.record_model_failure());  // 3 → circuit trips
///
/// assert!(mgr.is_using_fallback());
///
/// // ... later, after cooldown ...
/// if mgr.should_try_resume_primary(Duration::from_secs(60)) {
///     mgr.transition_to_recovering();
///     mgr.record_model_success();
///     mgr.record_model_success(); // → back to Primary
/// }
/// ```
/// Consolidated mutex-protected fallback state.
///
/// All mutable fallback bookkeeping lives behind a single lock so that
/// related fields are always observed together, preventing partial-state
/// reads that could occur when acquiring separate locks sequentially.
#[derive(Default)]
struct FallbackInner {
    /// Original model name (before fallback).
    original_model: Option<String>,
    /// Ordered fallback models with failure status.
    fallback_models: Vec<FallbackEntry>,
    /// Cached first non-failed fallback model name.
    active_fallback: Option<String>,
    /// Time when fallback was activated.
    fallback_switched_at: Option<Instant>,
}

/// Circuit breaker for API model fallback.
///
/// `&FallbackManager` is `Send + Sync` and can be freely shared across
/// threads (e.g. via `Arc<FallbackManager>`). No `&mut self` is needed
/// for any operation.
pub struct FallbackManager {
    /// Failures before switching to fallback.
    fallback_threshold: usize,
    /// Successes needed on primary before resuming.
    primary_resume_threshold: usize,
    /// Per-model max failure count for new [`FallbackEntry`] instances.
    default_max_fail_count: usize,
    /// Consecutive API failure counter.
    consecutive_failures: AtomicUsize,
    /// Whether fallback has been activated (sticky flag).
    fallback_activated: AtomicBool,
    /// Circuit breaker state (0=Primary, 1=Fallback, 2=Recovering).
    fallback_state: AtomicU8,
    /// Consecutive successes on primary during recovery.
    primary_success_count: AtomicUsize,
    /// Consolidated mutex-protected fallback state.
    ///
    /// Holding all related fields behind a single lock prevents partial-state
    /// reads that could occur when acquiring the (formerly separate) locks one
    /// at a time.
    inner: Mutex<FallbackInner>,
    /// How long to remain in fallback before attempting primary recovery.
    recovery_timeout: Duration,
}

impl FallbackManager {
    /// Create a new fallback manager with the given thresholds.
    ///
    /// Starts in [`FallbackState::Primary`] with all counters zeroed.
    /// Use this constructor when you want to control the exact numeric
    /// thresholds. For config-file-driven construction see
    /// [`FallbackManager::with_config`].
    ///
    /// # Parameters
    ///
    /// * `fallback_threshold` — number of consecutive failures before the
    ///   circuit trips to [`FallbackState::Fallback`].
    /// * `primary_resume_threshold` — number of consecutive successes on
    ///   the primary model during [`FallbackState::Recovering`] needed to
    ///   close the circuit.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(5, 3);
    /// // Trip after 5 failures, resume after 3 consecutive successes
    /// ```
    #[must_use]
    pub fn new(fallback_threshold: usize, primary_resume_threshold: usize) -> Self {
        Self {
            fallback_threshold,
            primary_resume_threshold,
            default_max_fail_count: 2,
            consecutive_failures: AtomicUsize::new(0),
            fallback_activated: AtomicBool::new(false),
            fallback_state: AtomicU8::new(FallbackState::Primary as u8),
            primary_success_count: AtomicUsize::new(0),
            inner: Mutex::new(FallbackInner::default()),
            recovery_timeout: Duration::from_secs(60),
        }
    }

    /// Apply configuration from a [`FallbackConfig`] struct.
    ///
    /// Sets the failure threshold, recovery parameters, and per-model
    /// max fail count from the config.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackConfig};
    /// use std::time::Duration;
    ///
    /// let config = FallbackConfig {
    ///     trip_threshold: 5,
    ///     recovery_timeout: Duration::from_secs(120),
    ///     recovery_successes_needed: 3,
    ///     max_fail_count: 2,
    /// };
    /// let mgr = FallbackManager::new(5, 3).with_config(&config);
    /// ```
    #[must_use]
    pub fn with_config(mut self, config: &FallbackConfig) -> Self {
        self.fallback_threshold = config.trip_threshold;
        self.primary_resume_threshold = config.recovery_successes_needed;
        self.default_max_fail_count = config.max_fail_count;
        self.recovery_timeout = config.recovery_timeout;
        self
    }

    /// Set the recovery timeout (builder style).
    ///
    /// This is how long the manager stays in fallback before it is willing
    /// to probe the primary model again via
    /// [`should_try_resume_primary`](Self::should_try_resume_primary).
    ///
    /// Mirrors [`FallbackConfig::recovery_timeout`] for cases where a full
    /// [`with_config`](Self::with_config) is not desired.
    #[must_use]
    pub fn with_recovery_timeout(mut self, recovery_timeout: Duration) -> Self {
        self.recovery_timeout = recovery_timeout;
        self
    }

    /// Configured recovery timeout.
    ///
    /// Returns the duration the manager will remain in fallback before it
    /// is willing to probe the primary model again. Set via
    /// [`with_config`](Self::with_config) (from
    /// [`FallbackConfig::recovery_timeout`]) or
    /// [`with_recovery_timeout`](Self::with_recovery_timeout).
    ///
    /// Pass this to
    /// [`should_try_resume_primary`](Self::should_try_resume_primary) to
    /// honour the configured timeout without hard-coding a value.
    #[must_use]
    pub fn recovery_timeout(&self) -> Duration {
        self.recovery_timeout
    }

    /// Create with fallback already activated.
    ///
    /// Useful when a new manager should start in the
    /// [`FallbackState::Fallback`] state — for instance when
    /// the primary model is already known to be degraded.
    /// The `original_model` is stored for later recovery via
    /// [`should_try_resume_primary`](Self::should_try_resume_primary).
    ///
    /// # Parameters
    ///
    /// * `original_model` — the model name to remember for future recovery.
    /// * `fallback_threshold` — used for future re-tripping if recovery fails.
    ///
    /// # Initial state
    ///
    /// - [`fallback_activated`](Self::is_fallback_active) = `true`
    /// - [`state()`](Self::state) = [`FallbackState::Fallback`]
    /// - [`consecutive_failures()`](Self::consecutive_failures) = `0`
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new_with_fallback("llm-70b".into(), 3);
    /// assert!(mgr.is_using_fallback());
    /// assert_eq!(mgr.original_model(), Some("llm-70b".to_string()));
    /// ```
    #[must_use]
    pub fn new_with_fallback(original_model: String, fallback_threshold: usize) -> Self {
        let mgr = Self::new(fallback_threshold, 2);
        if let Ok(mut inner) = mgr.inner.lock() {
            inner.original_model = Some(original_model);
            inner.fallback_switched_at = Some(Instant::now());
        }
        mgr.fallback_activated.store(true, Ordering::Relaxed);
        mgr.consecutive_failures.store(0, Ordering::Relaxed);
        mgr.fallback_state
            .store(FallbackState::Fallback as u8, Ordering::Relaxed);
        mgr
    }

    /// Create a new manager with a primary model name.
    ///
    /// The model name is stored as
    /// [`original_model`](Self::original_model) for later retrieval via
    /// [`active_model`](Self::active_model). Uses default thresholds
    /// (trip after 3 failures, resume after 2 successes).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::for_model("llm-70b");
    /// assert_eq!(mgr.original_model(), Some("llm-70b".to_string()));
    /// assert!(!mgr.is_using_fallback());
    /// ```
    pub fn for_model(primary_model: impl Into<String>) -> Self {
        let mgr = Self::new(3, 2);
        if let Ok(mut inner) = mgr.inner.lock() {
            inner.original_model = Some(primary_model.into());
        }
        mgr
    }

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

    /// Get the current circuit breaker state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// assert_eq!(mgr.state(), FallbackState::Primary);
    /// ```
    pub fn state(&self) -> FallbackState {
        FallbackState::from(self.fallback_state.load(Ordering::Relaxed))
    }

    /// Check if we're currently using a fallback model.
    ///
    /// Returns `true` only when the circuit is in
    /// [`FallbackState::Fallback`]. During
    /// [`FallbackState::Recovering`] the manager is probing the primary
    /// model (half-open state), so this returns `false` — callers should
    /// route requests to the primary.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    /// let mgr = FallbackManager::new(3, 2);
    /// assert!(!mgr.is_using_fallback());
    /// ```
    pub fn is_using_fallback(&self) -> bool {
        matches!(self.state(), FallbackState::Fallback)
    }

    /// Check if fallback has ever been activated (sticky flag).
    ///
    /// Unlike [`is_using_fallback`](Self::is_using_fallback), this flag
    /// remains `true` even after the circuit recovers — it records
    /// whether the circuit *has ever* tripped during this session.
    /// Useful for diagnostics and metrics. Only cleared by
    /// [`reset`](Self::reset) or [`transition_to_primary`](Self::transition_to_primary).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::new(3, 2);
    /// assert!(!mgr.is_fallback_active());
    /// ```
    pub fn is_fallback_active(&self) -> bool {
        self.fallback_activated.load(Ordering::Relaxed)
    }

    /// Get the number of consecutive failures.
    ///
    /// The count since the last success (when in
    /// [`FallbackState::Primary`]) or since the circuit tripped.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::new(3, 2);
    /// assert_eq!(mgr.consecutive_failures(), 0);
    /// mgr.record_model_failure();
    /// assert_eq!(mgr.consecutive_failures(), 1);
    /// ```
    pub fn consecutive_failures(&self) -> usize {
        self.consecutive_failures.load(Ordering::Relaxed)
    }

    /// Get the original model name (before fallback).
    ///
    /// Returns the model name stored at construction time via
    /// [`for_model`](Self::for_model) or
    /// [`new_with_fallback`](Self::new_with_fallback), or set later
    /// with [`set_original_model`](Self::set_original_model).
    /// Returns `None` if no model name has been set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::for_model("llm-70b");
    /// assert_eq!(mgr.original_model(), Some("llm-70b".to_string()));
    /// ```
    pub fn original_model(&self) -> Option<String> {
        self.inner
            .lock()
            .ok()
            .and_then(|i| i.original_model.clone())
    }

    /// Set the original model name.
    ///
    /// Overwrites the stored primary model name. Useful when the model
    /// is resolved from configuration or changed mid-session.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::new(3, 2);
    /// assert_eq!(mgr.original_model(), None);
    /// mgr.set_original_model("llm-70b".into());
    /// assert_eq!(mgr.original_model(), Some("llm-70b".to_string()));
    /// ```
    pub fn set_original_model(&self, model: String) {
        if let Ok(mut inner) = self.inner.lock() {
            inner.original_model = Some(model);
        }
    }

    /// Get the time when fallback was activated.
    ///
    /// Returns `Some(Instant)` if the circuit has transitioned to
    /// [`FallbackState::Fallback`] at least once (and has not yet
    /// recovered). Returns `None` if the circuit has never tripped or
    /// has already recovered back to [`FallbackState::Primary`].
    /// Used by [`should_try_resume_primary`](Self::should_try_resume_primary)
    /// to enforce the cooldown period.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// use std::time::Duration;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// assert!(mgr.fallback_switched_at().is_none());
    /// ```
    pub fn fallback_switched_at(&self) -> Option<Instant> {
        self.inner.lock().ok().and_then(|i| i.fallback_switched_at)
    }

    /// Get the model that should be used for the next request.
    ///
    /// When the circuit is in [`FallbackState::Fallback`], returns the
    /// fallback model (if one has been set via
    /// [`set_fallback_model`](Self::set_fallback_model) or
    /// [`add_fallback_model`](Self::add_fallback_model)),
    /// falling back to the original model if no dedicated fallback is
    /// configured. When the circuit is in [`FallbackState::Primary`] or
    /// [`FallbackState::Recovering`] (half-open probe), always returns the
    /// original model — the manager is testing whether the primary has
    /// recovered.
    ///
    /// # Returns
    ///
    /// * `Some(model_name)` — the model the caller should use for the next
    ///   LLM request.
    /// * `None` — no model has been configured (neither primary nor fallback).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::for_model("llm-70b");
    /// assert_eq!(mgr.active_model(), Some("llm-70b".to_string()));
    /// ```
    pub fn active_model(&self) -> Option<String> {
        match self.state() {
            FallbackState::Primary | FallbackState::Recovering => self.original_model(),
            FallbackState::Fallback => self.fallback_model().or_else(|| self.original_model()),
        }
    }

    /// Set a single fallback model, clearing any existing chain.
    ///
    /// Resets the fallback chain to contain only the given model. Use this
    /// for simple single-fallback setups. For multi-model chains, use
    /// [`add_fallback_model`](Self::add_fallback_model) to build up the
    /// chain incrementally, or [`set_fallback_models`](Self::set_fallback_models)
    /// to set the entire chain at once.
    ///
    /// # Parameters
    ///
    /// * `model` — the fallback model identifier (e.g. `"llm-70b"`).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::for_model("llm-1");
    /// mgr.add_fallback_model("llm-2");
    /// mgr.add_fallback_model("llm-3");
    /// assert_eq!(mgr.fallback_models(), vec!["llm-2", "llm-3"]);
    ///
    /// mgr.set_fallback_model("llm-4"); // clears chain, sets single model
    /// assert_eq!(mgr.fallback_models(), vec!["llm-4"]);
    ///
    /// // Simulate failures until circuit trips
    /// mgr.record_model_failure();
    /// mgr.record_model_failure();
    /// mgr.record_model_failure(); // trips to Fallback
    ///
    /// assert_eq!(mgr.state(), FallbackState::Fallback);
    /// assert_eq!(mgr.active_model(), Some("llm-4".to_string()));
    /// ```
    pub fn set_fallback_model(&self, model: impl Into<String>) {
        if let Ok(mut inner) = self.inner.lock() {
            inner.fallback_models.clear();
            inner
                .fallback_models
                .push(FallbackEntry::new(model).with_max_fail_count(self.default_max_fail_count));
        }
        self.recompute_active_fallback();
    }

    /// Get the first fallback model, if any are configured.
    ///
    /// Returns the model name at index `0` of the fallback chain (the
    /// highest-priority fallback), or `None` if no fallback models have
    /// been configured.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// assert!(mgr.fallback_model().is_none());
    ///
    /// mgr.add_fallback_model("llm-70b");
    /// mgr.add_fallback_model("llm-120b");
    /// assert_eq!(mgr.fallback_model(), Some("llm-70b".to_string())); // first in chain
    /// ```
    pub fn fallback_model(&self) -> Option<String> {
        self.inner
            .lock()
            .ok()
            .and_then(|i| i.active_fallback.clone())
    }

    /// Get the full fallback model chain.
    ///
    /// Returns all configured fallback models in priority order (index `0`
    /// is the first fallback tried).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-70b");
    /// mgr.add_fallback_model("llm-120b");
    /// mgr.add_fallback_model("llm-32b");
    ///
    /// let chain = mgr.fallback_models();
    /// assert_eq!(chain, vec!["llm-70b", "llm-120b", "llm-32b"]);
    /// ```
    pub fn fallback_models(&self) -> Vec<String> {
        self.inner
            .lock()
            .ok()
            .map(|i| i.fallback_models.iter().map(|e| e.name.clone()).collect())
            .unwrap_or_default()
    }

    /// Add a fallback model to the end of the fallback chain.
    ///
    /// Appends the model as the lowest-priority fallback (last resort).
    /// Use [`insert_fallback_model`](Self::insert_fallback_model) to add
    /// at a specific position in the chain.
    ///
    /// # Parameters
    ///
    /// * `model` — the fallback model identifier.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-70b");
    /// mgr.add_fallback_model("llm-120b");
    ///
    /// let chain = mgr.fallback_models();
    /// assert_eq!(chain, vec!["llm-70b", "llm-120b"]);
    /// ```
    pub fn add_fallback_model(&self, model: impl Into<String>) {
        if let Ok(mut inner) = self.inner.lock() {
            inner
                .fallback_models
                .push(FallbackEntry::new(model).with_max_fail_count(self.default_max_fail_count));
        }
        self.recompute_active_fallback();
    }

    /// Insert a fallback model at a specific position in the chain.
    ///
    /// Models at and after the insertion index are shifted to the right.
    /// If `index` is beyond the end of the chain, the model is appended.
    ///
    /// # Parameters
    ///
    /// * `index` — the position in the chain (0 = highest priority).
    /// * `model` — the fallback model identifier.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-70b");
    /// mgr.add_fallback_model("llm-32b");
    /// mgr.insert_fallback_model(1, "llm-120b"); // insert between them
    ///
    /// let chain = mgr.fallback_models();
    /// assert_eq!(chain, vec!["llm-70b", "llm-120b", "llm-32b"]);
    /// ```
    pub fn insert_fallback_model(&self, index: usize, model: impl Into<String>) {
        if let Ok(mut inner) = self.inner.lock() {
            let entry = FallbackEntry::new(model).with_max_fail_count(self.default_max_fail_count);
            if index >= inner.fallback_models.len() {
                inner.fallback_models.push(entry);
            } else {
                inner.fallback_models.insert(index, entry);
            }
        }
        self.recompute_active_fallback();
    }

    /// Remove a fallback model by name.
    ///
    /// Removes the first occurrence of the given model name from the chain.
    /// Returns `true` if a model was removed, `false` if the name was not
    /// found in the chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-70b");
    /// mgr.add_fallback_model("llm-120b");
    ///
    /// assert!(mgr.remove_fallback_model("llm-70b"));
    /// assert!(!mgr.remove_fallback_model("nonexistent"));
    ///
    /// let chain = mgr.fallback_models();
    /// assert_eq!(chain, vec!["llm-120b"]);
    /// ```
    pub fn remove_fallback_model(&self, model: &str) -> bool {
        let removed = if let Ok(mut inner) = self.inner.lock() {
            if let Some(pos) = inner.fallback_models.iter().position(|x| x.name == model) {
                inner.fallback_models.remove(pos);
                true
            } else {
                false
            }
        } else {
            false
        };
        if removed {
            self.recompute_active_fallback();
        }
        removed
    }

    /// Replace the entire fallback model chain.
    ///
    /// Clears any existing fallback models and sets the provided list
    /// as the new chain, in the given order.
    ///
    /// # Parameters
    ///
    /// * `models` — fallback model identifiers in priority order.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.set_fallback_models(vec!["llm-70b".into(), "llm-120b".into(), "llm-32b".into()]);
    ///
    /// let chain = mgr.fallback_models();
    /// assert_eq!(chain, vec!["llm-70b", "llm-120b", "llm-32b"]);
    /// ```
    pub fn set_fallback_models(&self, models: Vec<String>) {
        let max_fc = self.default_max_fail_count;
        if let Ok(mut inner) = self.inner.lock() {
            inner.fallback_models = models
                .into_iter()
                .map(|name| FallbackEntry::new(name).with_max_fail_count(max_fc))
                .collect();
        }
        self.recompute_active_fallback();
    }

    // ==================================================
    // Fallback failure tracking
    // ==================================================

    /// Mark a fallback model as failed by name.
    ///
    /// Call this when the fallback model itself returns errors. The model
    /// is not removed from the chain — it is flagged so that
    /// [`active_model`](Self::active_model) skips it and returns the next
    /// non-failed model instead. Returns `true` if the model was found
    /// and marked, `false` if no model with that name exists in the chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-2");
    /// mgr.add_fallback_model("llm-3");
    ///
    /// assert!(mgr.mark_fallback_failed("llm-2"));
    /// assert!(!mgr.mark_fallback_failed("nonexistent"));
    ///
    /// // Mark again to exceed max_fail_count (default = 2)
    /// mgr.mark_fallback_failed("llm-2");
    ///
    /// // active_model skips failed, returns next available
    /// assert_eq!(mgr.fallback_model(), Some("llm-3".to_string()));
    /// ```
    pub fn mark_fallback_failed(&self, model: &str) -> bool {
        let found = if let Ok(mut inner) = self.inner.lock() {
            if let Some(entry) = inner.fallback_models.iter_mut().find(|e| e.name == model) {
                entry.record_attempt("marked_failed");
                true
            } else {
                false
            }
        } else {
            false
        };
        if found {
            self.recompute_active_fallback();
        }
        found
    }

    /// Clear the failed flag on a fallback model by name.
    ///
    /// Use this to retry a previously failed fallback model — for example
    /// after a cooldown period. Returns `true` if the model was found and
    /// its flag cleared, `false` if no model with that name exists.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-2");
    /// mgr.mark_fallback_failed("llm-2");
    /// mgr.mark_fallback_failed("llm-2"); // exceeds max_fail_count (default = 2)
    /// assert!(mgr.failed_fallbacks().contains(&"llm-2".to_string()));
    ///
    /// mgr.clear_fallback_failed("llm-2");
    /// assert!(mgr.failed_fallbacks().is_empty());
    /// ```
    pub fn clear_fallback_failed(&self, model: &str) -> bool {
        let found = if let Ok(mut inner) = self.inner.lock() {
            if let Some(entry) = inner.fallback_models.iter_mut().find(|e| e.name == model) {
                entry.clear_attempts();
                true
            } else {
                false
            }
        } else {
            false
        };
        if found {
            self.recompute_active_fallback();
        }
        found
    }

    /// Clear all failed flags, making every fallback model available again.
    ///
    /// Called by [`reset`](Self::reset) and when the circuit recovers
    /// back to the primary model.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-2");
    /// mgr.add_fallback_model("llm-3");
    /// mgr.mark_fallback_failed("llm-2");
    /// mgr.mark_fallback_failed("llm-2"); // exceeds max_fail_count
    /// mgr.mark_fallback_failed("llm-3");
    /// mgr.mark_fallback_failed("llm-3"); // exceeds max_fail_count
    /// assert_eq!(mgr.failed_fallbacks().len(), 2);
    ///
    /// mgr.clear_all_fallback_failed();
    /// assert!(mgr.failed_fallbacks().is_empty());
    /// ```
    pub fn clear_all_fallback_failed(&self) {
        if let Ok(mut inner) = self.inner.lock() {
            for entry in &mut inner.fallback_models {
                entry.clear_attempts();
            }
        }
        self.recompute_active_fallback();
    }

    /// Get the names of all fallback models marked as failed.
    ///
    /// Returns model names in chain order, filtered to only those with
    /// the failed flag set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-2");
    /// mgr.add_fallback_model("llm-3");
    /// mgr.mark_fallback_failed("llm-3");
    /// mgr.mark_fallback_failed("llm-3"); // exceeds max_fail_count (default = 2)
    ///
    /// let failed = mgr.failed_fallbacks();
    /// assert_eq!(failed, vec!["llm-3"]);
    /// ```
    pub fn failed_fallbacks(&self) -> Vec<String> {
        self.inner
            .lock()
            .ok()
            .map(|i| {
                i.fallback_models
                    .iter()
                    .filter(|e| e.failed())
                    .map(|e| e.name.clone())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get the names of all non-failed (available) fallback models.
    ///
    /// Returns model names in chain order, filtered to only those
    /// without the failed flag.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-2");
    /// mgr.add_fallback_model("llm-3");
    /// mgr.mark_fallback_failed("llm-3");
    /// mgr.mark_fallback_failed("llm-3"); // exceeds max_fail_count (default = 2)
    ///
    /// let available = mgr.available_fallbacks();
    /// assert_eq!(available, vec!["llm-2"]);
    /// ```
    pub fn available_fallbacks(&self) -> Vec<String> {
        self.inner
            .lock()
            .ok()
            .map(|i| {
                i.fallback_models
                    .iter()
                    .filter(|e| !e.failed())
                    .map(|e| e.name.clone())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Look up a fallback entry by name.
    ///
    /// Returns a cloned [`FallbackEntry`] for the first model in the chain
    /// whose name matches, or `None` if the name is not present. Use this
    /// to inspect a specific model's failure status without iterating the
    /// full chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-70b");
    /// mgr.add_fallback_model("llm-120b");
    ///
    /// let entry = mgr.fallback_entry("llm-70b");
    /// assert!(entry.is_some());
    /// let e = entry.unwrap();
    /// assert_eq!(e.name(), "llm-70b");
    /// assert!(!e.failed()); // not failed yet
    ///
    /// assert!(mgr.fallback_entry("nonexistent").is_none());
    /// ```
    pub fn fallback_entry(&self, name: &str) -> Option<FallbackEntry> {
        self.inner
            .lock()
            .ok()
            .and_then(|i| i.fallback_models.iter().find(|e| e.name == name).cloned())
    }

    /// Set the [`available`](FallbackEntry::available) flag on a fallback model.
    ///
    /// When set to `false`, the entry is considered [`failed`](FallbackEntry::failed)
    /// regardless of its attempt count, and [`active_model`](Self::active_model)
    /// will skip it. When set back to `true`, the entry becomes eligible again
    /// (unless its attempt count has also reached [`FallbackEntry::max_fail_count`]).
    ///
    /// Returns `true` if the model was found in the chain and updated,
    /// `false` if no model with that name exists.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.add_fallback_model("llm-2");
    /// mgr.add_fallback_model("llm-3");
    ///
    /// // Take llm-2 out of rotation (e.g. API key revoked)
    /// assert!(mgr.set_fallback_available("llm-2", false));
    ///
    /// // active_model now skips llm-2
    /// assert_eq!(mgr.fallback_model(), Some("llm-3".to_string()));
    ///
    /// // Bring it back
    /// mgr.set_fallback_available("llm-2", true);
    /// assert_eq!(mgr.fallback_model(), Some("llm-2".to_string()));
    /// ```
    pub fn set_fallback_available(&self, model: &str, available: bool) -> bool {
        let found = if let Ok(mut inner) = self.inner.lock() {
            if let Some(entry) = inner.fallback_models.iter_mut().find(|e| e.name == model) {
                entry.set_available(available);
                true
            } else {
                false
            }
        } else {
            false
        };
        if found {
            self.recompute_active_fallback();
        }
        found
    }

    // ==================================================
    // Recording
    // ==================================================

    /// Record an API failure and check if fallback should be triggered.
    ///
    /// Called by the agent loop each time an LLM API call fails (e.g.
    /// rate limit, server error, timeout). Returns `true` when the
    /// consecutive failure count reaches the configured
    /// [`fallback_threshold`](FallbackManager::new) and the circuit
    /// has not already been activated.
    ///
    /// # Returns
    ///
    /// * `true` — the failure count reached the threshold for
    ///   the first time; the caller should switch to the fallback model.
    /// * `false` — either the threshold hasn't been reached yet, or the
    ///   circuit has already been tripped.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::new(3, 2);
    /// assert!(!mgr.record_api_failure()); // 1
    /// assert!(!mgr.record_api_failure()); // 2
    /// assert!(mgr.record_api_failure());  // 3 — threshold reached, now activated
    /// assert!(!mgr.record_api_failure()); // 4 — already activated, no re-trip
    /// ```
    pub fn record_api_failure(&self) -> bool {
        let failures = self
            .consecutive_failures
            .fetch_add(1, Ordering::Relaxed)
            .saturating_add(1);
        if failures >= self.fallback_threshold && !self.fallback_activated.load(Ordering::Relaxed) {
            warn!(
                consecutive_failures = failures,
                threshold = self.fallback_threshold,
                "Fallback threshold reached"
            );
            self.fallback_activated.store(true, Ordering::Relaxed);
            true
        } else {
            false
        }
    }

    /// Alias for [`record_api_failure`](Self::record_api_failure) — framework-style name.
    ///
    /// Provided for callers that prefer the shorter `record_failure` name.
    /// Delegates directly to [`record_api_failure`](Self::record_api_failure).
    pub fn record_failure(&self) -> bool {
        self.record_api_failure()
    }

    /// Reset the consecutive failure counter.
    ///
    /// Sets [`consecutive_failures`](Self::consecutive_failures) back to
    /// `0` without changing the circuit state. Typically called by the
    /// framework when a manual reset is desired (e.g. user intervention)
    /// rather than through the normal success/failure recording flow.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.record_api_failure();
    /// mgr.record_api_failure();
    /// assert_eq!(mgr.consecutive_failures(), 2);
    /// mgr.reset_failure_counter();
    /// assert_eq!(mgr.consecutive_failures(), 0);
    /// ```
    pub fn reset_failure_counter(&self) {
        self.consecutive_failures.store(0, Ordering::Relaxed);
    }

    /// Record a success on the current model.
    ///
    /// Called by the agent loop after a successful LLM response. The
    /// effect depends on the current circuit state:
    ///
    /// - **[`Primary`](FallbackState::Primary)**: Resets the failure
    ///   counter to `0`, confirming the primary model is healthy.
    /// - **[`Fallback`](FallbackState::Fallback)**: No-op. Successes on
    ///   the fallback model don't affect recovery — the manager waits
    ///   for the cooldown period to expire first.
    /// - **[`Recovering`](FallbackState::Recovering)**: Increments the
    ///   success counter. If it reaches the configured threshold, the
    ///   circuit closes via [`transition_to_primary`](Self::transition_to_primary).
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::FallbackManager;
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.record_api_failure();
    /// assert_eq!(mgr.consecutive_failures(), 1);
    /// mgr.record_model_success(); // resets failures to 0
    /// assert_eq!(mgr.consecutive_failures(), 0);
    /// ```
    pub fn record_model_success(&self) {
        match self.state() {
            FallbackState::Primary => {
                self.consecutive_failures.store(0, Ordering::Relaxed);
            }
            FallbackState::Fallback => {
                // Success on fallback, stay in fallback
            }
            FallbackState::Recovering => {
                let successes = self
                    .primary_success_count
                    .fetch_add(1, Ordering::Relaxed)
                    .saturating_add(1);
                debug!(
                    successes,
                    threshold = self.primary_resume_threshold,
                    "Primary model success during recovery test"
                );
                if successes >= self.primary_resume_threshold {
                    self.transition_to_primary();
                }
            }
        }
    }

    /// Alias for [`record_model_success`](Self::record_model_success) — framework-style name.
    ///
    /// Provided for callers that prefer the shorter `record_success` name.
    /// Delegates directly to [`record_model_success`](Self::record_model_success).
    pub fn record_success(&self) {
        self.record_model_success();
    }

    /// Record a failure on the current model.
    ///
    /// Called by the agent loop when an LLM request fails. The effect
    /// depends on the current circuit state:
    ///
    /// - **[`Primary`](FallbackState::Primary)**: Increments the failure
    ///   counter. If the count reaches the threshold, transitions to
    ///   [`Fallback`](FallbackState::Fallback) via
    ///   [`transition_to_fallback`](Self::transition_to_fallback).
    /// - **[`Fallback`](FallbackState::Fallback)**: Logs a warning —
    ///   the fallback model itself is experiencing failures. The circuit
    ///   stays open.
    /// - **[`Recovering`](FallbackState::Recovering)**: Immediately
    ///   reopens the circuit back to [`Fallback`](FallbackState::Fallback)
    ///   — the primary is not yet healthy.
    ///
    /// # Returns
    ///
    /// `true` if this specific failure caused the circuit to trip from
    /// `Primary` to `Fallback`; `false` otherwise.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// assert!(!mgr.record_model_failure()); // 1
    /// assert!(!mgr.record_model_failure()); // 2
    /// assert!(mgr.record_model_failure());  // 3 → trips to Fallback
    /// assert_eq!(mgr.state(), FallbackState::Fallback);
    /// ```
    pub fn record_model_failure(&self) -> bool {
        match self.state() {
            FallbackState::Primary => {
                let failures = self
                    .consecutive_failures
                    .fetch_add(1, Ordering::Relaxed)
                    .saturating_add(1);
                if failures >= self.fallback_threshold {
                    self.transition_to_fallback();
                    return true;
                }
                false
            }
            FallbackState::Fallback => {
                let fb_name = self
                    .fallback_model()
                    .unwrap_or_else(|| "unknown".to_string());
                warn!(
                    "Fallback model \"{fb_name}\" also experiencing failures; consider calling mark_fallback_failed(\"{fb_name}\") to skip it"
                );
                false
            }
            FallbackState::Recovering => {
                warn!("Primary model failed during recovery test, staying on fallback");
                self.transition_to_fallback();
                false
            }
        }
    }

    // ==================================================
    // State transitions
    // ==================================================

    /// Check if we should try resuming the primary model.
    ///
    /// Returns `true` if **both** conditions hold:
    ///
    /// 1. The circuit is currently in [`FallbackState::Fallback`].
    /// 2. The elapsed time since [`fallback_switched_at`](Self::fallback_switched_at)
    ///    is at least `min_fallback_duration`.
    ///
    /// Called by the agent loop before each turn while in the fallback
    /// state. When this returns `true`, the caller should call
    /// [`transition_to_recovering`](Self::transition_to_recovering) to
    /// begin probing the primary model.
    ///
    /// # Parameters
    ///
    /// * `min_fallback_duration` — minimum time to stay in fallback
    ///   before attempting recovery (typically from
    ///   [`FallbackConfig::recovery_timeout`]).
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use loopctl::fallback::FallbackManager;
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// // Not in fallback state → false
    /// assert!(!mgr.should_try_resume_primary(Duration::from_secs(10)));
    /// ```
    pub fn should_try_resume_primary(&self, min_fallback_duration: Duration) -> bool {
        if self.state() != FallbackState::Fallback {
            return false;
        }
        if let Some(switched_at) = self.fallback_switched_at() {
            switched_at.elapsed() >= min_fallback_duration
        } else {
            false
        }
    }

    /// Transition to using fallback model (circuit open).
    ///
    /// Moves the circuit breaker to [`FallbackState::Fallback`], records
    /// the current time as [`fallback_switched_at`](Self::fallback_switched_at),
    /// and resets the recovery success counter. Called automatically by
    /// [`record_model_failure`](Self::record_model_failure) when the
    /// failure threshold is reached, or manually when the circuit needs
    /// to trip immediately.
    ///
    /// After this call, [`is_using_fallback`](Self::is_using_fallback)
    /// returns `true`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.transition_to_fallback();
    /// assert_eq!(mgr.state(), FallbackState::Fallback);
    /// ```
    pub fn transition_to_fallback(&self) {
        self.fallback_state
            .store(FallbackState::Fallback as u8, Ordering::Relaxed);
        self.fallback_activated.store(true, Ordering::Relaxed);
        if let Ok(mut inner) = self.inner.lock() {
            inner.fallback_switched_at = Some(Instant::now());
        }
        self.primary_success_count.store(0, Ordering::Relaxed);
        info!("Circuit breaker: transitioned to Fallback state");
    }

    /// Transition to testing primary model (half-open state).
    ///
    /// Moves the circuit breaker from [`FallbackState::Fallback`] to
    /// [`FallbackState::Recovering`] and resets the recovery success
    /// counter. Called by the agent loop after
    /// [`should_try_resume_primary`](Self::should_try_resume_primary)
    /// returns `true`. Subsequent calls to
    /// [`record_model_success`](Self::record_model_success) will count
    /// toward the recovery threshold.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.transition_to_fallback();
    /// mgr.transition_to_recovering();
    /// assert_eq!(mgr.state(), FallbackState::Recovering);
    /// ```
    pub fn transition_to_recovering(&self) {
        self.fallback_state
            .store(FallbackState::Recovering as u8, Ordering::Relaxed);
        self.primary_success_count.store(0, Ordering::Relaxed);
        info!("Circuit breaker: transitioned to Recovering state (testing primary)");
    }

    /// Transition back to primary model (circuit closed).
    ///
    /// Moves the circuit breaker to [`FallbackState::Primary`], clears
    /// the fallback timestamp, and resets all counters (failures,
    /// successes, and the `fallback_activated` flag). Called
    /// automatically when the recovery success threshold is reached
    /// inside [`record_model_success`](Self::record_model_success), or
    /// manually to force an immediate return to primary.
    ///
    /// After this call, [`is_using_fallback`](Self::is_using_fallback)
    /// returns `false`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// mgr.transition_to_fallback();
    /// mgr.transition_to_primary();
    /// assert_eq!(mgr.state(), FallbackState::Primary);
    /// assert!(!mgr.is_using_fallback());
    /// ```
    pub fn transition_to_primary(&self) {
        self.fallback_state
            .store(FallbackState::Primary as u8, Ordering::Relaxed);
        if let Ok(mut inner) = self.inner.lock() {
            inner.fallback_switched_at = None;
        }
        self.primary_success_count.store(0, Ordering::Relaxed);
        self.consecutive_failures.store(0, Ordering::Relaxed);
        self.fallback_activated.store(false, Ordering::Relaxed);
        self.clear_all_fallback_failed();
        info!("Circuit breaker: transitioned to Primary state (primary model recovered)");
    }

    /// Reset the circuit breaker to [`FallbackState::Primary`] state.
    ///
    /// Performs a full reset: sets the state to `Primary`, zeros all
    /// counters, clears the `fallback_activated` flag, and clears the
    /// fallback timestamp. Hard reset — erases all
    /// failure history and is equivalent to creating a new manager.
    ///
    /// Use this when you want to force the circuit back to its initial
    /// state (e.g. after a configuration change or user intervention)
    /// rather than going through the normal recovery flow.
    ///
    /// # Example
    ///
    /// ```rust
    /// use loopctl::fallback::{FallbackManager, FallbackState};
    ///
    /// let mgr = FallbackManager::new(3, 2);
    /// for _ in 0..3 { mgr.record_model_failure(); }
    /// assert_eq!(mgr.state(), FallbackState::Fallback);
    ///
    /// mgr.reset();
    /// assert_eq!(mgr.state(), FallbackState::Primary);
    /// assert!(!mgr.is_fallback_active());
    /// assert_eq!(mgr.consecutive_failures(), 0);
    /// ```
    pub fn reset(&self) {
        self.fallback_state
            .store(FallbackState::Primary as u8, Ordering::Relaxed);
        self.consecutive_failures.store(0, Ordering::Relaxed);
        self.primary_success_count.store(0, Ordering::Relaxed);
        self.fallback_activated.store(false, Ordering::Relaxed);
        if let Ok(mut inner) = self.inner.lock() {
            inner.fallback_switched_at = None;
        }
        self.clear_all_fallback_failed();
    }

    // ==================================================
    // Private helpers
    // ==================================================

    /// Recompute the cached [`active_fallback`](Self::active_fallback) from
    /// the current fallback chain.
    ///
    /// [`fallback_models`]: Self::fallback_models
    /// [`active_fallback`]: Self::active_fallback
    fn recompute_active_fallback(&self) {
        let active = self.inner.lock().ok().and_then(|i| {
            i.fallback_models
                .iter()
                .find(|e| !e.failed())
                .map(|e| e.name.clone())
        });
        if let Ok(mut inner) = self.inner.lock() {
            inner.active_fallback = active;
        }
    }
}

/// Produces a [`FallbackManager`] with production defaults.
///
/// Equivalent to `FallbackManager::new(3, 2)` — trips after 3
/// consecutive failures and resumes after 2 consecutive successes.
/// No model name is stored; use [`FallbackManager::for_model`] or
/// [`FallbackManager::set_original_model`] to configure one.
///
/// # Example
///
/// ```rust
/// use loopctl::fallback::FallbackManager;
///
/// let mgr = FallbackManager::default();
/// assert_eq!(mgr.consecutive_failures(), 0);
/// assert!(!mgr.is_using_fallback());
/// ```
impl Default for FallbackManager {
    fn default() -> Self {
        Self::new(3, 2)
    }
}

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

    #[test]
    fn test_initial_state() {
        let mgr = FallbackManager::new(3, 2);
        assert_eq!(mgr.state(), FallbackState::Primary);
        assert!(!mgr.is_using_fallback());
        assert!(!mgr.is_fallback_active());
        assert_eq!(mgr.consecutive_failures(), 0);
    }

    #[test]
    fn test_failure_threshold() {
        let mgr = FallbackManager::new(3, 2);
        assert!(!mgr.record_api_failure()); // 1
        assert!(!mgr.record_api_failure()); // 2
        assert!(mgr.record_api_failure()); // 3 — threshold reached
    }

    #[test]
    fn test_model_failure_triggers_fallback() {
        let mgr = FallbackManager::new(3, 2);
        assert!(!mgr.record_model_failure()); // 1
        assert!(!mgr.record_model_failure()); // 2
        assert!(mgr.record_model_failure()); // 3 — triggers fallback
        assert_eq!(mgr.state(), FallbackState::Fallback);
    }

    #[test]
    fn test_recovery() {
        let mgr = FallbackManager::new(3, 2);
        // Trigger fallback
        for _ in 0..3 {
            mgr.record_model_failure();
        }
        assert_eq!(mgr.state(), FallbackState::Fallback);

        // Transition to recovering
        mgr.transition_to_recovering();
        assert_eq!(mgr.state(), FallbackState::Recovering);

        // Recover after enough successes
        mgr.record_model_success(); // 1
        mgr.record_model_success(); // 2 — threshold reached
        assert_eq!(mgr.state(), FallbackState::Primary);
    }

    #[test]
    fn test_recovery_failure_goes_back_to_fallback() {
        let mgr = FallbackManager::new(3, 2);
        for _ in 0..3 {
            mgr.record_model_failure();
        }
        mgr.transition_to_recovering();
        mgr.record_model_failure(); // failure during recovery
        assert_eq!(mgr.state(), FallbackState::Fallback);
    }

    #[test]
    fn test_should_try_resume_primary() {
        let mgr = FallbackManager::new(3, 2);
        assert!(!mgr.should_try_resume_primary(Duration::from_secs(10)));

        // Trigger fallback
        for _ in 0..3 {
            mgr.record_model_failure();
        }
        // Not enough time
        assert!(!mgr.should_try_resume_primary(Duration::from_secs(3600)));
        // Enough time (0s timeout)
        assert!(mgr.should_try_resume_primary(Duration::from_secs(0)));
    }

    #[test]
    fn test_new_with_fallback() {
        let mgr = FallbackManager::new_with_fallback("llm-70b".into(), 3);
        assert!(mgr.is_fallback_active());
        assert!(mgr.is_using_fallback());
        assert_eq!(mgr.original_model(), Some("llm-70b".to_string()));
    }

    #[test]
    fn test_reset() {
        let mgr = FallbackManager::new(3, 2);
        for _ in 0..3 {
            mgr.record_model_failure();
        }
        assert_eq!(mgr.state(), FallbackState::Fallback);

        mgr.reset();
        assert_eq!(mgr.state(), FallbackState::Primary);
        assert!(!mgr.is_fallback_active());
        assert_eq!(mgr.consecutive_failures(), 0);
    }

    #[test]
    fn test_api_failure_does_not_retrip() {
        let mgr = FallbackManager::new(3, 2);
        // Trip the circuit
        for _ in 0..3 {
            mgr.record_api_failure();
        }
        // Activate fallback
        mgr.transition_to_fallback();
        mgr.fallback_activated.store(true, Ordering::Relaxed);

        // Further failures should not return true (already activated)
        assert!(!mgr.record_api_failure());
    }

    #[test]
    fn test_record_success_resets_on_primary() {
        let mgr = FallbackManager::new(3, 2);
        mgr.record_api_failure();
        mgr.record_api_failure();
        assert_eq!(mgr.consecutive_failures(), 2);

        mgr.record_model_success();
        assert_eq!(mgr.consecutive_failures(), 0);
    }

    #[test]
    fn test_for_model() {
        let mgr = FallbackManager::for_model("llm-70b");
        assert_eq!(mgr.original_model(), Some("llm-70b".to_string()));
        assert_eq!(mgr.state(), FallbackState::Primary);
    }

    #[test]
    fn test_concurrent_access() {
        use std::sync::Arc;
        use std::thread;

        let mgr = Arc::new(FallbackManager::new(3, 2));
        let mut handles = Vec::new();

        for _ in 0..10 {
            let mgr = Arc::clone(&mgr);
            handles.push(thread::spawn(move || {
                mgr.record_api_failure();
                mgr.record_model_success();
                mgr.state();
                mgr.consecutive_failures();
            }));
        }

        for h in handles {
            h.join().unwrap();
        }
    }

    #[test]
    fn test_consolidated_mutex_fields_are_consistent() {
        let mgr = FallbackManager::for_model("primary-model");
        mgr.add_fallback_model("fallback-model");

        // Before transition: using primary model, no switch time.
        assert_eq!(mgr.active_model(), Some("primary-model".to_string()));
        assert!(mgr.fallback_switched_at().is_none());

        // Transition to fallback — updates multiple fields.
        mgr.transition_to_fallback();

        // After transition: both fields should be set together.
        // This verifies the consolidated Mutex prevents partial reads.
        assert_eq!(mgr.active_model(), Some("fallback-model".to_string()));
        assert!(
            mgr.fallback_switched_at().is_some(),
            "switch time should be set after transition"
        );
    }

    #[test]
    fn test_consolidated_mutex_clears_fields_together() {
        let mgr = FallbackManager::for_model("primary-model");
        mgr.add_fallback_model("fallback-model");
        mgr.transition_to_fallback();

        // Both fields are set.
        assert_eq!(mgr.active_model(), Some("fallback-model".to_string()));
        assert!(mgr.fallback_switched_at().is_some());

        // Transition back to primary.
        mgr.transition_to_primary();

        // Both fields should be cleared together.
        assert!(
            mgr.fallback_switched_at().is_none(),
            "switch time should be cleared after transition to primary"
        );
    }

    #[test]
    fn test_consolidated_mutex_reset_clears_all() {
        let mgr = FallbackManager::for_model("primary-model");
        mgr.add_fallback_model("fallback-model");
        mgr.transition_to_fallback();
        mgr.record_failure();

        // State is dirty.
        assert!(mgr.consecutive_failures() > 0);
        assert!(mgr.fallback_switched_at().is_some());

        // Full reset.
        mgr.reset();

        // Everything cleared.
        assert_eq!(mgr.consecutive_failures(), 0);
        assert!(mgr.fallback_switched_at().is_none());
    }

    #[test]
    fn with_max_fail_count_no_padding_when_not_failed() {
        let entry = FallbackEntry::new("model-a").with_max_fail_count(5);
        assert!(!entry.failed());
        assert_eq!(entry.attempt_count(), 0);
        assert_eq!(entry.max_fail_count, 5);
    }

    #[test]
    fn with_max_fail_count_pads_already_failed_entry() {
        let mut entry = FallbackEntry::new("model-b");
        entry.record_attempt("timeout");
        entry.record_attempt("timeout");
        assert!(entry.failed());
        assert_eq!(entry.attempt_count(), 2);

        let entry = entry.with_max_fail_count(5);
        assert_eq!(entry.max_fail_count, 5);
        assert_eq!(entry.attempt_count(), 5);
        assert!(entry.failed());
    }

    #[test]
    fn with_max_fail_count_pads_exactly_to_new_threshold() {
        let mut entry = FallbackEntry::new("model-c");
        entry.record_attempt("err");
        entry.record_attempt("err");
        assert!(entry.failed());

        let entry = entry.with_max_fail_count(3);
        assert_eq!(entry.attempt_count(), 3);
        assert!(entry.failed());
    }

    #[test]
    fn with_max_fail_count_no_padding_when_lowering() {
        let mut entry = FallbackEntry::new("model-d");
        entry.record_attempt("err");
        entry.record_attempt("err");
        assert!(entry.failed());

        let entry = entry.with_max_fail_count(1);
        assert_eq!(entry.max_fail_count, 1);
        assert_eq!(entry.attempt_count(), 2);
        assert!(entry.failed());
    }

    #[test]
    fn with_max_fail_count_clamps_to_minimum_one() {
        let entry = FallbackEntry::new("model-e").with_max_fail_count(0);
        assert_eq!(entry.max_fail_count, 1);
    }
}