oxi-cli 0.3.0-alpha

Terminal-based AI coding assistant — multi-provider, streaming-first, extensible
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
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
//! Autonomous development loop skill for oxi
//!
//! A fully autonomous, recursive development cycle that runs
//! **Design → Plan → Implement → Verify → Fix** in a loop until zero
//! *genuine* issues remain. The operator issues one command and gets a
//! finished, verified, committed result.
//!
//! This module provides:
//! - [`AutonomousLoop`] — state machine that tracks loop iterations, phases,
//!   batches, issues, and verification results.
//! - [`LoopTask`] / [`TaskBatch`] — structured task and batch definitions
//!   with dependency tracking.
//! - [`Issue`] / [`IssueSeverity`] / [`IssueVerdict`] — issue tracking with
//!   severity classification and false-positive filtering.
//! - [`LoopPhase`] — phase enum for the six phases of the loop.
//! - [`AutonomousLoopSkill`] — skill content generator that produces the
//!   system-prompt instructions for the LLM-driven autonomous workflow.
//! - [`LoopStatus`] — serializable status snapshot for diagnostics.

use anyhow::{bail, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::PathBuf;

// ── Constants ──────────────────────────────────────────────────────────

/// Maximum number of full loop iterations before forced stop.
pub const MAX_ITERATIONS: u8 = 8;

// ── Phase ──────────────────────────────────────────────────────────────

/// The phases of the autonomous development loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoopPhase {
    /// Understand requirements and produce a clear design.
    Design,
    /// Decompose into ordered, verifiable implementation steps.
    Plan,
    /// Execute the plan by batch, parallelizing independent tasks.
    Implement,
    /// Multi-axis verification that catches real problems.
    Verify,
    /// Confirm that every issue found is a REAL issue.
    ReValidate,
    /// Fix only the confirmed, genuine issues.
    Fix,
    /// Session concluded — all criteria met.
    Done,
}

impl Default for LoopPhase {
    fn default() -> Self {
        LoopPhase::Design
    }
}

impl fmt::Display for LoopPhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LoopPhase::Design => write!(f, "DESIGN"),
            LoopPhase::Plan => write!(f, "PLAN"),
            LoopPhase::Implement => write!(f, "IMPLEMENT"),
            LoopPhase::Verify => write!(f, "VERIFY"),
            LoopPhase::ReValidate => write!(f, "RE-VALIDATE"),
            LoopPhase::Fix => write!(f, "FIX"),
            LoopPhase::Done => write!(f, "DONE"),
        }
    }
}

impl LoopPhase {
    /// Return all phases in loop order.
    pub fn all() -> &'static [LoopPhase] {
        &[
            LoopPhase::Design,
            LoopPhase::Plan,
            LoopPhase::Implement,
            LoopPhase::Verify,
            LoopPhase::ReValidate,
            LoopPhase::Fix,
            LoopPhase::Done,
        ]
    }

    /// Advance to the next phase in the standard sequence.
    ///
    /// The loop flow is:
    /// ```text
    /// Design → Plan → Implement → Verify
    ///   ↑                              │
    ///   └── Fix ← ReValidate ←────────┘
    ///                                    ↘ Done (no issues)
    /// ```
    pub fn next(&self) -> Option<LoopPhase> {
        match self {
            LoopPhase::Design => Some(LoopPhase::Plan),
            LoopPhase::Plan => Some(LoopPhase::Implement),
            LoopPhase::Implement => Some(LoopPhase::Verify),
            LoopPhase::Verify => Some(LoopPhase::ReValidate),
            LoopPhase::ReValidate => Some(LoopPhase::Fix),
            LoopPhase::Fix => Some(LoopPhase::Verify), // back to verify after fix
            LoopPhase::Done => None,
        }
    }

    /// Returns `true` if this phase should proceed to `Done` when no issues
    /// are found (as opposed to continuing the loop).
    pub fn can_exit_on_clean(&self) -> bool {
        matches!(self, LoopPhase::Verify | LoopPhase::ReValidate)
    }
}

// ── Task and Batch ─────────────────────────────────────────────────────

/// Status of a task or batch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
    /// Not yet started.
    Pending,
    /// Currently running.
    Running,
    /// Successfully completed.
    Done,
    /// Failed with an error.
    Failed,
}

impl fmt::Display for TaskStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskStatus::Pending => write!(f, "pending"),
            TaskStatus::Running => write!(f, "running"),
            TaskStatus::Done => write!(f, "done"),
            TaskStatus::Failed => write!(f, "failed"),
        }
    }
}

/// A single task in the implementation plan.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopTask {
    /// Unique task identifier (e.g., "T1", "T2").
    pub id: String,
    /// Short description of what this task accomplishes.
    pub description: String,
    /// File paths this task creates or modifies.
    pub touches_files: Vec<PathBuf>,
    /// IDs of tasks this task depends on.
    pub depends_on: Vec<String>,
    /// How to verify this task works.
    pub verification: String,
    /// Current status.
    pub status: TaskStatus,
    /// Commit hash after completion, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_hash: Option<String>,
}

impl LoopTask {
    /// Create a new task with the given ID and description.
    pub fn new(id: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            description: description.into(),
            touches_files: Vec::new(),
            depends_on: Vec::new(),
            verification: String::new(),
            status: TaskStatus::Pending,
            commit_hash: None,
        }
    }

    /// Add a file this task touches.
    pub fn touches(mut self, path: impl Into<PathBuf>) -> Self {
        self.touches_files.push(path.into());
        self
    }

    /// Declare a dependency on another task.
    pub fn depends_on(mut self, task_id: impl Into<String>) -> Self {
        self.depends_on.push(task_id.into());
        self
    }

    /// Set verification method.
    pub fn verify_with(mut self, method: impl Into<String>) -> Self {
        self.verification = method.into();
        self
    }

    /// Mark the task as running.
    pub fn start(&mut self) {
        self.status = TaskStatus::Running;
    }

    /// Mark the task as completed with an optional commit hash.
    pub fn complete(&mut self, commit_hash: Option<String>) {
        self.status = TaskStatus::Done;
        self.commit_hash = commit_hash;
    }

    /// Mark the task as failed.
    pub fn fail(&mut self) {
        self.status = TaskStatus::Failed;
    }
}

/// A batch of tasks that can be executed in parallel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskBatch {
    /// Batch index (0-based).
    pub index: usize,
    /// Tasks in this batch.
    pub tasks: Vec<LoopTask>,
    /// Whether tasks in this batch have file conflicts (must run sequentially).
    pub has_conflicts: bool,
    /// Current status of the batch.
    pub status: TaskStatus,
}

impl TaskBatch {
    /// Create a new batch at the given index.
    pub fn new(index: usize) -> Self {
        Self {
            index,
            tasks: Vec::new(),
            has_conflicts: false,
            status: TaskStatus::Pending,
        }
    }

    /// Add a task to this batch.
    pub fn add_task(&mut self, task: LoopTask) {
        self.tasks.push(task);
    }

    /// Mark all tasks as running.
    pub fn start(&mut self) {
        self.status = TaskStatus::Running;
        for task in &mut self.tasks {
            task.start();
        }
    }

    /// Mark the batch as completed.
    pub fn complete(&mut self) {
        self.status = TaskStatus::Done;
    }

    /// Check if all tasks in this batch are done.
    pub fn all_done(&self) -> bool {
        self.tasks.iter().all(|t| t.status == TaskStatus::Done)
    }

    /// Check if any task in this batch failed.
    pub fn any_failed(&self) -> bool {
        self.tasks.iter().any(|t| t.status == TaskStatus::Failed)
    }
}

// ── Issue tracking ─────────────────────────────────────────────────────

/// Severity of an issue found during verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IssueSeverity {
    /// Formatting, naming preference — optional.
    Nit = 0,
    /// Style inconsistency, missing edge case — should fix.
    Minor = 1,
    /// Incorrect behavior, failing tests, broken feature — must fix.
    Important = 2,
    /// Build broken, data loss, security vulnerability — must fix now.
    Critical = 3,
}

impl fmt::Display for IssueSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IssueSeverity::Nit => write!(f, "Nit"),
            IssueSeverity::Minor => write!(f, "Minor"),
            IssueSeverity::Important => write!(f, "Important"),
            IssueSeverity::Critical => write!(f, "Critical"),
        }
    }
}

/// Verdict after re-validating an issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IssueVerdict {
    /// Real issue — proceed to fix.
    Confirmed,
    /// Not actually a problem — discard.
    FalsePositive,
    /// Real but out of scope — log for future.
    Deferred,
    /// Cannot determine — needs user input.
    NeedsContext,
}

impl fmt::Display for IssueVerdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IssueVerdict::Confirmed => write!(f, "CONFIRMED"),
            IssueVerdict::FalsePositive => write!(f, "FALSE_POSITIVE"),
            IssueVerdict::Deferred => write!(f, "DEFERRED"),
            IssueVerdict::NeedsContext => write!(f, "NEEDS_CONTEXT"),
        }
    }
}

/// An issue found during verification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Issue {
    /// Issue number (1-based, for display).
    pub number: usize,
    /// One-line description.
    pub description: String,
    /// Severity.
    pub severity: IssueSeverity,
    /// Location (file:line or component name).
    pub location: String,
    /// Evidence (error message, test output, or concrete observation).
    pub evidence: String,
    /// Whether the issue is reproducible.
    pub reproducible: bool,
    /// Suggested fix approach.
    pub fix_approach: String,
    /// Verdict after re-validation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verdict: Option<IssueVerdict>,
    /// Reason for the verdict (especially for false positives).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verdict_reason: Option<String>,
    /// Whether this issue has been fixed.
    pub fixed: bool,
    /// Commit hash of the fix, if applied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fix_commit: Option<String>,
}

impl Issue {
    /// Create a new issue.
    pub fn new(
        number: usize,
        description: impl Into<String>,
        severity: IssueSeverity,
        location: impl Into<String>,
    ) -> Self {
        Self {
            number,
            description: description.into(),
            severity,
            location: location.into(),
            evidence: String::new(),
            reproducible: false,
            fix_approach: String::new(),
            verdict: None,
            verdict_reason: None,
            fixed: false,
            fix_commit: None,
        }
    }

    /// Set evidence for this issue.
    pub fn with_evidence(mut self, evidence: impl Into<String>) -> Self {
        self.evidence = evidence.into();
        self
    }

    /// Set whether the issue is reproducible.
    pub fn reproducible(mut self, yes: bool) -> Self {
        self.reproducible = yes;
        self
    }

    /// Set the fix approach.
    pub fn fix_approach(mut self, approach: impl Into<String>) -> Self {
        self.fix_approach = approach.into();
        self
    }

    /// Record a verdict after re-validation.
    pub fn set_verdict(&mut self, verdict: IssueVerdict, reason: impl Into<String>) {
        self.verdict = Some(verdict);
        self.verdict_reason = Some(reason.into());
    }

    /// Mark the issue as fixed.
    pub fn mark_fixed(&mut self, commit_hash: Option<String>) {
        self.fixed = true;
        self.fix_commit = commit_hash;
    }

    /// Whether this issue must be fixed (confirmed and not yet fixed).
    pub fn needs_fix(&self) -> bool {
        self.verdict == Some(IssueVerdict::Confirmed) && !self.fixed
    }

    /// Whether this issue is actionable (confirmed or needs context, not fixed).
    pub fn is_actionable(&self) -> bool {
        matches!(
            self.verdict,
            Some(IssueVerdict::Confirmed) | Some(IssueVerdict::NeedsContext)
        ) && !self.fixed
    }
}

// ── Verification result ───────────────────────────────────────────────

/// Result of a verification pass.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationResult {
    /// Whether the build succeeded.
    pub build_passed: bool,
    /// Whether all tests passed.
    pub tests_passed: bool,
    /// Whether type checking passed.
    pub type_check_passed: bool,
    /// Whether linting passed.
    pub lint_passed: bool,
    /// Issues found during this verification pass.
    pub issues: Vec<Issue>,
    /// Timestamp of this verification.
    pub timestamp: String,
}

impl VerificationResult {
    /// Create a new verification result.
    pub fn new() -> Self {
        Self {
            build_passed: false,
            tests_passed: false,
            type_check_passed: false,
            lint_passed: false,
            issues: Vec::new(),
            timestamp: Utc::now().to_rfc3339(),
        }
    }

    /// Whether all checks passed with no issues.
    pub fn is_clean(&self) -> bool {
        self.build_passed
            && self.tests_passed
            && self.type_check_passed
            && self.lint_passed
            && self.issues.is_empty()
    }

    /// Whether the critical gates passed (build + tests).
    pub fn critical_passed(&self) -> bool {
        self.build_passed && self.tests_passed
    }

    /// Count issues by severity.
    pub fn issue_count_by_severity(&self, severity: IssueSeverity) -> usize {
        self.issues
            .iter()
            .filter(|i| i.severity == severity)
            .count()
    }

    /// Count confirmed issues that still need fixing.
    pub fn confirmed_unfixed(&self) -> usize {
        self.issues.iter().filter(|i| i.needs_fix()).count()
    }
}

impl Default for VerificationResult {
    fn default() -> Self {
        Self::new()
    }
}

// ── Loop status snapshot ───────────────────────────────────────────────

/// A serializable snapshot of the autonomous loop state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopStatus {
    /// The task being executed.
    pub task: String,
    /// Current iteration number (1-based).
    pub iteration: u8,
    /// Maximum iterations allowed.
    pub max_iterations: u8,
    /// Current phase.
    pub phase: LoopPhase,
    /// Execution batches.
    pub batches: Vec<TaskBatch>,
    /// Issues found across all iterations.
    pub issues: Vec<Issue>,
    /// Latest verification result.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_verification: Option<VerificationResult>,
    /// Most recent commit hash.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_commit: Option<String>,
    /// Whether git working tree is clean.
    pub git_clean: bool,
    /// Any blocking condition.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocker: Option<String>,
    /// Timestamp of this status snapshot.
    pub timestamp: String,
}

impl LoopStatus {
    /// Render the status as a formatted string for display.
    pub fn render(&self) -> String {
        let mut s = String::with_capacity(2048);

        s.push_str("AUTONOMOUS LOOP STATUS\n");
        s.push_str("═══════════════════════\n");
        s.push_str(&format!("Task: {}\n", self.task));
        s.push_str(&format!(
            "Iteration: {} / {}\n",
            self.iteration, self.max_iterations
        ));
        s.push_str(&format!("Phase: {}\n", self.phase));

        // Batch summary
        let done_count = self
            .batches
            .iter()
            .filter(|b| b.status == TaskStatus::Done)
            .count();
        let total_count = self.batches.len();
        s.push_str(&format!("Batches: {} / {} done\n", done_count, total_count));
        for batch in &self.batches {
            let task_ids: Vec<&str> = batch.tasks.iter().map(|t| t.id.as_str()).collect();
            let mode = if batch.has_conflicts {
                "sequential"
            } else {
                "parallel"
            };
            s.push_str(&format!(
                "  Batch {}: [{}] ({}) — {}\n",
                batch.index,
                task_ids.join(", "),
                mode,
                batch.status
            ));
        }

        // Issue summary
        let total = self.issues.len();
        let confirmed = self
            .issues
            .iter()
            .filter(|i| i.verdict == Some(IssueVerdict::Confirmed))
            .count();
        let fixed = self.issues.iter().filter(|i| i.fixed).count();
        s.push_str(&format!(
            "Issues: {} found → {} confirmed → {} fixed\n",
            total, confirmed, fixed
        ));

        // Progress bar
        let pct = if total_count > 0 {
            (done_count * 10) / total_count
        } else {
            0
        };
        let filled: String = "".repeat(pct);
        let empty: String = "".repeat(10 - pct);
        s.push_str(&format!("Progress: {}{} \n", filled, empty));

        // Commit and git status
        if let Some(ref hash) = self.last_commit {
            s.push_str(&format!("Last commit: {}\n", &hash[..7.min(hash.len())]));
        }
        s.push_str(&format!(
            "Git status: {}\n",
            if self.git_clean { "clean" } else { "dirty" }
        ));

        // Blocker
        if let Some(ref blocker) = self.blocker {
            s.push_str(&format!("Blocks: {}\n", blocker));
        }

        s
    }
}

// ── Autonomous Loop state machine ──────────────────────────────────────

/// The autonomous development loop state machine.
///
/// Tracks the full lifecycle of an autonomous development task across
/// multiple iterations of the Design → Plan → Implement → Verify →
/// ReValidate → Fix loop.
///
/// # Usage
///
/// ```rust,ignore
/// let mut al = AutonomousLoop::new("Implement user authentication");
/// al.start()?;
///
/// // Design phase
/// al.advance()?; // → Plan
///
/// // Plan phase — add tasks and compute batches
/// al.add_task(LoopTask::new("T1", "Create auth module").touches("src/auth.rs"));
/// al.add_task(LoopTask::new("T2", "Add login route").depends_on("T1"));
/// al.compute_batches()?;
/// al.advance()?; // → Implement
///
/// // ... execute batches ...
/// al.advance()?; // → Verify
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousLoop {
    /// Unique loop instance ID.
    pub id: String,
    /// The task description.
    pub task: String,
    /// Current iteration (1-based).
    pub iteration: u8,
    /// Maximum iterations allowed.
    pub max_iterations: u8,
    /// Current phase.
    pub phase: LoopPhase,
    /// Whether the loop has been started.
    pub started: bool,
    /// Whether the loop has been forcefully stopped.
    pub emergency_stopped: bool,
    /// All tasks in the plan.
    pub tasks: Vec<LoopTask>,
    /// Computed execution batches.
    pub batches: Vec<TaskBatch>,
    /// Issues found across all iterations.
    pub issues: Vec<Issue>,
    /// Latest verification result.
    pub last_verification: Option<VerificationResult>,
    /// Most recent commit hash.
    pub last_commit: Option<String>,
    /// Whether the git working tree is clean.
    pub git_clean: bool,
    /// Any blocking condition preventing progress.
    pub blocker: Option<String>,
    /// Creation timestamp.
    pub created_at: String,
    /// Last update timestamp.
    pub updated_at: String,
}

impl AutonomousLoop {
    /// Create a new autonomous loop for the given task.
    pub fn new(task: impl Into<String>) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            task: task.into(),
            iteration: 0,
            max_iterations: MAX_ITERATIONS,
            phase: LoopPhase::Design,
            started: false,
            emergency_stopped: false,
            tasks: Vec::new(),
            batches: Vec::new(),
            issues: Vec::new(),
            last_verification: None,
            last_commit: None,
            git_clean: true,
            blocker: None,
            created_at: Utc::now().to_rfc3339(),
            updated_at: Utc::now().to_rfc3339(),
        }
    }

    /// Set the maximum number of iterations.
    pub fn with_max_iterations(mut self, max: u8) -> Self {
        self.max_iterations = max.min(MAX_ITERATIONS).max(1);
        self
    }

    /// Start the loop (transitions to iteration 1, Design phase).
    pub fn start(&mut self) -> Result<()> {
        if self.started {
            bail!("Loop already started");
        }
        if self.emergency_stopped {
            bail!("Loop was emergency-stopped and cannot be restarted");
        }
        self.started = true;
        self.iteration = 1;
        self.phase = LoopPhase::Design;
        self.touch();
        Ok(())
    }

    /// Emergency stop — halts the loop immediately.
    pub fn emergency_stop(&mut self, reason: impl Into<String>) {
        self.emergency_stopped = true;
        self.blocker = Some(reason.into());
        self.touch();
    }

    /// Advance to the next phase.
    ///
    /// Follows the standard loop flow:
    /// - After ReValidate with no confirmed issues → Done
    /// - After ReValidate with confirmed issues → Fix → Verify (new iteration)
    /// - After Verify with no issues → Done
    /// - After Verify with issues → ReValidate
    pub fn advance(&mut self) -> Result<LoopPhase> {
        if !self.started {
            bail!("Loop has not been started");
        }
        if self.emergency_stopped {
            bail!(
                "Loop was emergency-stopped: {}",
                self.blocker.as_deref().unwrap_or("unknown")
            );
        }

        let next = match self.phase {
            LoopPhase::Design => Some(LoopPhase::Plan),
            LoopPhase::Plan => Some(LoopPhase::Implement),
            LoopPhase::Implement => Some(LoopPhase::Verify),

            LoopPhase::Verify => {
                // If clean, we're done
                if self.is_clean() {
                    Some(LoopPhase::Done)
                } else {
                    Some(LoopPhase::ReValidate)
                }
            }

            LoopPhase::ReValidate => {
                let has_confirmed = self.issues.iter().any(|i| i.needs_fix());
                if has_confirmed {
                    Some(LoopPhase::Fix)
                } else {
                    // All issues are false positives or deferred — done!
                    Some(LoopPhase::Done)
                }
            }

            LoopPhase::Fix => {
                // After fixing, increment iteration and go back to verify
                self.iteration += 1;
                if self.iteration > self.max_iterations {
                    self.emergency_stop(format!(
                        "Maximum iterations ({}) reached",
                        self.max_iterations
                    ));
                    bail!(
                        "Maximum iterations ({}) reached. Diagnostic:\n{}",
                        self.max_iterations,
                        self.diagnostic()
                    );
                }
                Some(LoopPhase::Verify)
            }

            LoopPhase::Done => {
                bail!("Loop is already complete");
            }
        };

        if let Some(phase) = next {
            self.phase = phase;
            self.touch();
            Ok(phase)
        } else {
            bail!("No valid next phase from {:?}", self.phase);
        }
    }

    /// Jump to a specific phase (for recovery or testing).
    pub fn set_phase(&mut self, phase: LoopPhase) {
        self.phase = phase;
        self.touch();
    }

    // ── Task management ─────────────────────────────────────────────

    /// Add a task to the plan.
    pub fn add_task(&mut self, task: LoopTask) {
        self.tasks.push(task);
        self.touch();
    }

    /// Get a task by ID.
    pub fn get_task(&self, id: &str) -> Option<&LoopTask> {
        self.tasks.iter().find(|t| t.id == id)
    }

    /// Get a mutable reference to a task by ID.
    pub fn get_task_mut(&mut self, id: &str) -> Option<&mut LoopTask> {
        self.tasks.iter_mut().find(|t| t.id == id)
    }

    // ── Batch computation ───────────────────────────────────────────

    /// Compute execution batches from the current task list.
    ///
    /// Groups tasks into batches using topological ordering. Each batch
    /// contains tasks whose dependencies are all in *earlier* batches.
    /// Tasks within a batch that touch overlapping files are flagged
    /// as having conflicts.
    ///
    /// Uses Kahn's algorithm for topological sorting, grouping tasks
    /// by their dependency depth level.
    pub fn compute_batches(&mut self) -> Result<()> {
        if self.tasks.is_empty() {
            self.batches.clear();
            return Ok(());
        }

        use std::collections::{HashMap, HashSet, VecDeque};

        // Build adjacency graph
        let task_ids: HashSet<&str> = self.tasks.iter().map(|t| t.id.as_str()).collect();
        let mut in_degree: HashMap<&str, usize> = HashMap::new();
        let mut dependents: HashMap<&str, Vec<&str>> = HashMap::new(); // task -> tasks that depend on it

        for task in &self.tasks {
            in_degree.entry(task.id.as_str()).or_insert(0);
            dependents.entry(task.id.as_str()).or_insert_with(Vec::new);

            for dep in &task.depends_on {
                if !task_ids.contains(dep.as_str()) {
                    bail!(
                        "Task '{}' depends on '{}' which does not exist",
                        task.id,
                        dep
                    );
                }
                *in_degree.entry(task.id.as_str()).or_insert(0) += 1;
                dependents
                    .entry(dep.as_str())
                    .or_insert_with(Vec::new)
                    .push(task.id.as_str());
            }
        }

        // Kahn's algorithm with level tracking
        let mut queue: VecDeque<(&str, usize)> = VecDeque::new(); // (task_id, level)
        for task in &self.tasks {
            if task.depends_on.is_empty() {
                queue.push_back((task.id.as_str(), 0));
            }
        }

        let mut levels: HashMap<&str, usize> = HashMap::new();
        let mut processed: HashSet<&str> = HashSet::new();

        while let Some((task_id, level)) = queue.pop_front() {
            if processed.contains(task_id) {
                continue;
            }
            processed.insert(task_id);
            levels.insert(task_id, level);

            // Decrease in-degree of dependents
            if let Some(deps) = dependents.get(task_id) {
                for &dep_id in deps {
                    let deg = in_degree.get_mut(dep_id).unwrap();
                    *deg -= 1;
                    if *deg == 0 {
                        queue.push_back((dep_id, level + 1));
                    }
                }
            }
        }

        // Check for circular dependencies
        if processed.len() != self.tasks.len() {
            let unassigned: Vec<&str> = self
                .tasks
                .iter()
                .filter(|t| !processed.contains(t.id.as_str()))
                .map(|t| t.id.as_str())
                .collect();
            bail!(
                "Cannot compute batches: circular dependency detected. Unassigned tasks: {:?}",
                unassigned
            );
        }

        // Group tasks by level into batches
        let max_level = levels.values().copied().max().unwrap_or(0);
        let mut batches: Vec<TaskBatch> = Vec::new();

        for level in 0..=max_level {
            let batch_idx = level;
            let mut batch = TaskBatch::new(batch_idx);

            for task in &self.tasks {
                let task_level = levels.get(task.id.as_str()).copied().unwrap_or(0);
                if task_level != level {
                    continue;
                }

                // Check for file conflicts with tasks already in this batch
                let has_conflict = batch.tasks.iter().any(|bt| {
                    let bt_files: HashSet<_> = bt.touches_files.iter().collect();
                    task.touches_files.iter().any(|f| bt_files.contains(f))
                });

                if has_conflict {
                    batch.has_conflicts = true;
                }

                batch.add_task(task.clone());
            }

            if !batch.tasks.is_empty() {
                batches.push(batch);
            }
        }

        self.batches = batches;
        self.touch();
        Ok(())
    }

    /// Get the next pending batch, if any.
    pub fn next_pending_batch(&self) -> Option<&TaskBatch> {
        self.batches
            .iter()
            .find(|b| b.status == TaskStatus::Pending)
    }

    /// Get a mutable reference to a batch by index.
    pub fn get_batch_mut(&mut self, index: usize) -> Option<&mut TaskBatch> {
        self.batches.get_mut(index)
    }

    /// Count completed batches.
    pub fn completed_batch_count(&self) -> usize {
        self.batches
            .iter()
            .filter(|b| b.status == TaskStatus::Done)
            .count()
    }

    /// Count total batches.
    pub fn total_batch_count(&self) -> usize {
        self.batches.len()
    }

    // ── Issue management ────────────────────────────────────────────

    /// Add an issue found during verification.
    pub fn add_issue(&mut self, issue: Issue) {
        self.issues.push(issue);
        self.touch();
    }

    /// Get all confirmed, unfixed issues.
    pub fn confirmed_issues(&self) -> Vec<&Issue> {
        self.issues.iter().filter(|i| i.needs_fix()).collect()
    }

    /// Count issues by verdict.
    pub fn issues_by_verdict(&self, verdict: IssueVerdict) -> usize {
        self.issues
            .iter()
            .filter(|i| i.verdict == Some(verdict))
            .count()
    }

    /// Count fixed issues.
    pub fn fixed_issue_count(&self) -> usize {
        self.issues.iter().filter(|i| i.fixed).count()
    }

    // ── Verification ────────────────────────────────────────────────

    /// Record a verification result.
    pub fn record_verification(&mut self, result: VerificationResult) {
        // Merge issues into the global list
        let next_number = self.issues.len() + 1;
        for (i, mut issue) in result.issues.into_iter().enumerate() {
            issue.number = next_number + i;
            self.issues.push(issue);
        }
        // Store the result (without the moved issues)
        let mut stored = VerificationResult {
            issues: Vec::new(), // issues are in the global list now
            ..result
        };
        stored.issues = self
            .issues
            .iter()
            .filter(|i| i.number >= next_number)
            .cloned()
            .collect();
        self.last_verification = Some(stored);
        self.touch();
    }

    /// Whether the current state is "clean" (no unfixed confirmed issues,
    /// all verification gates passed).
    pub fn is_clean(&self) -> bool {
        let no_unfixed = !self.issues.iter().any(|i| i.needs_fix());
        let verify_ok = self
            .last_verification
            .as_ref()
            .map(|v| v.is_clean())
            .unwrap_or(false);
        no_unfixed && verify_ok
    }

    // ── Git integration ─────────────────────────────────────────────

    /// Record a commit hash.
    pub fn record_commit(&mut self, hash: impl Into<String>) {
        self.last_commit = Some(hash.into());
        self.touch();
    }

    /// Set the git clean status.
    pub fn set_git_clean(&mut self, clean: bool) {
        self.git_clean = clean;
        self.touch();
    }

    // ── Status and diagnostics ──────────────────────────────────────

    /// Produce a serializable status snapshot.
    pub fn status(&self) -> LoopStatus {
        LoopStatus {
            task: self.task.clone(),
            iteration: self.iteration,
            max_iterations: self.max_iterations,
            phase: self.phase,
            batches: self.batches.clone(),
            issues: self.issues.clone(),
            last_verification: self.last_verification.clone(),
            last_commit: self.last_commit.clone(),
            git_clean: self.git_clean,
            blocker: self.blocker.clone(),
            timestamp: Utc::now().to_rfc3339(),
        }
    }

    /// Produce a diagnostic report when the loop hits max iterations or
    /// emergency stop.
    pub fn diagnostic(&self) -> String {
        let mut s = String::with_capacity(4096);

        s.push_str("═══ AUTONOMOUS LOOP DIAGNOSTIC ═══\n\n");
        s.push_str(&format!("Task: {}\n", self.task));
        s.push_str(&format!(
            "Iterations used: {} / {}\n",
            self.iteration, self.max_iterations
        ));
        s.push_str(&format!("Phase at stop: {}\n", self.phase));

        if let Some(ref blocker) = self.blocker {
            s.push_str(&format!("Blocker: {}\n", blocker));
        }

        s.push_str(&format!("Emergency stopped: {}\n", self.emergency_stopped));

        // Batch progress
        s.push_str("\n── Batches ──\n");
        for batch in &self.batches {
            let task_ids: Vec<&str> = batch.tasks.iter().map(|t| t.id.as_str()).collect();
            s.push_str(&format!(
                "  Batch {}: [{}] — {}\n",
                batch.index,
                task_ids.join(", "),
                batch.status
            ));
            for task in &batch.tasks {
                s.push_str(&format!(
                    "    {}: {} [{}]\n",
                    task.id, task.description, task.status
                ));
            }
        }

        // Issue summary
        s.push_str("\n── Issues ──\n");
        let total = self.issues.len();
        let confirmed = self.issues_by_verdict(IssueVerdict::Confirmed);
        let false_pos = self.issues_by_verdict(IssueVerdict::FalsePositive);
        let deferred = self.issues_by_verdict(IssueVerdict::Deferred);
        let fixed = self.fixed_issue_count();
        s.push_str(&format!(
            "  Total: {} | Confirmed: {} | False positives: {} | Deferred: {} | Fixed: {}\n",
            total, confirmed, false_pos, deferred, fixed
        ));

        // Recurring issues
        s.push_str("\n── Unfixed Confirmed Issues ──\n");
        for issue in self.issues.iter().filter(|i| i.needs_fix()) {
            s.push_str(&format!(
                "  #{} [{}] {}{}\n",
                issue.number, issue.severity, issue.description, issue.location
            ));
            if !issue.evidence.is_empty() {
                s.push_str(&format!("    Evidence: {}\n", issue.evidence));
            }
            if !issue.fix_approach.is_empty() {
                s.push_str(&format!("    Fix approach: {}\n", issue.fix_approach));
            }
        }

        // Verification history
        if let Some(ref v) = self.last_verification {
            s.push_str("\n── Last Verification ──\n");
            s.push_str(&format!(
                "  Build: {}\n",
                if v.build_passed { "" } else { "" }
            ));
            s.push_str(&format!(
                "  Tests: {}\n",
                if v.tests_passed { "" } else { "" }
            ));
            s.push_str(&format!(
                "  Type check: {}\n",
                if v.type_check_passed { "" } else { "" }
            ));
            s.push_str(&format!(
                "  Lint: {}\n",
                if v.lint_passed { "" } else { "" }
            ));
        }

        s.push('\n');
        s
    }

    /// Update the timestamp.
    fn touch(&mut self) {
        self.updated_at = Utc::now().to_rfc3339();
    }
}

// ── Skill prompt ───────────────────────────────────────────────────────

/// The autonomous-loop skill content generator.
///
/// Produces the system-prompt instructions that guide the LLM through the
/// autonomous development workflow.
pub struct AutonomousLoopSkill;

impl AutonomousLoopSkill {
    /// Generate the full skill instructions to be injected into the system
    /// prompt when the autonomous-loop skill is active.
    pub fn skill_instructions() -> String {
        let prompt = r#"# Autonomous Development Loop Skill

You are operating the **autonomous-loop** skill. Your goal is to execute a
fully autonomous development cycle that produces a finished, verified, and
committed result from a single task description.

## Core Principles

1. **Never stop until genuinely done.** No "I think this looks good, please review" — keep going until verification gates pass clean.
2. **Every finding must survive cross-examination.** A bug is only a bug if it can be proven. An issue is only an issue if it can be demonstrated.
3. **Every checkpoint is a save point.** Git commits at every stable state mean any step is reversible.
4. **TDD for logic.** When implementing logic, algorithms, or data transformations — write the failing test first. When implementing UI layout or configuration, TDD is optional.

## Maximum Iterations

The loop runs at most **8 full iterations**. If still failing after 8 iterations, stop and produce a diagnostic report explaining what went wrong.

## Loop Phases

```
┌─────────────────────────────────────────────────────────────────┐
│                                                                 │
│  1. DESIGN ──── 2. PLAN ──── 3. IMPLEMENT ──── 4. VERIFY       │
│                                                  │              │
│                                                  ▼              │
│                                           Issues found?         │
│                                           ┌─────┴─────┐        │
│                                           │ YES       │ NO     │
│                                           ▼           ▼        │
│                                     5. RE-VALIDATE   7. DONE   │
│                                           │                     │
│                                     Real issues?                │
│                                     ┌────┴────┐                │
│                                     │ YES     │ NO (false +)   │
│                                     ▼         ▼                │
│                                   6. FIX    Discard,           │
│                                     │       re-verify           │
│                                     ▼                           │
│                              Commit fix ──→ back to 4           │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

## Phase 1: DESIGN

**Goal:** Understand requirements and produce a clear design before touching code.

### Design Quality Gate

Before proceeding, evaluate:

- [ ] Spec or design doc exists for this feature?
- [ ] Design is up-to-date with current codebase state?
- [ ] Approach is defined with specific files to touch?
- [ ] Acceptance criteria are concrete and testable?
- [ ] No known gaps or ambiguities in requirements?

**If ANY of these are "no":** Stop. Use the deep-research skill to investigate
and produce a solid design before continuing.

### Steps

1. Read all relevant context — specs, existing code, AGENTS.md, project conventions
2. If no spec/design exists, produce a minimal design doc
3. If a design already exists, validate it against the current codebase state
4. Identify risks and unknowns
5. **Commit checkpoint** if you created or updated a design doc

### Exit Criteria

- [ ] Objective is clear and testable
- [ ] Approach is defined
- [ ] Files to touch are identified
- [ ] Acceptance criteria are concrete

## Phase 2: PLAN

**Goal:** Decompose into ordered, verifiable implementation steps.

### Steps

1. Break into vertical slices — each slice delivers a working, testable increment
2. Order by dependency — foundations first, consumers last
3. Each task must have:
   - Task ID (e.g., T1, T2)
   - Exact file paths
   - What it accomplishes
   - How to verify it works
   - `dependsOn` — list of task IDs
   - `touchesFiles` — files this task creates or modifies
4. Group tasks into parallel execution batches
5. Mark commit points — commit after each batch completes

### Exit Criteria

- [ ] Every task has acceptance criteria
- [ ] Every task has a verification method
- [ ] Every task has dependsOn and touchesFiles
- [ ] Tasks are grouped into execution batches
- [ ] No circular dependencies
- [ ] No task exceeds ~5 files

## Phase 3: IMPLEMENT

**Goal:** Execute the plan by batch, parallelizing independent tasks, with commits at every stable point.

### Rules

**Rule 0: Simplicity First.** Before writing code: "What is the simplest thing that could work?"

**Rule 1: Batch Execution.** Execute tasks by batch, respecting the dependency graph.

**Rule 2: Build Must Stay Green.** After each batch: build compiles, existing tests pass.

**Rule 3: Scope Discipline.** Touch only what the task requires. No unsolicited refactoring.

**Rule 4: Commit Frequently.** After every successful batch:
```
git commit -m "<type>(<scope>): <what this batch accomplishes>"
```

### Commit Message Format

Types: `feat`, `fix`, `refactor`, `test`, `docs`, `chore`
Scopes: match the module/area being changed

Examples:
- ✅ `feat(auth): add JWT token generation`
- ✅ `test(cache): add LRU eviction tests`
- ❌ `feat: implement phase 1` — too coarse

### Safety Protocol

At the START of implementation:
```bash
git add -A && git commit -m "chore: checkpoint before <feature> implementation"
```

## Phase 4: VERIFY

**Goal:** Multi-axis verification that catches real problems.

### Steps

1. Run build, test, lint:
   ```bash
   npm run build && npm test && npm run lint
   # or: cargo build && cargo test && cargo clippy
   ```
   - [ ] Build succeeds with zero errors
   - [ ] All tests pass (existing + new)
   - [ ] Zero type/lint errors

2. Walk through acceptance criteria from Phase 2:
   - [ ] Every acceptance criterion is met
   - [ ] Edge cases handled
   - [ ] Error paths handled

3. **Log any issues found:**
   ```
   ISSUE [N]: [one-line description]
     Severity: Critical | Important | Minor | Nit
     Location: file:line or component
     Evidence: [exact error message or concrete observation]
     Reproducible: YES/NO
     Fix approach: [brief description]
   ```

**Severity definitions:**
- **Critical:** Build broken, data loss, security vulnerability — must fix
- **Important:** Incorrect behavior, failing tests, broken feature — must fix
- **Minor:** Style inconsistency, missing edge case — should fix
- **Nit:** Formatting, naming preference — optional

## Phase 5: RE-VALIDATE (The False Positive Filter)

**Goal:** Confirm that every issue found in Phase 4 is a REAL issue.

### For EVERY issue:

**Step 1: Reproduce or Demonstrate**
- Build error? → Re-read the exact error message and the code
- Test failure? → Re-run the specific failing test in isolation
- Logic bug? → Trace the data flow: input → wrong output

**Step 2: Cross-Examine** — if ANY answer is "no," it's likely a false positive:

| Question | Why it matters |
|----------|---------------|
| Does this violate a project convention? | Many "issues" are intentional styles |
| Is this actually in scope? | Adjacent code may look "wrong" but isn't this change |
| Would a staff engineer flag this? | Distinguishes real from theoretical |
| Is the "correct" version actually better here? | Context-dependent patterns exist |
| Does this affect actual behavior? | Theoretical issues waste time |

**Step 3: Verdict**

| Verdict | Action |
|---------|--------|
| **CONFIRMED** | Real issue → proceed to Phase 6 |
| **FALSE_POSITIVE** | Not a problem → discard, document why |
| **DEFERRED** | Real but out of scope → log, don't fix now |
| **NEEDS_CONTEXT** | Can't determine → ask the user |

### Common False Positive Patterns

- **Over-applying best practices** on internal-only functions
- **Misunderstanding intent** (variable "unused" but used in templates)
- **Generic rules vs project context** (project disables a linter rule intentionally)
- **Theoretical concerns** ("could be slow" with bounded data)
- **Adjacent code problems** outside task scope

## Phase 6: FIX (If CONFIRMED Issues Exist)

**Goal:** Fix only the confirmed, genuine issues.

### Rules

- **One fix per commit.** Each fix is independently revertable.
- **Fix the root cause, not the symptom.** Ask "why?" at least twice.
- **Re-run specific verification after each fix.**

After all fixes committed:
```bash
npm run build && npm test && npm run lint
```

Then **return to Phase 4 (VERIFY)** for a fresh pass.

## Phase 7: DONE

**Goal:** Final confirmation that the task is genuinely complete.

### Final Verification

- [ ] Build succeeds with zero errors
- [ ] Full test suite passes
- [ ] Type check passes
- [ ] Lint passes
- [ ] All acceptance criteria met
- [ ] No uncommitted changes (`git status` is clean)
- [ ] No TODO/FIXME/HACK that should have been resolved
- [ ] No debug logging left behind

### Completion Report

```
## Task Complete: [Task Name]

### Summary
[1-2 sentences]

### Changes
- [file list with one-line descriptions]

### Commits
[newest first]

### Verification
- Build: ✅ PASS
- Tests: ✅ PASS (N tests)
- Type check: ✅ PASS
- Lint: ✅ PASS

### Issues Found & Resolved
- [Issues confirmed and fixed]

### Discarded False Positives
- [Issues discarded with reasons]
```

## Emergency Stop Conditions

Stop immediately and report if:
- Build broken and can't fix within 2 attempts
- Tests failing and fix introduces new failures
- Hit 8 loop iterations
- Fundamental design flaw discovered
- Something genuinely not understood

## Anti-Rationalization Table

| Rationalization | Reality |
|---|---|
| "Build passes, probably good enough" | Build ≠ working. Tests + type checks + acceptance criteria matter. |
| "Mental review is sufficient" | Mental review misses the same bugs introduced. |
| "Minor issues can wait" | Minor issues compound into tomorrow's bugs. |
| "Skip re-validation, issue is obvious" | False positives waste hours. 5 min cross-examination saves 30 min. |
| "Commit everything at the end" | Catastrophic failure at min 45 = losing 45 min. |
| "These issues are all real" | When finding many issues at once, false positive rate is highest. |
| "Fix all issues at once" | Batch fixes hide which fix solved which issue. |
| "Improve nearby code while here" | Every unsolicited change is a risk. Stay in scope. |

## Red Flags (Self-Monitoring)

- Skipping re-validation because "the issue is obvious"
- Committing >100 lines without a build/test check
- Finding the same issue in iteration 3 that was "fixed" in iteration 2
- Rationalizing why a failed test "doesn't count"
- Broadening scope beyond the original task
- More than 3 consecutive fix-and-reverify cycles on the same issue
"#;
        prompt.to_string()
    }
}

// ── Tests ──────────────────────────────────────────────────────────────

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

    // ── LoopPhase tests ────────────────────────────────────────────

    #[test]
    fn test_phase_display() {
        assert_eq!(format!("{}", LoopPhase::Design), "DESIGN");
        assert_eq!(format!("{}", LoopPhase::Plan), "PLAN");
        assert_eq!(format!("{}", LoopPhase::Implement), "IMPLEMENT");
        assert_eq!(format!("{}", LoopPhase::Verify), "VERIFY");
        assert_eq!(format!("{}", LoopPhase::ReValidate), "RE-VALIDATE");
        assert_eq!(format!("{}", LoopPhase::Fix), "FIX");
        assert_eq!(format!("{}", LoopPhase::Done), "DONE");
    }

    #[test]
    fn test_phase_next() {
        assert_eq!(LoopPhase::Design.next(), Some(LoopPhase::Plan));
        assert_eq!(LoopPhase::Plan.next(), Some(LoopPhase::Implement));
        assert_eq!(LoopPhase::Implement.next(), Some(LoopPhase::Verify));
        assert_eq!(LoopPhase::Verify.next(), Some(LoopPhase::ReValidate));
        assert_eq!(LoopPhase::ReValidate.next(), Some(LoopPhase::Fix));
        assert_eq!(LoopPhase::Fix.next(), Some(LoopPhase::Verify));
        assert_eq!(LoopPhase::Done.next(), None);
    }

    #[test]
    fn test_phase_can_exit_on_clean() {
        assert!(LoopPhase::Verify.can_exit_on_clean());
        assert!(LoopPhase::ReValidate.can_exit_on_clean());
        assert!(!LoopPhase::Design.can_exit_on_clean());
        assert!(!LoopPhase::Fix.can_exit_on_clean());
    }

    #[test]
    fn test_phase_all() {
        let all = LoopPhase::all();
        assert_eq!(all.len(), 7);
        assert_eq!(all[0], LoopPhase::Design);
        assert_eq!(all[6], LoopPhase::Done);
    }

    // ── TaskStatus tests ───────────────────────────────────────────

    #[test]
    fn test_task_status_display() {
        assert_eq!(format!("{}", TaskStatus::Pending), "pending");
        assert_eq!(format!("{}", TaskStatus::Running), "running");
        assert_eq!(format!("{}", TaskStatus::Done), "done");
        assert_eq!(format!("{}", TaskStatus::Failed), "failed");
    }

    // ── LoopTask tests ─────────────────────────────────────────────

    #[test]
    fn test_task_builder() {
        let task = LoopTask::new("T1", "Create auth module")
            .touches("src/auth.rs")
            .touches("src/lib.rs")
            .depends_on("T0")
            .verify_with("cargo test auth");

        assert_eq!(task.id, "T1");
        assert_eq!(task.description, "Create auth module");
        assert_eq!(task.touches_files.len(), 2);
        assert_eq!(task.depends_on, vec!["T0"]);
        assert_eq!(task.verification, "cargo test auth");
        assert_eq!(task.status, TaskStatus::Pending);
    }

    #[test]
    fn test_task_lifecycle() {
        let mut task = LoopTask::new("T1", "Do something");
        assert_eq!(task.status, TaskStatus::Pending);

        task.start();
        assert_eq!(task.status, TaskStatus::Running);

        task.complete(Some("abc123".to_string()));
        assert_eq!(task.status, TaskStatus::Done);
        assert_eq!(task.commit_hash, Some("abc123".to_string()));
    }

    #[test]
    fn test_task_fail() {
        let mut task = LoopTask::new("T1", "Do something");
        task.start();
        task.fail();
        assert_eq!(task.status, TaskStatus::Failed);
    }

    // ── TaskBatch tests ────────────────────────────────────────────

    #[test]
    fn test_batch_lifecycle() {
        let mut batch = TaskBatch::new(0);
        batch.add_task(LoopTask::new("T1", "Task 1"));
        batch.add_task(LoopTask::new("T2", "Task 2"));

        assert!(!batch.all_done());
        assert!(!batch.any_failed());

        batch.start();
        assert_eq!(batch.status, TaskStatus::Running);
        assert_eq!(batch.tasks[0].status, TaskStatus::Running);

        batch.complete();
        assert_eq!(batch.status, TaskStatus::Done);
    }

    #[test]
    fn test_batch_all_done() {
        let mut batch = TaskBatch::new(0);
        let mut t1 = LoopTask::new("T1", "Task 1");
        t1.complete(None);
        let mut t2 = LoopTask::new("T2", "Task 2");
        t2.complete(None);
        batch.add_task(t1);
        batch.add_task(t2);
        assert!(batch.all_done());
    }

    #[test]
    fn test_batch_any_failed() {
        let mut batch = TaskBatch::new(0);
        batch.add_task(LoopTask::new("T1", "Task 1"));
        let mut t2 = LoopTask::new("T2", "Task 2");
        t2.fail();
        batch.add_task(t2);
        assert!(batch.any_failed());
    }

    // ── Issue tests ────────────────────────────────────────────────

    #[test]
    fn test_issue_builder() {
        let issue = Issue::new(
            1,
            "Build fails on ARM64",
            IssueSeverity::Critical,
            "src/build.rs:42",
        )
        .with_evidence("error: unsupported target")
        .reproducible(true)
        .fix_approach("Add ARM64 target detection");

        assert_eq!(issue.number, 1);
        assert_eq!(issue.severity, IssueSeverity::Critical);
        assert!(issue.reproducible);
        assert!(issue.verdict.is_none());
        assert!(!issue.fixed);
    }

    #[test]
    fn test_issue_verdict() {
        let mut issue = Issue::new(1, "Test", IssueSeverity::Minor, "main.rs");
        assert!(!issue.needs_fix());

        issue.set_verdict(IssueVerdict::Confirmed, "Reproduced locally");
        assert!(issue.needs_fix());
        assert!(issue.is_actionable());

        issue.mark_fixed(Some("abc123".to_string()));
        assert!(!issue.needs_fix());
        assert!(issue.fixed);
        assert_eq!(issue.fix_commit, Some("abc123".to_string()));
    }

    #[test]
    fn test_issue_false_positive() {
        let mut issue = Issue::new(1, "Test", IssueSeverity::Nit, "main.rs");
        issue.set_verdict(
            IssueVerdict::FalsePositive,
            "Internal function, callers trusted",
        );
        assert!(!issue.needs_fix());
        assert!(!issue.is_actionable());
    }

    #[test]
    fn test_issue_deferred() {
        let mut issue = Issue::new(1, "Test", IssueSeverity::Minor, "main.rs");
        issue.set_verdict(IssueVerdict::Deferred, "Out of scope for this task");
        assert!(!issue.needs_fix());
        assert!(!issue.is_actionable());
    }

    #[test]
    fn test_severity_ordering() {
        assert!(IssueSeverity::Critical > IssueSeverity::Important);
        assert!(IssueSeverity::Important > IssueSeverity::Minor);
        assert!(IssueSeverity::Minor > IssueSeverity::Nit);
    }

    #[test]
    fn test_severity_display() {
        assert_eq!(format!("{}", IssueSeverity::Critical), "Critical");
        assert_eq!(format!("{}", IssueSeverity::Important), "Important");
        assert_eq!(format!("{}", IssueSeverity::Minor), "Minor");
        assert_eq!(format!("{}", IssueSeverity::Nit), "Nit");
    }

    #[test]
    fn test_verdict_display() {
        assert_eq!(format!("{}", IssueVerdict::Confirmed), "CONFIRMED");
        assert_eq!(format!("{}", IssueVerdict::FalsePositive), "FALSE_POSITIVE");
        assert_eq!(format!("{}", IssueVerdict::Deferred), "DEFERRED");
        assert_eq!(format!("{}", IssueVerdict::NeedsContext), "NEEDS_CONTEXT");
    }

    // ── VerificationResult tests ───────────────────────────────────

    #[test]
    fn test_verification_result_new() {
        let result = VerificationResult::new();
        assert!(!result.build_passed);
        assert!(!result.tests_passed);
        assert!(!result.type_check_passed);
        assert!(!result.lint_passed);
        assert!(result.issues.is_empty());
        assert!(!result.is_clean());
    }

    #[test]
    fn test_verification_result_clean() {
        let result = VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        };
        assert!(result.is_clean());
        assert!(result.critical_passed());
    }

    #[test]
    fn test_verification_result_with_issues() {
        let mut result = VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        };
        result
            .issues
            .push(Issue::new(1, "Bug", IssueSeverity::Minor, "main.rs"));
        assert!(!result.is_clean());
    }

    #[test]
    fn test_verification_critical_failed() {
        let result = VerificationResult {
            build_passed: false,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        };
        assert!(!result.critical_passed());
    }

    #[test]
    fn test_verification_issue_count_by_severity() {
        let mut result = VerificationResult::new();
        result
            .issues
            .push(Issue::new(1, "A", IssueSeverity::Critical, "a.rs"));
        result
            .issues
            .push(Issue::new(2, "B", IssueSeverity::Critical, "b.rs"));
        result
            .issues
            .push(Issue::new(3, "C", IssueSeverity::Minor, "c.rs"));
        assert_eq!(result.issue_count_by_severity(IssueSeverity::Critical), 2);
        assert_eq!(result.issue_count_by_severity(IssueSeverity::Minor), 1);
        assert_eq!(result.issue_count_by_severity(IssueSeverity::Nit), 0);
    }

    // ── AutonomousLoop tests ───────────────────────────────────────

    #[test]
    fn test_loop_new() {
        let al = AutonomousLoop::new("Implement auth");
        assert_eq!(al.task, "Implement auth");
        assert_eq!(al.iteration, 0);
        assert_eq!(al.max_iterations, MAX_ITERATIONS);
        assert_eq!(al.phase, LoopPhase::Design);
        assert!(!al.started);
        assert!(al.tasks.is_empty());
        assert!(al.issues.is_empty());
    }

    #[test]
    fn test_loop_with_max_iterations() {
        let al = AutonomousLoop::new("Test").with_max_iterations(4);
        assert_eq!(al.max_iterations, 4);
    }

    #[test]
    fn test_loop_with_max_iterations_clamped() {
        let al = AutonomousLoop::new("Test").with_max_iterations(0);
        assert_eq!(al.max_iterations, 1);

        let al = AutonomousLoop::new("Test").with_max_iterations(100);
        assert_eq!(al.max_iterations, MAX_ITERATIONS);
    }

    #[test]
    fn test_loop_start() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        assert!(al.started);
        assert_eq!(al.iteration, 1);
        assert_eq!(al.phase, LoopPhase::Design);
    }

    #[test]
    fn test_loop_start_twice() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        assert!(al.start().is_err());
    }

    #[test]
    fn test_loop_emergency_stop() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.emergency_stop("Build is broken beyond repair");
        assert!(al.emergency_stopped);
        assert_eq!(
            al.blocker,
            Some("Build is broken beyond repair".to_string())
        );
    }

    #[test]
    fn test_loop_advance_not_started() {
        let mut al = AutonomousLoop::new("Test");
        assert!(al.advance().is_err());
    }

    #[test]
    fn test_loop_advance_after_emergency_stop() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.emergency_stop("Nope");
        assert!(al.advance().is_err());
    }

    #[test]
    fn test_loop_advance_design_to_plan() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        let next = al.advance().unwrap();
        assert_eq!(next, LoopPhase::Plan);
        assert_eq!(al.phase, LoopPhase::Plan);
    }

    #[test]
    fn test_loop_advance_plan_to_implement() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.advance().unwrap(); // Design → Plan
        let next = al.advance().unwrap(); // Plan → Implement
        assert_eq!(next, LoopPhase::Implement);
    }

    #[test]
    fn test_loop_advance_implement_to_verify() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.advance().unwrap(); // → Plan
        al.advance().unwrap(); // → Implement
        let next = al.advance().unwrap(); // → Verify
        assert_eq!(next, LoopPhase::Verify);
    }

    #[test]
    fn test_loop_advance_verify_clean_goes_to_done() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.advance().unwrap(); // → Plan
        al.advance().unwrap(); // → Implement
        al.advance().unwrap(); // → Verify

        // Record a clean verification
        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        });

        let next = al.advance().unwrap(); // → Done (clean)
        assert_eq!(next, LoopPhase::Done);
    }

    #[test]
    fn test_loop_advance_verify_with_issues_goes_to_revalidate() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.advance().unwrap(); // → Plan
        al.advance().unwrap(); // → Implement
        al.advance().unwrap(); // → Verify

        // Record verification with an issue
        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![Issue::new(1, "A bug", IssueSeverity::Important, "main.rs")],
            timestamp: Utc::now().to_rfc3339(),
        });

        let next = al.advance().unwrap(); // → ReValidate
        assert_eq!(next, LoopPhase::ReValidate);
    }

    #[test]
    fn test_loop_advance_revalidate_confirmed_goes_to_fix() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.advance().unwrap(); // → Plan
        al.advance().unwrap(); // → Implement
        al.advance().unwrap(); // → Verify

        // Add an issue and confirm it
        let mut issue = Issue::new(1, "A bug", IssueSeverity::Important, "main.rs");
        issue.set_verdict(IssueVerdict::Confirmed, "Reproduced");
        al.add_issue(issue);

        al.set_phase(LoopPhase::ReValidate);
        let next = al.advance().unwrap(); // → Fix
        assert_eq!(next, LoopPhase::Fix);
    }

    #[test]
    fn test_loop_advance_revalidate_false_positive_goes_to_done() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();

        // Add a false-positive issue
        let mut issue = Issue::new(1, "False alarm", IssueSeverity::Nit, "main.rs");
        issue.set_verdict(IssueVerdict::FalsePositive, "Internal function");
        al.add_issue(issue);

        al.set_phase(LoopPhase::ReValidate);
        let next = al.advance().unwrap(); // → Done
        assert_eq!(next, LoopPhase::Done);
    }

    #[test]
    fn test_loop_advance_fix_goes_to_verify_with_increment() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        assert_eq!(al.iteration, 1);

        al.set_phase(LoopPhase::Fix);
        let next = al.advance().unwrap(); // → Verify, iteration++
        assert_eq!(next, LoopPhase::Verify);
        assert_eq!(al.iteration, 2);
    }

    #[test]
    fn test_loop_advance_done_is_error() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();
        al.set_phase(LoopPhase::Done);
        assert!(al.advance().is_err());
    }

    #[test]
    fn test_loop_max_iterations_exceeded() {
        let mut al = AutonomousLoop::new("Test").with_max_iterations(2);
        al.start().unwrap();
        al.iteration = 2;

        al.set_phase(LoopPhase::Fix);
        assert!(al.advance().is_err());
        assert!(al.emergency_stopped);
    }

    #[test]
    fn test_loop_set_phase() {
        let mut al = AutonomousLoop::new("Test");
        al.set_phase(LoopPhase::Verify);
        assert_eq!(al.phase, LoopPhase::Verify);
    }

    // ── Task management tests ──────────────────────────────────────

    #[test]
    fn test_add_and_get_task() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Create module"));
        al.add_task(LoopTask::new("T2", "Add tests"));

        assert_eq!(al.tasks.len(), 2);
        assert_eq!(al.get_task("T1").unwrap().description, "Create module");
        assert_eq!(al.get_task("T2").unwrap().description, "Add tests");
        assert!(al.get_task("T3").is_none());
    }

    #[test]
    fn test_get_task_mut() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Create module"));

        al.get_task_mut("T1")
            .unwrap()
            .complete(Some("abc".to_string()));
        assert_eq!(
            al.get_task("T1").unwrap().commit_hash,
            Some("abc".to_string())
        );
    }

    // ── Batch computation tests ────────────────────────────────────

    #[test]
    fn test_compute_batches_empty() {
        let mut al = AutonomousLoop::new("Test");
        al.compute_batches().unwrap();
        assert!(al.batches.is_empty());
    }

    #[test]
    fn test_compute_batches_single_task() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Do thing"));
        al.compute_batches().unwrap();

        assert_eq!(al.batches.len(), 1);
        assert_eq!(al.batches[0].tasks.len(), 1);
        assert!(!al.batches[0].has_conflicts);
    }

    #[test]
    fn test_compute_batches_parallel() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Task 1"));
        al.add_task(LoopTask::new("T2", "Task 2"));
        al.compute_batches().unwrap();

        // Both in batch 0 (no dependencies)
        assert_eq!(al.batches.len(), 1);
        assert_eq!(al.batches[0].tasks.len(), 2);
    }

    #[test]
    fn test_compute_batches_sequential() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Foundation"));
        al.add_task(LoopTask::new("T2", "Build on foundation").depends_on("T1"));
        al.add_task(LoopTask::new("T3", "Final layer").depends_on("T2"));

        al.compute_batches().unwrap();

        assert_eq!(al.batches.len(), 3);
        assert_eq!(al.batches[0].tasks[0].id, "T1");
        assert_eq!(al.batches[1].tasks[0].id, "T2");
        assert_eq!(al.batches[2].tasks[0].id, "T3");
    }

    #[test]
    fn test_compute_batches_mixed() {
        let mut al = AutonomousLoop::new("Test");
        // T1, T2 independent → batch 0
        al.add_task(LoopTask::new("T1", "Independent 1"));
        al.add_task(LoopTask::new("T2", "Independent 2"));
        // T3 depends on T1, T4 depends on T2 → batch 1
        al.add_task(LoopTask::new("T3", "After T1").depends_on("T1"));
        al.add_task(LoopTask::new("T4", "After T2").depends_on("T2"));
        // T5 depends on T3, T4 → batch 2
        al.add_task(
            LoopTask::new("T5", "After T3 and T4")
                .depends_on("T3")
                .depends_on("T4"),
        );

        al.compute_batches().unwrap();

        assert_eq!(al.batches.len(), 3);
        assert_eq!(al.batches[0].tasks.len(), 2);
        assert_eq!(al.batches[1].tasks.len(), 2);
        assert_eq!(al.batches[2].tasks.len(), 1);
    }

    #[test]
    fn test_compute_batches_file_conflicts() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Touch lib").touches("src/lib.rs"));
        al.add_task(LoopTask::new("T2", "Also touch lib").touches("src/lib.rs"));

        al.compute_batches().unwrap();

        // Both in batch 0 but flagged as conflicting
        assert_eq!(al.batches.len(), 1);
        assert!(al.batches[0].has_conflicts);
    }

    #[test]
    fn test_compute_batches_circular_dependency() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Circular 1").depends_on("T2"));
        al.add_task(LoopTask::new("T2", "Circular 2").depends_on("T1"));

        let result = al.compute_batches();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("circular dependency"));
    }

    #[test]
    fn test_next_pending_batch() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Task 1"));
        al.add_task(LoopTask::new("T2", "Task 2").depends_on("T1"));
        al.compute_batches().unwrap();

        assert!(al.next_pending_batch().is_some());
        assert_eq!(al.next_pending_batch().unwrap().index, 0);

        al.batches[0].status = TaskStatus::Done;
        assert!(al.next_pending_batch().is_some());
        assert_eq!(al.next_pending_batch().unwrap().index, 1);

        al.batches[1].status = TaskStatus::Done;
        assert!(al.next_pending_batch().is_none());
    }

    #[test]
    fn test_completed_batch_count() {
        let mut al = AutonomousLoop::new("Test");
        al.add_task(LoopTask::new("T1", "Task 1"));
        al.add_task(LoopTask::new("T2", "Task 2").depends_on("T1"));
        al.compute_batches().unwrap();

        assert_eq!(al.completed_batch_count(), 0);
        assert_eq!(al.total_batch_count(), 2);

        al.batches[0].status = TaskStatus::Done;
        assert_eq!(al.completed_batch_count(), 1);
    }

    // ── Issue management tests ─────────────────────────────────────

    #[test]
    fn test_add_issue() {
        let mut al = AutonomousLoop::new("Test");
        al.add_issue(Issue::new(1, "Bug", IssueSeverity::Important, "main.rs"));

        assert_eq!(al.issues.len(), 1);
        assert_eq!(al.issues[0].description, "Bug");
    }

    #[test]
    fn test_confirmed_issues() {
        let mut al = AutonomousLoop::new("Test");

        // Add a confirmed issue
        let mut confirmed = Issue::new(1, "Real bug", IssueSeverity::Important, "main.rs");
        confirmed.set_verdict(IssueVerdict::Confirmed, "Reproduced");
        al.add_issue(confirmed);

        // Add a false positive
        let mut fp = Issue::new(2, "False alarm", IssueSeverity::Nit, "lib.rs");
        fp.set_verdict(IssueVerdict::FalsePositive, "Internal function");
        al.add_issue(fp);

        // Add a fixed issue
        let mut fixed = Issue::new(3, "Already fixed", IssueSeverity::Minor, "util.rs");
        fixed.set_verdict(IssueVerdict::Confirmed, "Was real");
        fixed.mark_fixed(None);
        al.add_issue(fixed);

        assert_eq!(al.confirmed_issues().len(), 1);
        assert_eq!(al.confirmed_issues()[0].description, "Real bug");
    }

    #[test]
    fn test_issues_by_verdict() {
        let mut al = AutonomousLoop::new("Test");

        let mut i1 = Issue::new(1, "A", IssueSeverity::Minor, "a");
        i1.set_verdict(IssueVerdict::Confirmed, "Real");
        al.add_issue(i1);

        let mut i2 = Issue::new(2, "B", IssueSeverity::Nit, "b");
        i2.set_verdict(IssueVerdict::FalsePositive, "Fake");
        al.add_issue(i2);

        let mut i3 = Issue::new(3, "C", IssueSeverity::Minor, "c");
        i3.set_verdict(IssueVerdict::Confirmed, "Real");
        al.add_issue(i3);

        assert_eq!(al.issues_by_verdict(IssueVerdict::Confirmed), 2);
        assert_eq!(al.issues_by_verdict(IssueVerdict::FalsePositive), 1);
        assert_eq!(al.issues_by_verdict(IssueVerdict::Deferred), 0);
    }

    #[test]
    fn test_fixed_issue_count() {
        let mut al = AutonomousLoop::new("Test");

        let mut i1 = Issue::new(1, "A", IssueSeverity::Minor, "a");
        i1.mark_fixed(Some("abc".to_string()));
        al.add_issue(i1);

        al.add_issue(Issue::new(2, "B", IssueSeverity::Minor, "b"));

        assert_eq!(al.fixed_issue_count(), 1);
    }

    // ── Verification tests ─────────────────────────────────────────

    #[test]
    fn test_record_verification() {
        let mut al = AutonomousLoop::new("Test");
        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![Issue::new(1, "Bug", IssueSeverity::Minor, "main.rs")],
            timestamp: Utc::now().to_rfc3339(),
        });

        assert!(al.last_verification.is_some());
        assert_eq!(al.issues.len(), 1);
    }

    #[test]
    fn test_is_clean() {
        let mut al = AutonomousLoop::new("Test");
        assert!(!al.is_clean()); // No verification yet

        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        });
        assert!(al.is_clean());
    }

    #[test]
    fn test_is_dirty_with_issue() {
        let mut al = AutonomousLoop::new("Test");
        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![Issue::new(1, "Bug", IssueSeverity::Minor, "main.rs")],
            timestamp: Utc::now().to_rfc3339(),
        });
        assert!(!al.is_clean());
    }

    // ── Git integration tests ──────────────────────────────────────

    #[test]
    fn test_record_commit() {
        let mut al = AutonomousLoop::new("Test");
        al.record_commit("deadbeef");
        assert_eq!(al.last_commit, Some("deadbeef".to_string()));
    }

    #[test]
    fn test_set_git_clean() {
        let mut al = AutonomousLoop::new("Test");
        al.set_git_clean(false);
        assert!(!al.git_clean);
        al.set_git_clean(true);
        assert!(al.git_clean);
    }

    // ── Status and diagnostics tests ───────────────────────────────

    #[test]
    fn test_status_snapshot() {
        let mut al = AutonomousLoop::new("Build auth system");
        al.start().unwrap();
        al.add_task(LoopTask::new("T1", "Create module"));
        al.compute_batches().unwrap();

        let status = al.status();
        assert_eq!(status.task, "Build auth system");
        assert_eq!(status.iteration, 1);
        assert_eq!(status.phase, LoopPhase::Design);
        assert_eq!(status.batches.len(), 1);
        assert!(status.git_clean);
    }

    #[test]
    fn test_status_render() {
        let mut al = AutonomousLoop::new("Test task");
        al.start().unwrap();
        al.add_task(LoopTask::new("T1", "Foundation"));
        al.add_task(LoopTask::new("T2", "Build on it").depends_on("T1"));
        al.compute_batches().unwrap();
        al.record_commit("abc1234");

        let status = al.status();
        let rendered = status.render();

        assert!(rendered.contains("AUTONOMOUS LOOP STATUS"));
        assert!(rendered.contains("Test task"));
        assert!(rendered.contains("DESIGN"));
        assert!(rendered.contains("T1"));
        assert!(rendered.contains("abc1234"));
    }

    #[test]
    fn test_diagnostic() {
        let mut al = AutonomousLoop::new("Test task");
        al.start().unwrap();
        al.emergency_stop("Hit max iterations");

        let diag = al.diagnostic();
        assert!(diag.contains("AUTONOMOUS LOOP DIAGNOSTIC"));
        assert!(diag.contains("Test task"));
        assert!(diag.contains("Hit max iterations"));
    }

    #[test]
    fn test_diagnostic_with_issues() {
        let mut al = AutonomousLoop::new("Test");
        al.start().unwrap();

        let mut issue = Issue::new(
            1,
            "Critical build failure",
            IssueSeverity::Critical,
            "build.rs:1",
        );
        issue.set_verdict(IssueVerdict::Confirmed, "Build won't compile");
        issue.set_verdict(IssueVerdict::Confirmed, "Still broken");
        al.add_issue(issue);

        let diag = al.diagnostic();
        assert!(diag.contains("Critical build failure"));
        assert!(diag.contains("build.rs:1"));
    }

    // ── Skill prompt test ──────────────────────────────────────────

    #[test]
    fn test_skill_instructions() {
        let prompt = AutonomousLoopSkill::skill_instructions();
        assert!(prompt.contains("Autonomous Development Loop"));
        assert!(prompt.contains("DESIGN"));
        assert!(prompt.contains("PLAN"));
        assert!(prompt.contains("IMPLEMENT"));
        assert!(prompt.contains("VERIFY"));
        assert!(prompt.contains("RE-VALIDATE"));
        assert!(prompt.contains("FIX"));
        assert!(prompt.contains("DONE"));
        assert!(prompt.contains("8"));
        assert!(prompt.contains("Emergency Stop"));
        assert!(prompt.contains("Anti-Rationalization"));
        assert!(prompt.contains("Red Flags"));
    }

    // ── Full loop integration test ─────────────────────────────────

    #[test]
    fn test_full_loop_happy_path() {
        let mut al = AutonomousLoop::new("Implement caching").with_max_iterations(3);
        al.start().unwrap();
        assert_eq!(al.iteration, 1);
        assert_eq!(al.phase, LoopPhase::Design);

        // Design → Plan
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Plan);

        // Add tasks
        al.add_task(LoopTask::new("T1", "Create cache module").touches("src/cache.rs"));
        al.add_task(
            LoopTask::new("T2", "Add tests")
                .depends_on("T1")
                .touches("tests/cache_test.rs"),
        );
        al.compute_batches().unwrap();
        assert_eq!(al.total_batch_count(), 2);

        // Plan → Implement
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Implement);

        // Implement → Verify
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Verify);

        // Record clean verification
        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        });
        assert!(al.is_clean());

        // Verify → Done
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Done);
    }

    #[test]
    fn test_full_loop_with_fix_cycle() {
        let mut al = AutonomousLoop::new("Fix bugs").with_max_iterations(4);
        al.start().unwrap();

        // Fast forward to Verify
        al.set_phase(LoopPhase::Verify);

        // Record verification with issue
        al.record_verification(VerificationResult {
            build_passed: false,
            tests_passed: false,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![
                Issue::new(1, "Build fails", IssueSeverity::Critical, "main.rs:10")
                    .with_evidence("undefined variable"),
            ],
            timestamp: Utc::now().to_rfc3339(),
        });
        assert!(!al.is_clean());

        // Verify → ReValidate
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::ReValidate);

        // Confirm the issue
        al.issues[0].set_verdict(IssueVerdict::Confirmed, "Build output reproduced");

        // ReValidate → Fix
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Fix);

        // Fix the issue
        al.issues[0].mark_fixed(Some("fix123".to_string()));
        al.record_commit("fix123");

        // Fix → Verify (iteration 2)
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Verify);
        assert_eq!(al.iteration, 2);

        // Now record clean verification
        al.record_verification(VerificationResult {
            build_passed: true,
            tests_passed: true,
            type_check_passed: true,
            lint_passed: true,
            issues: vec![],
            timestamp: Utc::now().to_rfc3339(),
        });

        // Verify → Done
        al.advance().unwrap();
        assert_eq!(al.phase, LoopPhase::Done);
    }

    // ── Serialization tests ────────────────────────────────────────

    #[test]
    fn test_loop_serde_roundtrip() {
        let mut al = AutonomousLoop::new("Serialize test");
        al.start().unwrap();
        al.add_task(LoopTask::new("T1", "Do work").touches("src/main.rs"));
        al.compute_batches().unwrap();
        al.add_issue(Issue::new(1, "Bug", IssueSeverity::Important, "main.rs"));
        al.record_commit("abc123");

        let json = serde_json::to_string_pretty(&al).unwrap();
        let parsed: AutonomousLoop = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.task, al.task);
        assert_eq!(parsed.iteration, al.iteration);
        assert_eq!(parsed.phase, al.phase);
        assert_eq!(parsed.tasks.len(), 1);
        assert_eq!(parsed.batches.len(), 1);
        assert_eq!(parsed.issues.len(), 1);
        assert_eq!(parsed.last_commit, Some("abc123".to_string()));
    }

    #[test]
    fn test_status_serde_roundtrip() {
        let al = AutonomousLoop::new("Status test");
        let status = al.status();

        let json = serde_json::to_string(&status).unwrap();
        let parsed: LoopStatus = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.task, status.task);
        assert_eq!(parsed.iteration, status.iteration);
        assert_eq!(parsed.phase, status.phase);
    }

    #[test]
    fn test_verification_result_serde_roundtrip() {
        let result = VerificationResult {
            build_passed: true,
            tests_passed: false,
            type_check_passed: true,
            lint_passed: false,
            issues: vec![Issue::new(
                1,
                "Test fail",
                IssueSeverity::Important,
                "test.rs",
            )],
            timestamp: Utc::now().to_rfc3339(),
        };

        let json = serde_json::to_string(&result).unwrap();
        let parsed: VerificationResult = serde_json::from_str(&json).unwrap();

        assert!(parsed.build_passed);
        assert!(!parsed.tests_passed);
        assert_eq!(parsed.issues.len(), 1);
    }

    #[test]
    fn test_issue_serde_roundtrip() {
        let mut issue = Issue::new(1, "Bug", IssueSeverity::Critical, "main.rs:10")
            .with_evidence("error: undefined")
            .reproducible(true)
            .fix_approach("Add variable declaration");
        issue.set_verdict(IssueVerdict::Confirmed, "Reproduced on main");
        issue.mark_fixed(Some("fix456".to_string()));

        let json = serde_json::to_string(&issue).unwrap();
        let parsed: Issue = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.number, 1);
        assert_eq!(parsed.severity, IssueSeverity::Critical);
        assert!(parsed.reproducible);
        assert_eq!(parsed.verdict, Some(IssueVerdict::Confirmed));
        assert!(parsed.fixed);
        assert_eq!(parsed.fix_commit, Some("fix456".to_string()));
    }

    #[test]
    fn test_loop_task_serde_roundtrip() {
        let task = LoopTask::new("T1", "Create module")
            .touches("src/mod.rs")
            .depends_on("T0")
            .verify_with("cargo test");

        let json = serde_json::to_string(&task).unwrap();
        let parsed: LoopTask = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.id, "T1");
        assert_eq!(parsed.touches_files.len(), 1);
        assert_eq!(parsed.depends_on, vec!["T0"]);
        assert_eq!(parsed.verification, "cargo test");
    }
}