orch-cli 0.100.13

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
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
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
//! Per-agent runner trait, error types, and agent registry.
//!
//! Each agent (Claude, Codex, OpenCode, Grok) has a different CLI invocation,
//! output format, and error pattern. This module defines a common trait
//! so the runner can delegate parsing and error classification to the
//! correct implementation.

#[macro_use]
mod delegate;
/// Shared error pattern detection utilities used by multiple agent runners.
pub(crate) mod patterns;

pub mod claude;
pub mod codex;
pub mod grok;
pub mod kimi;
pub mod minimax;
pub mod opencode;

use crate::config;
use crate::parser::AgentResponse;
use std::collections::BTreeSet;
use std::error;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::path::PathBuf;
use std::time::Duration;
use tokio::process::Command;

/// Unified permission rules that each agent translates into its native flags.
///
/// Instead of hardcoding `--permission-mode bypassPermissions` for Claude and
/// `--sandbox workspace-write` for Codex, we define a single set of rules and
/// let each `AgentRunner` format them for its CLI.
#[derive(Debug, Clone)]
pub struct PermissionRules {
    /// Whether the agent runs fully autonomous (no user prompts).
    pub autonomous: bool,
    /// Sandbox level for filesystem access.
    pub sandbox: SandboxLevel,
    /// Tool patterns to disallow (e.g., `["Bash(rm *)", "Bash(rm -*)"]`).
    pub disallowed_tools: Vec<String>,
    /// Tools to allow (whitelist). Overrides `disallowed_tools` when non-empty.
    ///
    /// Items are either agent-native tool names (e.g., "Edit", "Write", "Bash")
    /// or CLI command names (e.g., "git", "npm") which get translated to
    /// agent-specific patterns (e.g., `Bash(git*)` for Claude).
    pub allowed_tools: Vec<String>,
    /// Paths where the agent is allowed to edit files (worktree path).
    /// When set, Edit/Write tools are scoped to these paths only.
    /// Set dynamically per invocation (not from config).
    pub allowed_edit_paths: Vec<PathBuf>,
    /// Restrict to orchestration-only operations — denies Read, Glob, Grep,
    /// and Bash commands for browsing/reading files (ls, cat, find, etc.).
    /// Agents translate this into their native permission model.
    pub deny_read_only: bool,
    /// Additional directories that must be writable (e.g. the git common dir
    /// when running inside a worktree whose `.git` metadata lives outside the
    /// sandbox root). Codex translates these into `--add-dir` flags; other
    /// agents ignore the field.
    pub extra_writable_dirs: Vec<PathBuf>,
}

/// Sandbox level — how much filesystem access the agent gets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SandboxLevel {
    /// Agent can only write within the workspace/worktree.
    WorkspaceWrite,
    /// Agent has full filesystem access (dangerous).
    FullAccess,
    /// No sandboxing (orch manages isolation externally).
    None,
    /// The OS sandbox from `workflow.sandbox: os` runs the agent, so the agent's own sandbox is off
    Os,
}

impl Default for PermissionRules {
    fn default() -> Self {
        Self {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![
                "Bash(rm *)".to_string(),
                "Bash(rm -*)".to_string(),
                "Bash(git push*)".to_string(),
            ],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        }
    }
}

impl PermissionRules {
    /// Load permission rules from config, falling back to defaults.
    pub fn from_config() -> Self {
        let mut rules = Self::default();

        if let Ok(mode) = config::get("workflow.permissions.mode") {
            rules.autonomous = mode != "supervised";
        }

        if let Ok(sandbox) = config::get("workflow.permissions.sandbox") {
            rules.sandbox = match sandbox.as_str() {
                "full-access" | "danger-full-access" => SandboxLevel::FullAccess,
                "none" => SandboxLevel::None,
                _ => SandboxLevel::WorkspaceWrite,
            };
        }

        if let Ok(tools) = config::get("workflow.disallowed_tools") {
            let parsed: Vec<String> = tools
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            if !parsed.is_empty() {
                rules.disallowed_tools = parsed;
            }
        }

        if let Ok(tools) = config::get_list("workflow.allowed_tools") {
            rules.allowed_tools = tools;
        }

        rules
    }

    /// Restriction preset for control sessions: denies Read, Glob, Grep, and
    /// Bash commands that read files or list directories (ls, cat, find, etc.).
    ///
    /// The agent remains autonomous but is prevented from browsing or reading
    /// arbitrary files on the host machine. Translation into agent-native flags
    /// is handled by each `AgentRunner::build_command()` implementation.
    pub fn deny_read_only() -> Self {
        Self {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![
                "Bash(rm *)".to_string(),
                "Bash(rm -*)".to_string(),
                "Bash(git push*)".to_string(),
                "Bash(ls *)".to_string(),
                "Bash(ls)".to_string(),
                "Bash(find *)".to_string(),
                "Bash(cat *)".to_string(),
                "Bash(head *)".to_string(),
                "Bash(tail *)".to_string(),
                "Bash(fzf *)".to_string(),
                "Bash(less *)".to_string(),
                "Bash(more *)".to_string(),
                "Read".to_string(),
                "Glob".to_string(),
                "Grep".to_string(),
            ],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: true,
            extra_writable_dirs: vec![],
        }
    }
}

/// Structured result from per-agent NDJSON extraction.
///
/// Each agent emits a different NDJSON format. The per-agent `find_result`
/// functions parse agent-specific envelopes and return a unified `AgentResult`
/// so callers (review pipeline, response handler) don't need format knowledge.
#[derive(Debug, Clone)]
pub struct AgentResult {
    /// Whether the agent reported an error (e.g. `is_error: true` in Claude).
    pub is_error: bool,
    /// The extracted result text (inner content, stripped of envelope).
    pub result_text: String,
    /// Input tokens consumed (if reported by the agent).
    pub input_tokens: Option<u64>,
    /// Output tokens consumed (if reported by the agent).
    pub output_tokens: Option<u64>,
    /// Total cost in USD (if reported by the agent).
    pub cost_usd: Option<f64>,
    /// Wall-clock duration in milliseconds (if reported by the agent).
    pub duration_ms: Option<u64>,
    /// True when the provider cut the response short by exceeding its
    /// output/reasoning token budget (e.g. opencode's `step_finish` event
    /// reporting `reason: "length"`), as opposed to producing malformed
    /// output. Callers use this to distinguish a token-budget fluke from a
    /// genuinely format-incapable model.
    pub truncated_by_length: bool,
}

/// Concatenate text from all assistant-turn messages in the agent's NDJSON
/// output stream.  Used as an intermediate fallback when the `type:result`
/// envelope text is not valid AgentResponse JSON but an earlier assistant
/// message in the conversation might contain it.
pub fn collect_assistant_messages_text(_agent: &str, ndjson: &str) -> String {
    claude::collect_assistant_messages_text(ndjson)
}

/// Dispatch to the appropriate per-agent result extractor.
///
/// Returns `None` if no structured result could be found in the output
/// (e.g. plain text, empty output, or unrecognized format).
pub fn find_agent_result(agent: &str, ndjson: &str) -> Option<AgentResult> {
    match agent {
        "grok" => grok::find_grok_result(ndjson),
        "opencode" => opencode::find_opencode_result(ndjson),
        "codex" => codex::find_codex_result(ndjson),
        // claude, kimi, minimax and unknown agents all emit the claude format
        _ => claude::find_claude_result(ndjson),
    }
}

/// Parsed response from an agent, including metadata extracted from the
/// agent-specific output envelope.
#[derive(Debug, Clone)]
pub struct ParsedResponse {
    /// Normalized task response (status, summary, accomplished, etc.)
    pub response: AgentResponse,
    /// Input tokens consumed (if reported by the agent).
    pub input_tokens: Option<u64>,
    /// Output tokens consumed (if reported by the agent).
    pub output_tokens: Option<u64>,
    /// Wall-clock duration in milliseconds (if reported by the agent).
    pub duration_ms: Option<u64>,
}

/// Agent-specific error with enough detail for autonomous recovery.
#[derive(Debug, Clone)]
pub enum AgentError {
    /// Rate/usage limit — reroute to different agent, cooldown current.
    RateLimit { message: String },
    /// Auth/billing/API key error — switch agent entirely.
    Auth { message: String },
    /// Requested model not available — try different model, then switch agent.
    ModelUnavailable { message: String, model: String },
    /// Context window exceeded — truncate and retry, then switch agent.
    ContextOverflow { message: String },
    /// Agent hit the task time limit. Retry without cooling the model
    Timeout { elapsed: Duration },
    /// Process exited with no result envelope, usually a kill rather than a model fault
    Interrupted { message: String },
    /// Required tool/binary missing from the environment.
    MissingTool { tool: String },
    /// Sandbox or filesystem permission denied.
    PermissionDenied { message: String },
    /// Agent is waiting for interactive input (e.g., 1Password, SSH).
    WaitingForInput { message: String },
    /// The agent's session ID is no longer valid (session expired or was cleared).
    ///
    /// Returned when Claude reports "No conversation found with session ID: <uuid>".
    /// The caller should reset the stored UUID and retry with a fresh `--session-id`.
    StaleSession { session_id: String },
    /// Agent returned unparseable output.
    InvalidResponse { raw: String },
    /// Agent self-reported a failure in its response.
    AgentFailed { message: String },
    /// Transient network connectivity error — retry same agent, no failover.
    NetworkError { message: String },
    /// Thinking blocks cannot be modified (Claude extended-thinking + tool-use 400).
    ///
    /// Transient API incompatibility inside the Claude CLI's multi-turn tool-use
    /// loop — the Anthropic API rejects the request when thinking blocks are altered
    /// between turns. Not a model capacity problem: does NOT increment failure counts
    /// or apply cooldowns. The task is rerouted to a different agent.
    ThinkingBlockConflict { message: String },
    /// Unclassified error.
    Unknown { exit_code: i32, message: String },
}

impl Display for AgentError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::RateLimit { message, .. } => write!(f, "rate limit: {message}"),
            Self::Auth { message } => write!(f, "auth error: {message}"),
            Self::ModelUnavailable { message, model } => {
                write!(f, "model unavailable ({model}): {message}")
            }
            Self::ContextOverflow { message, .. } => write!(f, "context overflow: {message}"),
            Self::Timeout { elapsed } => write!(f, "timeout after {}s", elapsed.as_secs()),
            Self::Interrupted { message } => write!(f, "interrupted: {message}"),
            Self::MissingTool { tool } => write!(f, "missing tool: {tool}"),
            Self::PermissionDenied { message } => write!(f, "permission denied: {message}"),
            Self::WaitingForInput { message } => write!(f, "waiting for input: {message}"),
            Self::StaleSession { session_id } => {
                write!(f, "stale session (session expired): {session_id}")
            }
            Self::InvalidResponse { raw } => {
                let end = truncate_at_char_boundary(raw, 200);
                write!(f, "invalid response: {}", &raw[..end])
            }
            Self::AgentFailed { message } => write!(f, "agent failed: {message}"),
            Self::NetworkError { message } => write!(f, "network error: {message}"),
            Self::ThinkingBlockConflict { message } => {
                write!(f, "thinking block conflict: {message}")
            }
            Self::Unknown { exit_code, message } => {
                write!(f, "unknown error (exit {exit_code}): {message}")
            }
        }
    }
}

impl error::Error for AgentError {}

/// Return the variant name of an `AgentError` as a static string,
/// for structured logging and `result.json` output.
pub fn error_class_name(err: &AgentError) -> &'static str {
    match err {
        AgentError::RateLimit { .. } => "RateLimit",
        AgentError::Auth { .. } => "Auth",
        AgentError::ModelUnavailable { .. } => "ModelUnavailable",
        AgentError::ContextOverflow { .. } => "ContextOverflow",
        AgentError::Timeout { .. } => "Timeout",
        AgentError::Interrupted { .. } => "Interrupted",
        AgentError::MissingTool { .. } => "MissingTool",
        AgentError::PermissionDenied { .. } => "PermissionDenied",
        AgentError::WaitingForInput { .. } => "WaitingForInput",
        AgentError::StaleSession { .. } => "StaleSession",
        AgentError::InvalidResponse { .. } => "InvalidResponse",
        AgentError::AgentFailed { .. } => "AgentFailed",
        AgentError::NetworkError { .. } => "NetworkError",
        AgentError::ThinkingBlockConflict { .. } => "ThinkingBlockConflict",
        AgentError::Unknown { .. } => "Unknown",
    }
}

/// Extract file paths from free-form text.
///
/// Matches common source file patterns like `src/foo/bar.rs`, `tests/x.py`,
/// `path/to/file.ts`, etc. Deduplicates and returns them sorted.
fn extract_file_paths(text: &str) -> Vec<String> {
    // Match path-like tokens: optional leading slash or no slash, at least one
    // directory segment or a plain filename, with a recognised extension.
    let extensions = [
        "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "hpp", "rb", "sh",
        "md", "toml", "yaml", "yml", "json", "sql", "html", "css", "swift", "kt",
    ];
    let mut found: BTreeSet<String> = BTreeSet::new();
    for token in text.split_whitespace() {
        // Strip surrounding punctuation (backticks, quotes, parens, commas).
        // We intentionally do NOT strip '.' here because it is part of file extensions.
        let token = token.trim_matches(|c: char| {
            matches!(
                c,
                '`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
            )
        });
        // Strip a lone trailing dot that ends a sentence (e.g. "src/foo.rs.").
        // Only strip if the result still has a recognised extension — this avoids
        // accidentally stripping the final dot of "src/foo.rs" when there is none.
        let token = if let Some(without) = token.strip_suffix('.') {
            let still_has_ext = extensions
                .iter()
                .any(|ext| without.ends_with(&format!(".{ext}")));
            if still_has_ext { without } else { token }
        } else {
            token
        };
        // Must contain at least one slash (directory separator) or look like a
        // root-relative path, and end with a known extension.
        let has_ext = extensions
            .iter()
            .any(|ext| token.ends_with(&format!(".{ext}")));
        if !has_ext {
            continue;
        }
        // Accept tokens with at least one path separator, or starting with a
        // known top-level directory name common in Rust/JS/Python projects.
        let path_like = token.contains('/')
            || token.starts_with("src")
            || token.starts_with("tests")
            || token.starts_with("lib")
            || token.starts_with("bin")
            || token.starts_with("prompts")
            || token.starts_with("migrations");
        if path_like && token.len() >= 4 && !token.contains("://") {
            found.insert(token.to_string());
        }
    }
    found.into_iter().collect()
}

/// Split free-form text into accomplished and remaining bullet lists.
///
/// Lines under "remaining", "todo", "next steps", "still needed" headings are
/// classified as `remaining`; all other bullet lines go into `accomplished`.
fn extract_bullet_sections(text: &str) -> (Vec<String>, Vec<String>) {
    let remaining_headers = [
        "remaining",
        "todo",
        "to do",
        "next steps",
        "still needed",
        "left to do",
        "not done",
        "outstanding",
    ];

    let mut accomplished: Vec<String> = vec![];
    let mut remaining: Vec<String> = vec![];
    let mut in_remaining_section = false;

    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let lower = trimmed.to_lowercase();

        // Detect section headings: only lines with explicit heading markers.
        // Require trailing ':' or '#'-prefix to avoid misclassifying continuation
        // lines (e.g. explanatory text after a bullet) as headings, which would
        // incorrectly reset `in_remaining_section`.
        let is_heading = trimmed.ends_with(':') || trimmed.starts_with('#');

        if is_heading {
            in_remaining_section = remaining_headers.iter().any(|h| lower.contains(h));
            continue;
        }

        // Bullet lines: -, *, or numbered (1., 2.)
        let is_bullet = trimmed.starts_with('-')
            || trimmed.starts_with('*')
            || trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains('.');

        if !is_bullet {
            continue;
        }

        // Strip leading bullet character(s).
        let content = trimmed
            .trim_start_matches(|c: char| c == '-' || c == '*' || c.is_ascii_digit() || c == '.')
            .trim()
            .to_string();

        if content.is_empty() {
            continue;
        }

        if in_remaining_section {
            remaining.push(content);
        } else {
            accomplished.push(content);
        }
    }

    (accomplished, remaining)
}

/// Detect if text is a CLI/arg-parser diagnostic rather than an agent response.
/// CLI diagnostics indicate process startup failure, not an agent answer.
fn is_cli_parser_diagnostic(text: &str) -> bool {
    let lower = text.to_lowercase();

    // Clap-style error messages
    if lower.contains("error: unexpected argument") {
        return true;
    }

    // Usage/help text patterns
    if text.lines().any(|line| {
        let trimmed = line.trim();
        trimmed.starts_with("Usage:") || trimmed.starts_with("usage:")
    }) {
        return true;
    }

    // Clap help/info hints
    if lower.contains("for more information, try '--help'") {
        return true;
    }

    // Clap "tip" messages about passing values
    if lower.contains("tip: to pass '") {
        return true;
    }

    false
}

/// Detect whether `text` looks like an NDJSON event stream emitted by an
/// agent CLI (opencode/claude/codex). Returns true when the first non-empty
/// line parses as a JSON object containing a `type` field with one of the
/// known event-type strings.
///
/// This guard prevents raw NDJSON from being interpreted as agent prose and
/// leaking into notification summaries.
fn looks_like_ndjson_event_stream(text: &str) -> bool {
    let Some(first_line) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
        return false;
    };

    if !first_line.starts_with('{') {
        return false;
    }

    let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) else {
        return false;
    };

    let Some(event_type) = value.get("type").and_then(|v| v.as_str()) else {
        return false;
    };

    matches!(
        event_type,
        "step_start"
            | "step_finish"
            | "tool_use"
            | "tool_result"
            | "assistant"
            | "system"
            | "message"
            | "text"
    )
}

/// Build a synthetic agent response from plain text when structured parsing fails.
///
/// Returns `None` for empty/whitespace-only text so callers can preserve the
/// original `InvalidResponse` behavior.
pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
    // Returns true when `word` appears as a whole word in `text`
    // (not preceded or followed by an ASCII alphanumeric character).
    fn contains_word(text: &str, word: &str) -> bool {
        let mut start = 0;
        while let Some(pos) = text[start..].find(word) {
            let abs = start + pos;
            let before_ok = abs == 0 || !text.as_bytes()[abs - 1].is_ascii_alphanumeric();
            let after_ok = abs + word.len() >= text.len()
                || !text.as_bytes()[abs + word.len()].is_ascii_alphanumeric();
            if before_ok && after_ok {
                return true;
            }
            start = abs + 1;
            if start >= text.len() {
                break;
            }
        }
        false
    }

    let trimmed = text.trim();
    if trimmed.is_empty() {
        return None;
    }

    // Detect CLI/arg-parser diagnostics and reject them. These indicate the agent
    // process failed to start properly (e.g. invalid flag), not that the agent
    // produced a free-form answer. Clap-based CLIs emit patterns like:
    //   "error: unexpected argument '--flag' found"
    //   "Usage: command [OPTIONS]"
    //   "For more information, try '--help'"
    //   "tip: to pass '...' as a value, use '-- ...'"
    if is_cli_parser_diagnostic(trimmed) {
        return None;
    }

    // Detect NDJSON event streams (opencode/claude/codex stdout) and reject
    // them. Raw NDJSON masquerading as prose would otherwise leak into
    // notification summaries — the "completed" substring inside tool state
    // JSON triggers a false "done" classification and the first 500 bytes of
    // NDJSON become the user-visible summary.
    if looks_like_ndjson_event_stream(trimmed) {
        return None;
    }

    let lower = trimmed.to_lowercase();
    // Also accept plain-language confirmations of performed actions (issue/PR
    // creation, comments, etc.) as a successful "done" signal. This prevents
    // tasks from being retried when an agent reports success in free-form
    // text instead of returning structured JSON.

    // Negation phrases that override a "done/completed" match.
    let looks_negative = [
        "not done",
        "not yet done",
        "not complete",
        "not yet complete",
        "not completed",
        "not yet completed",
        "not committed",
        "incomplete",
        "undone",
    ]
    .iter()
    .any(|needle| lower.contains(needle));

    // Strong explicit completion phrases. These are high-confidence indicators
    // that the agent performed an action (filed issues, created commits, etc.).
    let explicit_done = [
        "nothing to",
        "nothing to do",
        "nothing to execute",
        "no positions",
        "no open positions",
        "no trades",
        "no trade",
        "no action needed",
        "no changes to commit",
        "completed",
        // Action/issue completion phrases
        "filed",
        "filed issue",
        "filed issues",
        "created issue",
        "created issues",
        "opened issue",
        "opened issues",
        "issue created",
        "issues created",
        "issues filed",
        "task created",
        "posted comment",
        "comment posted",
        "changes committed",
        "commit created",
        "fixed.",
        "has been fixed",
        "the fix has been applied",
        "the fix has already been applied",
        // Agent completion phrases (regression: #1362/#1363)
        "the fix is complete",
        "fix is working",
        "all tests pass",
        "tests pass.",
    ]
    .iter()
    .any(|needle| lower.contains(needle));

    // Conservative sentence-level heuristics for single-word signals like "done".
    // Accept "done" only when it appears in a short, self-contained sentence
    // without hedging language ("let me", "checking", "will", etc.). This
    // reduces false-positives from exploratory prose that mentions "done"
    // as part of a planning or investigatory sentence.
    let mut done_confident = false;
    for sentence in trimmed
        .split(['.', '!', '?', '\n'])
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        let s_lower = sentence.to_lowercase();
        // short sentence heuristic
        let word_count = sentence.split_whitespace().count();
        let hedging = [
            "let",
            "let me",
            "check",
            "checking",
            "will",
            "i'll",
            "i will",
            "trying",
            "try",
            "investigat",
            "maybe",
            "could",
            "should",
            "might",
            "if ",
            "plan",
            "planning",
        ];
        let contains_hedge = hedging.iter().any(|h| s_lower.contains(h));

        if contains_word(&s_lower, "done") && word_count <= 8 && !contains_hedge {
            done_confident = true;
            break;
        }

        // Commit/concrete action heuristics: require explicit commit language
        // rather than opportunistic mentions. Examples: "I've committed the changes",
        // "changes committed", or "commit created".
        if s_lower.contains("committed") || s_lower.contains("commit created") {
            // Accept only if sentence also suggests the changes were actually written
            if s_lower.contains("changes")
                || s_lower.contains("i've")
                || s_lower.contains("i have")
                || s_lower.contains("the commit")
            {
                done_confident = true;
                break;
            }
        }

        // Past-tense action verb at sentence start indicates a completed action
        // (e.g. "Added detect_rate_limit patterns", "Fixed the nil-pointer bug").
        // Accept only for short sentences without hedging language to avoid matching
        // prose like "I added a note that this might fail later".
        let past_tense_actions = [
            "added ",
            "fixed ",
            "updated ",
            "implemented ",
            "created ",
            "removed ",
            "changed ",
            "deleted ",
            "applied ",
            "resolved ",
            "patched ",
            "refactored ",
            "merged ",
            "pushed ",
            "deployed ",
        ];
        if !contains_hedge
            && word_count <= 12
            && past_tense_actions.iter().any(|v| s_lower.starts_with(v))
        {
            done_confident = true;
            break;
        }
    }

    let looks_done = !looks_negative && (explicit_done || done_confident);

    let looks_error = [
        "error:",
        "failed to",
        "cannot",
        "permission denied",
        "unable to",
    ]
    .iter()
    .any(|needle| lower.contains(needle));

    let status = if looks_error {
        "needs_review"
    } else if looks_done {
        "done"
    } else if looks_negative {
        // Agent explicitly stated the task is not complete — surface for human review.
        "needs_review"
    } else {
        // Text is ambiguous: no error signal, no completion signal, no explicit negation.
        // This happens when agents emit exploratory or startup text (e.g. "Let's go!",
        // "I need to find where...") and exit without producing structured JSON.
        // Returning None causes callers to treat this as an invalid response and reroute
        // the task rather than falsely advancing it to needs_review / in_review.
        return None;
    };

    let summary_end = truncate_at_char_boundary(trimmed, 500);
    let summary = trimmed[..summary_end].to_string();
    let error =
        (status == "needs_review").then(|| "agent returned plain text instead of JSON".to_string());

    // Extract structured fields from free-form text.
    let files = extract_file_paths(trimmed);
    let (accomplished, remaining) = extract_bullet_sections(trimmed);

    Some(AgentResponse {
        status: status.to_string(),
        summary,
        accomplished,
        remaining,
        files,
        error,
        input_tokens: None,
        output_tokens: None,
        learnings: vec![],
        delegations: vec![],
    })
}

/// Quote a string for safe insertion into a POSIX shell command.
pub(crate) fn shell_single_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// Find the largest byte index <= `max_bytes` that lies on a UTF-8 char
/// boundary.  Used for safe string truncation in error messages.
pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
    if max_bytes >= s.len() {
        return s.len();
    }
    // Walk backwards from max_bytes until we hit a char boundary
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    end
}

/// One step of an agent's work, as `orch stream` shows it
#[derive(Debug, Clone, PartialEq)]
pub enum StreamEvent {
    Started {
        model: String,
    },
    Text(String),
    Thinking(String),
    /// `id` links the call to its result, empty when the agent has none
    ToolCall {
        id: String,
        name: String,
        input: serde_json::Value,
    },
    /// `name` is empty when only `id` names the call
    ToolResult {
        id: String,
        name: String,
        output: String,
        is_error: bool,
    },
    Done(String),
    Error(String),
}

/// String at a JSON pointer, empty when missing
pub(crate) fn json_str<'a>(v: &'a serde_json::Value, pointer: &str) -> &'a str {
    v.pointer(pointer)
        .and_then(serde_json::Value::as_str)
        .unwrap_or("")
}

/// Error text from any of the shapes agents use: `message`, `error`, `error.message`, `error.data.message`
pub(crate) fn json_error_message(v: &serde_json::Value) -> String {
    [
        "/message",
        "/error",
        "/error/message",
        "/error/data/message",
    ]
    .iter()
    .find_map(|p| v.pointer(p).and_then(serde_json::Value::as_str))
    .unwrap_or("unknown error")
    .to_string()
}

/// Router stdout shape. Each runner reports its own
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouterTranscript {
    /// Claude Messages NDJSON (`type:result`)
    Messages,
    /// OpenCode NDJSON (`type:text`, `step_*`)
    OpenCode,
    /// Stdout is used as-is
    Raw,
}

/// Per-agent runner trait.
///
/// Each agent implements this to handle its specific CLI invocation,
/// output parsing, and error classification.
pub trait AgentRunner: Send + Sync {
    /// Agent name (e.g., "claude", "codex", "opencode"). Used in tests.
    #[cfg(test)]
    fn name(&self) -> &str;

    /// Build the CLI command string for the legacy tmux runner.
    ///
    /// The returned string is embedded into a shell command that captures
    /// output in the tmux session. The `permissions` struct carries unified
    /// rules that each agent translates to its own CLI flags.
    fn build_command(
        &self,
        model: Option<&str>,
        timeout_cmd: &str,
        sys_file: &str,
        msg_file: &str,
        permissions: &PermissionRules,
    ) -> String;

    /// Parse raw stdout into a ParsedResponse.
    ///
    /// Returns `Ok(ParsedResponse)` on success, `Err(AgentError)` if the
    /// output indicates an error or cannot be parsed.
    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;

    /// Extract the raw inner text from an agent output envelope, without
    /// attempting to parse it as an `AgentResponse`.
    ///
    /// Use this in the review pipeline so that a `ReviewResponse` JSON can be
    /// recovered even when the text doesn't match the task `AgentResponse` schema.
    ///
    /// - For Claude/Kimi/MiniMax: strips the `--output-format stream-json` NDJSON
    ///   wrapper and returns the `"result"` field of the final `"type":"result"` line.
    /// - For Codex: returns the text of the last `agent_message` item.
    /// - For OpenCode: concatenates all `text` events.
    /// - Default: returns `raw` unchanged (safe fallback for unknown agents).
    ///
    /// Returns `Err(AgentError)` only for terminal errors (rate limit, auth, etc.)
    /// that should abort the review pipeline entirely.
    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
        Ok(raw.to_string())
    }

    /// Transcript steps for one parsed line of this agent's NDJSON output
    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;

    /// Classify an error from exit code + stdout + stderr into an AgentError.
    ///
    /// Called when the agent process exits with a non-zero code, or when
    /// parse_response fails to find a valid result.
    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;

    /// Classify error with elapsed session time (for accurate timeout reporting).
    fn classify_error_with_elapsed(
        &self,
        exit_code: i32,
        stdout: &str,
        stderr: &str,
        elapsed_secs: Option<u64>,
    ) -> AgentError {
        let mut err = self.classify_error(exit_code, stdout, stderr);
        if let AgentError::Timeout { elapsed } = &mut err
            && let Some(actual_elapsed) = elapsed_secs
        {
            *elapsed = Duration::from_secs(actual_elapsed);
        }
        err
    }

    /// Models available for this agent (for intra-agent failover).
    fn available_models(&self) -> Vec<String> {
        vec![]
    }

    /// Free/fallback models for last-resort failover.
    fn free_models(&self) -> Vec<String> {
        vec![]
    }

    /// Router stdout shape. The router matches on this instead of agent names
    fn router_transcript(&self) -> RouterTranscript {
        RouterTranscript::Raw
    }

    /// Build a minimal CLI command for LLM-based routing.
    ///
    /// The command should run the agent with `prompt` as the sole task and
    /// return structured (JSON or NDJSON) output on stdout. Used by the router
    /// to classify tasks without launching a full agent session.
    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
}

/// Agents whose CLI takes `--session-id` for a new session and `--resume` to continue it
pub fn supports_session(agent: &str) -> bool {
    matches!(agent, "claude" | "kimi" | "minimax" | "grok")
}

/// Get the appropriate AgentRunner implementation for an agent name.
pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
    // Agents that are known to be claude-compatible (same NDJSON output format)
    const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];

    match agent_name {
        "claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
        "kimi" => Box::new(kimi::KimiClaudeRunner::new()),
        "minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
        "codex" => Box::new(codex::CodexRunner),
        "opencode" => Box::new(opencode::OpenCodeRunner::new()),
        "grok" => Box::new(grok::GrokRunner),
        // Unknown agents fall back to Claude-compatible parsing
        other => {
            // Only warn if the agent is not known to be claude-compatible
            if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
                tracing::warn!(
                    agent = other,
                    "unknown agent, using claude-compatible runner"
                );
            }
            Box::new(claude::ClaudeRunner::new(other))
        }
    }
}

/// Parse an NDJSON stream into a list of JSON values.
///
/// Shared by all agents that emit NDJSON output (Codex, OpenCode, etc.).
/// Lines that are empty or unparseable are silently skipped with a debug log.
///
/// For fragmented streams where complete JSON objects span multiple lines,
/// we also attempt to concatenate non-empty lines and parse them as a stream
/// of JSON objects to handle edge cases where models emit partial NDJSON.
pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
    // Fast path: try parsing each line individually (handles most cases)
    let events: Vec<serde_json::Value> = raw
        .lines()
        .filter(|line| !line.trim().is_empty())
        .filter_map(|line| match serde_json::from_str(line) {
            Ok(val) => Some(val),
            Err(e) => {
                tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
                None
            }
        })
        .collect();

    // If we got events, return them. Otherwise, try the accumulation fallback
    // for edge cases where models emit fragmented JSON (e.g., partial objects
    // that get split across lines, or streams with embedded newlines in strings).
    if !events.is_empty() {
        return events;
    }

    // Fallback: accumulate all non-empty, non-comment lines and try to extract
    // JSON objects by scanning for balanced braces. This handles edge cases like:
    // - Closing fence inside JSON strings: {"text": "```json\n{\"status\": \"done\"}\n```"}
    // - Fragmented NDJSON where incomplete objects span multiple lines
    // - Model outputs with embedded newlines in text fields
    let acc: String = raw
        .lines()
        .filter(|line| {
            let t = line.trim();
            !t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
        })
        .collect::<Vec<_>>()
        .join(" ");

    if acc.is_empty() {
        return Vec::new();
    }

    // Fallback: try to parse the accumulated text directly as a JSON value.
    // This handles multi-line JSON objects that don't fit on single lines.
    if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
        // Check if stripping ALL whitespace makes it a single JSON object with
        // the same content. If so, the input was plain multi-line JSON (not
        // fragmented NDJSON), and we should return empty to preserve original
        // behavior — callers then treat it as plain text.
        let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
        if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
            // Only return empty if the stripped version parses identically,
            // meaning whitespace was insignificant. If they differ, whitespace
            // matters and this is likely fragmented input.
            if stripped_val == val {
                return Vec::new();
            }
        }
        return vec![val];
    }

    // Direct parse failed — try to extract JSON objects by scanning for balanced
    // braces. This handles cases like embedded JSON within text:
    // `{"text": "```json\n{\"status\": \"done\"}\n```"}`
    extract_json_objects(&acc)
}

/// Extract complete JSON objects from a string by scanning for balanced braces.
///
/// This is a fallback for fragmented NDJSON streams where complete objects
/// don't appear on single lines. Returns all parseable objects found.
fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
    let mut results = Vec::new();
    let mut start: Option<usize> = None;
    let mut depth: i32 = 0;
    let mut in_string = false;
    let mut escape = false;

    for (idx, ch) in text.char_indices() {
        if let Some(start_idx) = start {
            if in_string {
                if escape {
                    escape = false;
                } else if ch == '\\' {
                    escape = true;
                } else if ch == '"' {
                    in_string = false;
                }
                continue;
            }

            match ch {
                '"' => in_string = true,
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        let candidate = &text[start_idx..=idx];
                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
                            results.push(val);
                        }
                        start = None;
                    }
                }
                _ => {}
            }
            continue;
        }

        if ch == '{' {
            start = Some(idx);
            depth = 1;
            in_string = false;
            escape = false;
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use tracing::Level;
    use tracing_subscriber::EnvFilter;
    use tracing_subscriber::fmt::writer::MakeWriter;
    use tracing_subscriber::util::SubscriberInitExt;

    use std::io;
    use std::io::Write;
    use std::sync::Arc;
    use std::sync::Mutex;

    use super::*;

    #[test]
    fn get_runner_returns_correct_types() {
        assert_eq!(get_runner("claude").name(), "claude");
        assert_eq!(get_runner("kimi").name(), "kimi");
        assert_eq!(get_runner("minimax").name(), "minimax");
        assert_eq!(get_runner("codex").name(), "codex");
        assert_eq!(get_runner("opencode").name(), "opencode");
        assert_eq!(get_runner("grok").name(), "grok");
        assert_eq!(
            get_runner("claude").router_transcript(),
            RouterTranscript::Messages
        );
        assert_eq!(
            get_runner("kimi").router_transcript(),
            RouterTranscript::Messages
        );
        assert_eq!(
            get_runner("minimax").router_transcript(),
            RouterTranscript::Messages
        );
        assert_eq!(
            get_runner("grok").router_transcript(),
            RouterTranscript::Messages
        );
        assert_eq!(
            get_runner("glm").router_transcript(),
            RouterTranscript::Messages
        );
        assert_eq!(
            get_runner("olm").router_transcript(),
            RouterTranscript::Messages
        );
        assert_eq!(
            get_runner("opencode").router_transcript(),
            RouterTranscript::OpenCode
        );
        assert_eq!(
            get_runner("codex").router_transcript(),
            RouterTranscript::Raw
        );
        assert!(supports_session("grok"));
        assert!(!supports_session("codex"));
        // olm and glm are claude-compatible and should return correct name
        assert_eq!(get_runner("olm").name(), "olm");
        assert_eq!(get_runner("glm").name(), "glm");
        // Unknown falls back to claude-compatible
        assert_eq!(get_runner("unknown-agent").name(), "unknown-agent");
    }

    /// Regression test: known claude-compatible agents (including glm) must not
    /// emit "unknown agent" warnings when get_runner() is called.
    #[test]
    fn get_runner_no_warning_for_claude_compatible_agents() {
        struct CaptureWriter(Arc<Mutex<Vec<u8>>>);
        impl Write for CaptureWriter {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
        impl<'a> MakeWriter<'a> for CaptureWriter {
            type Writer = CaptureWriter;
            fn make_writer(&'a self) -> Self::Writer {
                CaptureWriter(Arc::clone(&self.0))
            }
        }

        let output: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
        let output_clone = Arc::clone(&output);

        tracing_subscriber::fmt()
            .with_env_filter(EnvFilter::from_default_env().add_directive(Level::WARN.into()))
            .with_writer(CaptureWriter(output_clone))
            .with_ansi(false)
            .finish()
            .init();

        for agent in &["claude", "kimi", "minimax", "olm", "glm", "grok"] {
            get_runner(agent);
        }

        let captured = {
            let guard = output.lock().unwrap();
            String::from_utf8_lossy(&guard).to_string()
        };
        assert!(
            !captured.contains("unknown agent"),
            "known claude-compatible agents must not emit 'unknown agent' warnings; got: {captured}"
        );
    }

    #[test]
    fn agent_error_display() {
        let e = AgentError::RateLimit {
            message: "429 Too Many Requests".to_string(),
        };
        assert!(e.to_string().contains("rate limit"));

        let e = AgentError::Timeout {
            elapsed: Duration::from_mins(30),
        };
        assert!(e.to_string().contains("1800"));
    }

    #[test]
    fn pattern_detect_rate_limit() {
        assert!(patterns::detect_rate_limit("Error: rate limit exceeded").is_some());
        assert!(patterns::detect_rate_limit("HTTP 429 Too Many Requests").is_some());
        assert!(patterns::detect_rate_limit("You've hit your usage limit").is_some());
        assert!(
            patterns::detect_rate_limit(
                "You've hit your session limit · resets 10:30am (America/Sao_Paulo)"
            )
            .is_some()
        );
        assert!(patterns::detect_rate_limit(
            "Upstream error from Alibaba: Request rate increased too quickly. \
             To ensure system stability, please adjust your client logic to scale requests more smoothly over time."
        ).is_some());
        assert!(patterns::detect_rate_limit("all good").is_none());
    }

    #[test]
    fn classify_from_text_detects_weekly_limit_as_rate_limit() {
        // Regression test for issue #3283: Claude "weekly limit" errors were
        // classified as `failed` instead of `rate_limit` because "weekly limit"
        // was not in the detect_rate_limit pattern list.
        let system_event = r#"{"type":"system","subtype":"error","error":{"type":"weekly_limit","message":"You've hit your weekly limit · resets Jun 9 at 1am (America/Sao_Paulo)"}}"#;
        let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
            .repeat(200);
        let text = format!("{system_event}\n{work_product}");
        assert!(
            text.len() > 3000,
            "test output must exceed tail window to be meaningful"
        );
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::RateLimit { .. }),
            "weekly limit as early system event must be detected via head scan, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("weekly limit"),
            "error message should reference weekly limit, got: {msg}"
        );
    }

    #[test]
    fn detect_rate_limit_github_copilot_monthly_quota() {
        // Regression test for issue #3302: "You have exceeded your monthly quota"
        // was not matched because detect_rate_limit only checked "quota exceeded"
        // (reversed word order), causing 4 immediate retries with no cooldown.
        let err = patterns::detect_rate_limit("You have exceeded your monthly quota");
        assert!(
            matches!(err, Some(AgentError::RateLimit { .. })),
            "monthly quota exhaustion must be detected as rate limit, got: {err:?}"
        );
    }

    #[test]
    fn detect_rate_limit_nvidia_resourceexhausted() {
        // Regression test for issue #3361: Nvidia "ResourceExhausted: Worker local total
        // request limit reached" was classified as generic `failed` instead of `rate_limit`,
        // bypassing the cooldown path and weakening routing health signals.
        let opencode_error = r#"opencode agent error: agent failed: "Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (42/32)""#;
        let err = patterns::detect_rate_limit(opencode_error);
        assert!(
            matches!(err, Some(AgentError::RateLimit { .. })),
            "Nvidia ResourceExhausted must be detected as rate limit, got: {err:?}"
        );

        // Both sub-patterns must match independently.
        assert!(
            patterns::detect_rate_limit("ResourceExhausted: some capacity error").is_some(),
            "bare ResourceExhausted must match"
        );
        assert!(
            patterns::detect_rate_limit("Worker local total request limit reached (10/8)")
                .is_some(),
            "worker local total request limit reached must match"
        );

        // classify_from_text must also route this to RateLimit (exercises the tail-scan path).
        let err = patterns::classify_from_text(1, opencode_error);
        assert!(
            matches!(err, AgentError::RateLimit { .. }),
            "classify_from_text must produce RateLimit for Nvidia ResourceExhausted, got: {err:?}"
        );
    }

    #[test]
    fn detect_rate_limit_message_contains_context_not_tail() {
        // Simulate a long claude NDJSON output where the rate limit message is in
        // the middle and usage stats JSON is at the tail.
        let padding = "x".repeat(5000);
        let text = format!(
            "{padding}you've reached your usage limit for this billing cycle{padding}\
             {{\"web_fetch_requests\":0,\"service_tier\":\"standard\"}}"
        );
        let err = patterns::detect_rate_limit(&text).expect("should detect");
        let msg = err.to_string();
        assert!(
            msg.contains("usage limit"),
            "message should contain the actual error, got: {msg}"
        );
        assert!(
            !msg.contains("web_fetch_requests"),
            "message should not be the tail JSON, got: {msg}"
        );
    }

    #[test]
    fn pattern_detect_rate_limit_529_not_bare() {
        // Bare "529" in various contexts should NOT trigger rate limit detection.
        // These are false positive cases we want to avoid.
        assert!(
            patterns::detect_rate_limit("error on line 529").is_none(),
            "bare line number 529 should not match"
        );
        assert!(
            patterns::detect_rate_limit("file size 529 bytes").is_none(),
            "bare file size 529 should not match"
        );
        assert!(
            patterns::detect_rate_limit("port :5290 in config").is_none(),
            "port number containing 529 should not match"
        );
        assert!(
            patterns::detect_rate_limit("timeout after 5290ms").is_none(),
            "duration containing 529 should not match"
        );
        // But HTTP 529 status codes SHOULD match.
        assert!(
            patterns::detect_rate_limit("HTTP 529 Service Unavailable").is_some(),
            "HTTP 529 status should match"
        );
        assert!(
            patterns::detect_rate_limit("http 529").is_some(),
            "http 529 should match"
        );
        assert!(
            patterns::detect_rate_limit("529 service unavailable").is_some(),
            "529 service unavailable should match"
        );
        assert!(
            patterns::detect_rate_limit("status: 529").is_some(),
            "status: 529 should match"
        );
    }

    #[test]
    fn pattern_detect_auth() {
        assert!(patterns::detect_auth_error("401 Unauthorized").is_some());
        assert!(patterns::detect_auth_error("HTTP 401").is_some());
        assert!(patterns::detect_auth_error("error: 401").is_some());
        assert!(patterns::detect_auth_error("403 Forbidden").is_some());
        assert!(patterns::detect_auth_error("HTTP 403").is_some());
        assert!(patterns::detect_auth_error("HTTP 407 Authentication Required").is_some());
        assert!(patterns::detect_auth_error("407 Proxy Authentication Required").is_some());
        assert!(patterns::detect_auth_error("invalid api key").is_some());
        assert!(patterns::detect_auth_error("billing expired").is_some());
        assert!(patterns::detect_auth_error("task done").is_none());
        // Bare numbers in JSON must NOT trigger auth classification.
        assert!(patterns::detect_auth_error("duration_api_ms 4010292").is_none());
        assert!(
            patterns::detect_auth_error(
                "API Error: Unable to connect to API (ConnectionRefused) duration_api_ms 4010292"
            )
            .is_none()
        );
        // JSON field with colon: "duration_api_ms": 4010292 — contains ": 401" as substring.
        assert!(patterns::detect_auth_error(r#""duration_api_ms": 4010292"#).is_none());
        assert!(
            patterns::detect_auth_error(
                r#"{"error":"ConnectionRefused","duration_api_ms": 4010292}"#
            )
            .is_none()
        );
        // ": 401" at end-of-string or followed by non-digit must still match.
        assert!(patterns::detect_auth_error("status: 401").is_some());
        assert!(patterns::detect_auth_error("error: 403").is_some());
    }

    #[test]
    fn pattern_detect_auth_insufficient_balance() {
        // Regression test for issue #3642: "insufficient balance" (and by extension
        // "402 Payment Required: insufficient balance") must be detected as an auth
        // error so it routes through the credit exhaustion path, not the generic 5-min
        // backoff. This ensures the #3642 cooldown behavior is properly triggered.
        assert!(
            patterns::detect_auth_error("402 Payment Required: insufficient balance").is_some(),
            "insufficient balance must be detected as auth error"
        );
        assert!(
            patterns::detect_auth_error("insufficient balance").is_some(),
            "bare insufficient balance must be detected as auth error"
        );
        // The stored message should contain the matched pattern.
        let err = patterns::detect_auth_error("402 Payment Required: insufficient balance")
            .expect("should detect auth error");
        let AgentError::Auth { message } = err else {
            panic!("expected Auth, got {err:?}");
        };
        assert!(
            message.to_lowercase().contains("insufficient balance"),
            "stored message should contain the matched pattern, got: {message}"
        );
        // The message should be the line containing the auth error, not the tail.
        assert!(
            message.lines().count() <= 2,
            "message should be the auth line, not the full tail: {}",
            message.len()
        );
    }

    #[test]
    fn auth_error_message_contains_match_not_tail() {
        // Simulate real agent output: auth error appears early, NDJSON session
        // metadata at the end. Stored message must be the error line, not the
        // trailing JSON that agents emit at exit.
        let mut text = "some output\nunauthorized: your api key has expired\nx".repeat(400);
        text.push_str(r#","outputTokens":744,"cacheReadInputTokens":344785,"uuid":"86d13b1f-..."#);
        let err = patterns::detect_auth_error(&text).expect("should detect auth error");
        let AgentError::Auth { message } = err else {
            panic!("expected Auth, got {err:?}");
        };
        assert!(
            message.to_lowercase().contains("unauthorized"),
            "stored message should contain the matched pattern, got: {message}"
        );
        assert!(
            !message.contains("outputTokens"),
            "stored message must not be the trailing NDJSON, got: {message}"
        );
        // The message should be the line containing the auth error, not the tail.
        assert!(
            message.lines().count() <= 2,
            "message should be the auth line, not the full tail: {}",
            message.len()
        );
    }

    #[test]
    fn pattern_detect_network_error() {
        assert!(patterns::detect_network_error("connection refused").is_some());
        assert!(patterns::detect_network_error("ConnectionRefused").is_some());
        assert!(patterns::detect_network_error("Unable to connect to API").is_some());
        assert!(patterns::detect_network_error("ECONNREFUSED").is_some());
        assert!(patterns::detect_network_error("network unreachable").is_some());
        assert!(patterns::detect_network_error("Upstream idle timeout exceeded").is_some());
        assert!(patterns::detect_network_error("upstream idle timeout").is_some());
        assert!(patterns::detect_network_error("Streaming response failed").is_some());
        assert!(patterns::detect_network_error("Upstream request failed").is_some());
        assert!(patterns::detect_network_error("all systems operational").is_none());
    }

    #[test]
    fn network_error_message_contains_match_not_tail() {
        // Simulate real agent output: error appears early, unrelated stats JSON at the end.
        let prefix = "connection refused connecting to api.anthropic.com:443 ";
        let mut suffix = "x".repeat(2000);
        suffix.push_str(r#"":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0}"#);
        let text = format!("{prefix}{suffix}");

        let err = patterns::detect_network_error(&text).expect("should detect network error");
        let AgentError::NetworkError { message } = err else {
            panic!("expected NetworkError, got {err:?}");
        };
        assert!(
            message.to_lowercase().contains("connection refused"),
            "stored message should contain the matched pattern, got: {message}"
        );
        assert!(
            !message.contains("web_fetch_requests"),
            "stored message must not be the unrelated stats tail, got: {message}"
        );
    }

    #[test]
    fn pattern_detect_context_overflow() {
        assert!(patterns::detect_context_overflow("context_length_exceeded").is_some());
        assert!(patterns::detect_context_overflow("too many tokens in prompt").is_some());
        assert!(patterns::detect_context_overflow("success").is_none());
    }

    #[test]
    fn pattern_detect_worktree_missing() {
        assert!(
            patterns::detect_worktree_missing("worktree directory does not exist: /tmp/wt")
                .is_some()
        );
        assert!(patterns::detect_worktree_missing("all good").is_none());
    }

    #[test]
    fn pattern_detect_missing_tool() {
        assert!(patterns::detect_missing_tool("bun: command not found").is_some());
        assert!(patterns::detect_missing_tool("env: anchor: no such file").is_some());
        assert!(patterns::detect_missing_tool("everything works").is_none());
    }

    #[test]
    fn pattern_detect_permission_denied() {
        assert!(patterns::detect_permission_denied("permission denied: /etc/hosts").is_some());
        assert!(patterns::detect_permission_denied("sandbox violation detected").is_some());
        assert!(patterns::detect_permission_denied("disallowed tool: Bash(rm *)").is_some());
        assert!(patterns::detect_permission_denied("task completed").is_none());
    }

    #[test]
    fn pattern_detect_waiting_for_input() {
        assert!(patterns::detect_waiting_for_input("Enter passphrase for key").is_some());
        assert!(patterns::detect_waiting_for_input("1Password CLI required").is_some());
        assert!(
            patterns::detect_waiting_for_input("SSH authentication required for deploy key")
                .is_some()
        );
        assert!(
            patterns::detect_waiting_for_input("HTTP 407 Proxy Authentication Required").is_none()
        );
        assert!(patterns::detect_waiting_for_input("done").is_none());
    }

    #[test]
    fn pattern_detect_stale_session() {
        // Exact error message from Claude
        let err = patterns::detect_stale_session(
            "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c",
        );
        assert!(err.is_some(), "should detect stale session");
        if let Some(AgentError::StaleSession { session_id }) = err {
            assert_eq!(session_id, "2be572c4-57bb-4f86-bc03-b593c329177c");
        }

        // Case-insensitive
        let err = patterns::detect_stale_session("no conversation found with session id: abc-123");
        assert!(err.is_some(), "should detect lowercase variant");

        // Non-matching text
        assert!(patterns::detect_stale_session("all good").is_none());
        assert!(patterns::detect_stale_session("conversation started").is_none());

        // Multi-byte UTF-8 characters before the match must not panic.
        // German ß lowercases to "ss" (1 byte → 2 bytes), so using a byte
        // offset from `lower` directly into `text` would be wrong.
        let multibyte = "Straße: No conversation found with session ID: dead-beef";
        let err = patterns::detect_stale_session(multibyte);
        assert!(
            err.is_some(),
            "should detect stale session after multi-byte chars"
        );
        if let Some(AgentError::StaleSession { session_id }) = err {
            assert_eq!(session_id, "dead-beef");
        }
    }

    #[test]
    fn stale_session_display() {
        let e = AgentError::StaleSession {
            session_id: "abc-123".to_string(),
        };
        assert!(e.to_string().contains("stale session"));
        assert!(e.to_string().contains("abc-123"));
    }

    #[test]
    fn classify_from_text_timeout() {
        let err = patterns::classify_from_text(124, "");
        assert!(matches!(err, AgentError::Timeout { .. }));
    }

    #[test]
    fn classify_from_text_missing_tool_before_rate_limit() {
        // Missing tool takes priority over rate limit patterns
        let err = patterns::classify_from_text(1, "bun: command not found rate limit");
        assert!(matches!(err, AgentError::MissingTool { .. }));
    }

    #[test]
    fn classify_from_text_worktree_missing() {
        let err = patterns::classify_from_text(1, "worktree directory does not exist: /tmp/wt");
        assert!(matches!(err, AgentError::AgentFailed { .. }));
    }

    #[test]
    fn classify_from_text_model_not_found_backtick() {
        // Issue #3604: plain-text "model not found" errors (no structured
        // NDJSON event) must classify as ModelUnavailable, not fall through to
        // Unknown, so the agent-wide cooldown is not bumped for a bad model name.
        let text = "codex failed: model unavailable (gpt-5.5): Reconnecting... 2/5 \
            (unexpected status 404 Not Found: The model `gpt-5.5` does not exist \
            or you do not have access to it.)";
        let err = patterns::classify_from_text(1, text);
        match err {
            AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.5"),
            other => panic!("expected ModelUnavailable, got: {other:?}"),
        }
    }

    #[test]
    fn classify_from_text_model_metadata_not_found() {
        let text = "Model metadata for `gpt-5.4` not found. Defaulting to fallback \
            metadata; this can degrade performance and cause issues.";
        let err = patterns::classify_from_text(1, text);
        match err {
            AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.4"),
            other => panic!("expected ModelUnavailable, got: {other:?}"),
        }
    }

    #[test]
    fn classify_from_text_no_false_positive_from_work_product() {
        // Regression test for issue #1292: agent output containing rate-limit
        // keywords in code/diffs must not be misclassified as a rate limit error.
        let work_product = "Added `is_copilot_model(model) -> bool` helper\n\
             - Added copilot quota patterns to `parse_retry_at`\n\
             fn detect_rate_limit(text: &str) -> Option<AgentError> {\n\
             quota exceeded handling for billing cycle\n"
            .repeat(50); // ~200 lines of work product — well over 3000 chars
        let actual_error = "\nerror: command not found: cargo\n";
        let text = format!("{work_product}{actual_error}");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            !matches!(err, AgentError::RateLimit { .. }),
            "work product keywords must not trigger rate limit, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_still_detects_real_rate_limit_at_tail() {
        // A real rate-limit error printed at the end of the output must still
        // be detected, even if work product precedes it.
        let padding = "normal agent work output ".repeat(100);
        let text = format!("{padding}\nError: rate limit exceeded (429 Too Many Requests)\n");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::RateLimit { .. }),
            "real rate limit at tail must be detected, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_ignores_markdown_rate_limit_table_at_tail() {
        let padding = "normal agent work output ".repeat(250);
        let text = format!(
            "{padding}\n+| agent | model | outcome | count |\n+| codex | gpt-5.4 | failed | 1 |\n+| kimi | opus | rate_limit | 1 |\n"
        );
        let err = patterns::classify_from_text(1, &text);
        assert!(
            !matches!(err, AgentError::RateLimit { .. }),
            "markdown table cell must not trigger rate limit, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_rate_limit_non_ascii_prefix_does_not_panic() {
        // Regression test: non-ASCII characters before `rate_limit` that change
        // byte length when lowercased (e.g. İ 2→3 bytes, fl 3→2 bytes) must not
        // cause is_word_boundary to index text at an invalid byte offset.
        let text = "Aflαβrate_limit error: too many requests";
        let err = patterns::classify_from_text(1, text);
        assert!(
            matches!(err, AgentError::RateLimit { .. }),
            "real rate_limit should still be detected with non-ASCII prefix, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_session_limit_as_early_system_event() {
        // Regression test for issue #3272: Claude session limit errors appear as
        // `type:system` NDJSON events early in the stream, not as `type:result`
        // lines. When the agent produces significant output after the error, the
        // system event is pushed out of the tail window and missed by tail-only
        // scanning. The head scan must catch it.
        let system_event = r#"{"type":"system","subtype":"error","error":{"type":"session_limit","message":"You've hit your session limit · resets 4:10am (America/Sao_Paulo)"}}"#;
        // Generate enough work product (>3000 bytes) to push the system event
        // out of the tail window.
        let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
            .repeat(200);
        let text = format!("{system_event}\n{work_product}");
        // Verify the output is large enough that the event is not in the tail.
        assert!(
            text.len() > 3000,
            "test output must exceed tail window to be meaningful"
        );
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::RateLimit { .. }),
            "session limit as early system event must be detected via head scan, got: {err:?}"
        );
        // The message should contain the actual error, not unrelated tail content.
        let msg = err.to_string();
        assert!(
            msg.contains("session limit"),
            "error message should contain the rate limit reason, got: {msg}"
        );
    }

    #[test]
    fn classify_from_text_no_false_positive_auth_from_work_product() {
        // Regression test for issue #2126: auth keywords in agent work product
        // must not trigger auth classification when the real failure is
        // unrelated and appears at the end of the output.
        let work_product = "if response.status == 401 { return Err(\"unauthorized\") }\n\
             // handle 403 forbidden errors\n\
             // billing checks happen elsewhere\n"
            .repeat(80);
        let actual_error = "\nerror: command not found: cargo\n";
        let text = format!("{work_product}{actual_error}");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            !matches!(err, AgentError::Auth { .. }),
            "work product auth keywords must not trigger auth classification, got: {err:?}"
        );
        assert!(
            matches!(err, AgentError::MissingTool { .. }),
            "the real tail error should still win, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_still_detects_real_auth_at_tail() {
        let padding = "normal agent work output ".repeat(100);
        let text = format!("{padding}\nHTTP 401 Unauthorized\n");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::Auth { .. }),
            "real auth error at tail must be detected, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_no_false_positive_context_overflow_from_work_product() {
        // Regression test for issue #2205: context overflow keywords in agent
        // work product must not trigger ContextOverflow when the real failure is
        // unrelated and appears at the end of the output.
        let work_product = "const MAX_TOKEN_LIMIT = 10000;\n\
             // Ensure we don't exceed the token limit per request\n\
             fn check_token_limit(tokens: usize) { ... }\n\
             if total_tokens > MAX_TOKEN_LIMIT { ... }\n\
             // Note: too many tokens in the prompt causes context_length_exceeded\n"
            .repeat(80);
        let actual_error = "\nerror: command not found: cargo\n";
        let text = format!("{work_product}{actual_error}");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            !matches!(err, AgentError::ContextOverflow { .. }),
            "work product context keywords must not trigger ContextOverflow, got: {err:?}"
        );
        assert!(
            matches!(err, AgentError::MissingTool { .. }),
            "the real tail error should still win, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_still_detects_real_context_overflow_at_tail() {
        let padding = "normal agent work output ".repeat(100);
        let text = format!("{padding}\nError: context_length_exceeded\n");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::ContextOverflow { .. }),
            "real context overflow at tail must be detected, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_no_false_positive_permission_denied_from_work_product() {
        // Regression test for issue #2205: permission-related keywords in agent
        // work product must not trigger PermissionDenied when the real failure
        // is unrelated and appears at the end of the output.
        let work_product = "match fs::metadata(path) {\n\
             Err(ref e) if e.kind() == ErrorKind::PermissionDenied => {\n\
                 bail!(\"access denied: {path}\");\n\
             }\n\
             // Check if directory is writable\n\
             if !path.is_writable() { ... }\n\
             }\n"
        .repeat(80);
        let actual_error = "\nerror: command not found: cargo\n";
        let text = format!("{work_product}{actual_error}");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            !matches!(err, AgentError::PermissionDenied { .. }),
            "work product permission keywords must not trigger PermissionDenied, got: {err:?}"
        );
        assert!(
            matches!(err, AgentError::MissingTool { .. }),
            "the real tail error should still win, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_still_detects_real_permission_denied_at_tail() {
        let padding = "normal agent work output ".repeat(100);
        let text = format!("{padding}\npermission denied: /etc/hosts\n");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::PermissionDenied { .. }),
            "real permission denied at tail must be detected, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_no_false_positive_waiting_for_input_from_work_product() {
        // Regression test for issue #2205: input-request keywords in agent work
        // product must not trigger WaitingForInput when the real failure is
        // unrelated and appears at the end of the output.
        let work_product = "// Handle password prompts gracefully\n\
             if prompt.contains(\"password:\") {\n\
                 log::warn!(\"Password prompt detected — skipping interactive step\");\n\
             }\n\
             // SSH agent will ask for the deploy key passphrase\n\
             fn handle_ssh_passphrase() { ... }\n\
             )\n"
        .repeat(80);
        let actual_error = "\nerror: command not found: cargo\n";
        let text = format!("{work_product}{actual_error}");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            !matches!(err, AgentError::WaitingForInput { .. }),
            "work product input keywords must not trigger WaitingForInput, got: {err:?}"
        );
        assert!(
            matches!(err, AgentError::MissingTool { .. }),
            "the real tail error should still win, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_still_detects_real_waiting_for_input_at_tail() {
        let padding = "normal agent work output ".repeat(100);
        let text = format!("{padding}\nEnter passphrase for key:\n");
        let err = patterns::classify_from_text(1, &text);
        assert!(
            matches!(err, AgentError::WaitingForInput { .. }),
            "real waiting for input at tail must be detected, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_prefers_auth_over_permission_denied() {
        let err = patterns::classify_from_text(1, "HTTP 403 access denied: invalid token");
        assert!(
            matches!(err, AgentError::Auth { .. }),
            "auth errors must outrank permission denied, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_prefers_auth_over_waiting_for_input() {
        let err = patterns::classify_from_text(1, "HTTP 407 Proxy Authentication Required");
        assert!(
            matches!(err, AgentError::Auth { .. }),
            "HTTP auth failures must not be treated as waiting for input, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_stale_session() {
        // Regression test for issue #1800: classify_from_text must call
        // detect_stale_session to catch "No conversation found with session ID"
        // errors. Without this, the error would be misclassified as Unknown and
        // the control.rs recovery code would not trigger.
        let text = "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c";
        let err = patterns::classify_from_text(1, text);
        assert!(
            matches!(err, AgentError::StaleSession { .. }),
            "stale session must be detected via classify_from_text, got: {err:?}"
        );
        // Verify the Display format matches what control.rs expects
        assert!(
            err.to_string().contains("stale session"),
            "error display must contain 'stale session' for recovery code to trigger"
        );
    }

    #[test]
    fn classify_from_text_detects_socket_closed() {
        // Regression test for issue #3045: "socket connection was closed" must be
        // classified as NetworkError, not Unknown.
        let text = "API Error: The socket connection was closed unexpectedly. \
             For more information, pass `verbose: true` in the second argument to fetch()";
        let err = patterns::classify_from_text(1, text);
        assert!(
            matches!(err, AgentError::NetworkError { .. }),
            "socket closed must be NetworkError, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_socket_hang_up() {
        let err = patterns::classify_from_text(1, "Error: socket hang up");
        assert!(
            matches!(err, AgentError::NetworkError { .. }),
            "socket hang up must be NetworkError, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_fetch_failed() {
        let err = patterns::classify_from_text(1, "TypeError: fetch failed");
        assert!(
            matches!(err, AgentError::NetworkError { .. }),
            "fetch failed must be NetworkError, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_econnreset() {
        let err = patterns::classify_from_text(1, "read ECONNRESET");
        assert!(
            matches!(err, AgentError::NetworkError { .. }),
            "ECONNRESET must be NetworkError, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_stalled_mid_stream() {
        // Regression test for issue #3541: kimi's "Response stalled mid-stream" must be
        // classified as NetworkError, not Unknown/AgentFailed.
        let err = patterns::classify_from_text(
            1,
            "API Error: Response stalled mid-stream. The response above may be incomplete.",
        );
        assert!(
            matches!(err, AgentError::NetworkError { .. }),
            "stalled mid-stream must be NetworkError, got: {err:?}"
        );
    }

    #[test]
    fn classify_from_text_detects_connection_closed_mid_response() {
        // Regression test for issue #3541: claude's "Connection closed mid-response" must be
        // classified as NetworkError, not Unknown/AgentFailed.
        let err = patterns::classify_from_text(
            1,
            "API Error: Connection closed mid-response. The response above may be incomplete.",
        );
        assert!(
            matches!(err, AgentError::NetworkError { .. }),
            "connection closed mid-response must be NetworkError, got: {err:?}"
        );
    }

    #[test]
    fn synthesize_response_marks_done_for_plain_text_no_op() {
        let response = synthesize_response_from_text(
            "No open positions, no trade executions, no conditions change. Full cash, holding.",
        )
        .unwrap();

        assert_eq!(response.status, "done");
        assert_eq!(
            response.summary,
            "No open positions, no trade executions, no conditions change. Full cash, holding."
        );
        assert!(response.error.is_none());
    }

    #[test]
    fn synthesize_response_marks_needs_review_for_plain_text_error() {
        let response =
            synthesize_response_from_text("Failed to update branch: permission denied").unwrap();

        assert_eq!(response.status, "needs_review");
        assert_eq!(
            response.error.as_deref(),
            Some("agent returned plain text instead of JSON")
        );
    }

    #[test]
    fn synthesize_response_rejects_empty_text() {
        assert!(synthesize_response_from_text("   \n\t  ").is_none());
    }

    /// Regression: raw NDJSON event streams (opencode/claude/codex stdout)
    /// must be rejected by the synthesizer. Without the guard, the
    /// "completed" substring inside tool state JSON triggers a false "done"
    /// classification and 500 bytes of raw NDJSON leak into the
    /// notification summary.
    #[test]
    fn synthesize_response_rejects_ndjson_event_stream() {
        let ndjson = r#"{"type":"step_start","timestamp":1,"part":{"type":"step-start"}}
{"type":"tool_use","timestamp":2,"name":"bash","input":{"cmd":"echo completed"}}
{"type":"step_finish","timestamp":3,"part":{"type":"step-finish","reason":"stop"}}"#;
        assert!(
            synthesize_response_from_text(ndjson).is_none(),
            "raw NDJSON must not be interpreted as agent prose"
        );

        let single = r#"{"type":"step_finish","reason":"stop","completed":true}"#;
        assert!(
            synthesize_response_from_text(single).is_none(),
            "single-line NDJSON event must also be rejected"
        );
    }

    #[test]
    fn synthesize_response_accepts_json_without_event_type() {
        // A JSON-like blob that does NOT match a known NDJSON event type
        // should still be allowed through to the regular synthesis path
        // (so the guard does not over-reach).
        let text = "The task is complete. Filed issue #1234 successfully.";
        let response = synthesize_response_from_text(text).expect("plain prose should synthesize");
        assert_eq!(response.status, "done");
    }

    // Regression: opencode/nemotron-3-super-free and similar models sometimes exit
    // with code 0 after emitting only exploratory or startup text (e.g. "Let's go!",
    // planning prose) without completing any work.  The synthesis must return None for
    // such ambiguous text so the runner treats the run as an invalid response and
    // reroutes the task instead of falsely advancing it to needs_review / in_review.
    // (Issues #2404, #2653, #2666)
    #[test]
    fn synthesize_response_returns_none_for_ambiguous_startup_text() {
        // Short greeting — not an error, not done, not an explicit negation.
        assert!(
            synthesize_response_from_text("Let's go!").is_none(),
            "startup greeting must not synthesize as needs_review"
        );
        // Exploratory planning prose — agent is thinking out loud, not reporting completion.
        assert!(
            synthesize_response_from_text(
                "I need to find where the stream command is implemented. \
                 Looking at the CLI structure, it seems like the stream functionality \
                 might be in the task module or another file. Let me check the CLI \
                 command structure. First, let me look at the task module since stream \
                 is related to tasks."
            )
            .is_none(),
            "exploratory prose must not synthesize as needs_review"
        );
    }

    #[test]
    fn synthesize_response_does_not_mark_done_for_incomplete() {
        let response = synthesize_response_from_text("The task is incomplete").unwrap();
        assert_eq!(
            response.status, "needs_review",
            "\"incomplete\" should not match \"complete\""
        );
    }

    #[test]
    fn synthesize_response_does_not_mark_done_for_not_done() {
        let response = synthesize_response_from_text("Changes are not done yet").unwrap();
        assert_eq!(
            response.status, "needs_review",
            "\"not done\" should not match bare \"done\""
        );
    }

    #[test]
    fn synthesize_response_does_not_mark_done_for_not_complete() {
        let response = synthesize_response_from_text("Still in progress, not complete").unwrap();
        assert_eq!(
            response.status, "needs_review",
            "\"not complete\" should not match \"complete\""
        );
    }

    #[test]
    fn synthesize_response_does_not_mark_done_for_not_yet_completed() {
        let response = synthesize_response_from_text("The task is not yet completed").unwrap();
        assert_eq!(
            response.status, "needs_review",
            "\"not yet completed\" should not match \"completed\""
        );
    }

    #[test]
    fn synthesize_response_marks_done_for_completed() {
        let response =
            synthesize_response_from_text("Task has been completed successfully").unwrap();
        assert_eq!(response.status, "done");
    }

    #[test]
    fn synthesize_response_marks_done_for_word_boundary_done() {
        let response = synthesize_response_from_text("All changes are done.").unwrap();
        assert_eq!(response.status, "done");
    }

    #[test]
    fn synthesize_response_marks_done_for_issue_creation_text() {
        let response =
            synthesize_response_from_text("Filed 3 high-value GitHub issues: #1037, #1038, #1039")
                .unwrap();

        assert_eq!(response.status, "done");
        assert!(response.error.is_none());
        assert!(
            response
                .summary
                .contains("Filed 3 high-value GitHub issues")
        );
    }

    #[test]
    fn synthesize_response_marks_done_for_committed() {
        let response =
            synthesize_response_from_text("I've committed the changes to the repository").unwrap();
        assert_eq!(response.status, "done");
    }

    #[test]
    fn synthesize_response_rejects_exploratory_prose() {
        // Regression test: ensure exploratory analysis that mentions "let me check"
        // or planning language is NOT synthesized into a "done" completion.
        // With the ambiguous-text fix, this text correctly returns None (treated as
        // an invalid response / reroute signal) rather than synthesizing needs_review.
        // Crucially, it must NOT be marked "done".
        let exploratory = "I explored the codebase and found several .expect()/.unwrap() uses.\n\nLet me check each occurrence directly and run the tests to be sure. I may commit fixes afterwards.";
        match synthesize_response_from_text(exploratory) {
            None => {
                // Ambiguous exploratory prose correctly returns None — not marked done.
            }
            Some(resp) => {
                assert_ne!(
                    resp.status, "done",
                    "Exploratory prose must not be auto-marked done"
                );
            }
        }
    }

    #[test]
    fn synthesize_response_marks_done_for_commit_created() {
        let response = synthesize_response_from_text(
            "Commit created locally. The push is being blocked by permissions.",
        )
        .unwrap();
        assert_eq!(response.status, "done");
    }

    #[test]
    fn synthesize_response_does_not_mark_done_for_not_committed() {
        let response = synthesize_response_from_text("The changes are not committed yet").unwrap();
        assert_eq!(
            response.status, "needs_review",
            "\"not committed\" should not match \"committed\""
        );
    }

    // ── Regression: #1362/#1363 — agent text misclassified as needs_review ──

    #[test]
    fn synthesize_response_marks_done_for_fix_is_complete() {
        // Exact agent output from task 30203 (issue #1363).
        // "The fix is complete" was misclassified as needs_review because
        // the pattern list had "completed" but not "complete".
        let response = synthesize_response_from_text(
            "All 73 cooldown tests pass. The fix is complete.\n\n\
             **Summary of changes:**\n\n\
             1. **`src/store/kv.rs`** — Added `kv_increment()` method that uses a single \
             `INSERT … ON CONFLICT … DO UPDATE … RETURNING` SQL statement.",
        )
        .unwrap();
        assert_eq!(
            response.status, "done",
            "\"The fix is complete\" must be classified as done, not needs_review"
        );
    }

    #[test]
    fn synthesize_response_marks_done_for_tests_pass_fix_working() {
        // Exact agent output from task 30204 (issue #1362).
        // "All tests pass. The fix is clean and working." was misclassified
        // as needs_review because none of the looks_done patterns matched.
        let response = synthesize_response_from_text(
            "All tests pass. The fix is clean and working.\n\n\
             **Summary of changes** to `src/engine/runner/response.rs:37`:\n\n\
             - **Before:** `capped + jitter` → range `[capped, 1.6*capped]`\n\
             - **After:** `capped.saturating_sub(jitter_range) + jitter` → range `[0.7*capped, 1.3*capped]`",
        )
        .unwrap();
        assert_eq!(
            response.status, "done",
            "\"All tests pass. The fix is clean and working.\" must be classified as done"
        );
    }

    // ── parse_ndjson edge cases ───────────────────────────────────

    #[test]
    fn parse_ndjson_handles_standard_lines() {
        let raw = r#"{"type":"text","text":"hello"}
{"type":"text","text":"world"}"#;
        let events = parse_ndjson(raw);
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].get("type").unwrap().as_str(), Some("text"));
        assert_eq!(events[1].get("type").unwrap().as_str(), Some("text"));
    }

    #[test]
    fn parse_ndjson_skips_empty_lines() {
        let raw = r#"{"type":"text"}

{"type":"text"}
"#;
        let events = parse_ndjson(raw);
        assert_eq!(events.len(), 2);
    }

    #[test]
    fn parse_ndjson_skips_malformed_lines() {
        let raw = r#"{"type":"valid"}
not json at all
{"type":"also_valid"}"#;
        let events = parse_ndjson(raw);
        assert_eq!(events.len(), 2);
    }

    #[test]
    fn parse_ndjson_fallback_extracts_embedded_json() {
        // Edge case: JSON with closing fence inside string field
        let raw =
            r#"text: {"text": "here is the result: ```json\n{\"status\":\"done\"}\n```"} more"#;
        let events = parse_ndjson(raw);
        // Should have extracted the embedded JSON object
        assert!(
            !events.is_empty(),
            "should extract JSON objects via fallback"
        );
    }

    #[test]
    fn parse_ndjson_fallback_handles_fragmented_objects() {
        // Edge case: JSON object spread across multiple lines (fragmented NDJSON)
        let raw = r#"{"type": "text
", "content": "hello
world"}"#;
        let events = parse_ndjson(raw);
        // Should still extract the JSON via fallback
        assert!(!events.is_empty(), "should handle fragmented JSON");
    }

    // ── PermissionRules defaults ────────────────────────────────

    #[test]
    fn permission_rules_default_is_autonomous() {
        let rules = PermissionRules::default();
        assert!(rules.autonomous);
    }

    #[test]
    fn permission_rules_default_sandbox_is_workspace_write() {
        let rules = PermissionRules::default();
        assert_eq!(rules.sandbox, SandboxLevel::WorkspaceWrite);
    }

    #[test]
    fn permission_rules_default_disallows_rm() {
        let rules = PermissionRules::default();
        assert!(rules.disallowed_tools.contains(&"Bash(rm *)".to_string()));
        assert!(rules.disallowed_tools.contains(&"Bash(rm -*)".to_string()));
    }

    #[test]
    fn permission_rules_default_no_allowed_edit_paths() {
        let rules = PermissionRules::default();
        assert!(
            rules.allowed_edit_paths.is_empty(),
            "{:?}",
            rules.allowed_edit_paths
        );
    }

    // ── Permission translation across all agents ────────────────

    /// Test that all agents handle the default permission rules consistently.
    #[test]
    fn all_agents_handle_default_permissions() {
        let perms = PermissionRules::default();
        let sys = "/tmp/sys.md";
        let msg = "/tmp/msg.md";

        // Claude: should have bypassPermissions and rm disallowed
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", sys, msg, &perms);
        assert!(
            cmd.contains("--permission-mode bypassPermissions"),
            "claude default: expected bypassPermissions, got: {cmd}"
        );
        assert!(
            cmd.contains("Bash(rm *)"),
            "claude default: expected rm disallowed, got: {cmd}"
        );

        // Codex: autonomous + workspace-write → --sandbox workspace-write -c 'approval_policy="never"'
        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", sys, msg, &perms);
        assert!(
            cmd.contains("--sandbox workspace-write"),
            "codex default: expected --sandbox workspace-write, got: {cmd}"
        );
        assert!(
            cmd.contains(r#"-c 'approval_policy="never"'"#),
            "codex default: expected -c approval_policy=never, got: {cmd}"
        );
        assert!(
            !cmd.contains("--ask-for-approval"),
            "codex default: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
        );
        assert!(
            !cmd.contains("--full-auto"),
            "codex default: --full-auto is deprecated and must not appear, got: {cmd}"
        );

        // OpenCode: autonomous dispatch passes --dangerously-skip-permissions
        // and writes no config file (relies on opencode's built-in flag).
        let opencode = get_runner("opencode");
        let cmd = opencode.build_command(None, "", sys, msg, &perms);
        assert!(
            cmd.contains("--dangerously-skip-permissions"),
            "opencode default: should pass --dangerously-skip-permissions, got: {cmd}"
        );
        assert!(
            !cmd.contains("opencode.json"),
            "opencode default: should not write a config file, got: {cmd}"
        );
        assert!(
            !cmd.contains("XDG_CONFIG_HOME"),
            "opencode default: should not override XDG_CONFIG_HOME, got: {cmd}"
        );
        assert!(
            !cmd.contains(".orch-opencode"),
            "opencode default: should not reference .orch-opencode, got: {cmd}"
        );
    }

    /// Test supervised mode translates correctly for each agent.
    #[test]
    fn all_agents_handle_supervised_mode() {
        let perms = PermissionRules {
            autonomous: false,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let sys = "/tmp/sys.md";
        let msg = "/tmp/msg.md";

        // Claude: supervised → acceptEdits
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", sys, msg, &perms);
        assert!(
            cmd.contains("--permission-mode acceptEdits"),
            "claude supervised: expected acceptEdits, got: {cmd}"
        );

        // Codex: supervised → on-request
        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", sys, msg, &perms);
        assert!(
            cmd.contains(r#"-c 'approval_policy="on-request"'"#),
            "codex supervised: expected -c approval_policy=on-request, got: {cmd}"
        );
        assert!(
            !cmd.contains("--ask-for-approval"),
            "codex supervised: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
        );
    }

    /// Test full access sandbox translates correctly for each agent.
    #[test]
    fn all_agents_handle_full_access_sandbox() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::FullAccess,
            disallowed_tools: vec![],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let sys = "/tmp/sys.md";
        let msg = "/tmp/msg.md";

        // Claude: ignores sandbox level (no --sandbox flag)
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", sys, msg, &perms);
        assert!(
            !cmd.contains("--sandbox"),
            "claude full_access: should have no sandbox flag, got: {cmd}"
        );

        // Codex: full access → --dangerously-bypass-approvals-and-sandbox
        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", sys, msg, &perms);
        assert!(
            cmd.contains("--dangerously-bypass-approvals-and-sandbox"),
            "codex full_access: expected dangerously-bypass, got: {cmd}"
        );
    }

    /// SandboxLevel::None with autonomous uses --sandbox workspace-write (same as WorkspaceWrite).
    #[test]
    fn codex_sandbox_none_uses_workspace_write() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::None,
            disallowed_tools: vec![],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            cmd.contains("--sandbox workspace-write"),
            "codex sandbox::none + autonomous: should use --sandbox workspace-write, got: {cmd}"
        );
        assert!(
            cmd.contains(r#"-c 'approval_policy="never"'"#),
            "codex sandbox::none + autonomous: should use -c approval_policy=never, got: {cmd}"
        );
        assert!(
            !cmd.contains("--ask-for-approval"),
            "codex sandbox::none: --ask-for-approval was removed in 0.133.0, got: {cmd}"
        );
        assert!(
            !cmd.contains("--full-auto"),
            "codex sandbox::none: --full-auto is deprecated and must not appear, got: {cmd}"
        );
    }

    /// Test that allowed_edit_paths scopes Edit/Write when used with allowed_tools.
    #[test]
    fn claude_allowed_edit_paths_scope_edit_write() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec![
                "Edit".to_string(),
                "Write".to_string(),
                "Read".to_string(),
                "Bash".to_string(),
            ],
            allowed_edit_paths: vec![PathBuf::from("/home/user/worktree")],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);

        // Edit/Write should be scoped to worktree path
        assert!(
            cmd.contains("Edit(/home/user/worktree/*)"),
            "missing scoped Edit, got: {cmd}"
        );
        assert!(
            cmd.contains("Write(/home/user/worktree/*)"),
            "missing scoped Write, got: {cmd}"
        );
        // Read should be unrestricted
        assert!(cmd.contains("Read"), "missing Read");
    }

    /// Test that blocked paths don't affect Codex (it uses sandbox isolation).
    #[test]
    fn codex_ignores_allowed_edit_paths() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec![],
            allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            !cmd.contains("/home/user/project"),
            "codex: should not reference blocked paths, got: {cmd}"
        );
    }

    /// Test that blocked paths don't affect OpenCode.
    #[test]
    fn opencode_ignores_allowed_edit_paths() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec![],
            allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let opencode = get_runner("opencode");
        let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            !cmd.contains("/home/user/project"),
            "opencode: should not reference blocked paths, got: {cmd}"
        );
    }

    /// Test that disallowed tools merge correctly for Claude (defaults + custom).
    #[test]
    fn claude_merges_disallowed_tools() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![
                "Bash(rm *)".to_string(),
                "Bash(sudo *)".to_string(),
                "WebFetch".to_string(),
            ],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(cmd.contains("Bash(rm *)"), "missing rm disallow");
        assert!(cmd.contains("Bash(sudo *)"), "missing sudo disallow");
        assert!(cmd.contains("WebFetch"), "missing WebFetch disallow");
    }

    /// Test that Codex ignores disallowed tools (has no such flag).
    #[test]
    fn codex_ignores_disallowed_tools() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec!["Bash(rm *)".to_string(), "WebFetch".to_string()],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            !cmd.contains("disallow"),
            "codex: should not have disallow flags, got: {cmd}"
        );
    }

    /// Test Claude with empty disallowed tools produces no --disallowedTools flag.
    #[test]
    fn claude_no_disallowed_flag_when_empty() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            !cmd.contains("--disallowedTools"),
            "claude: should have no disallowed flag when empty, got: {cmd}"
        );
    }

    /// Test Kimi/MiniMax aliases inherit Claude permission translation.
    #[test]
    fn kimi_minimax_use_claude_permissions() {
        let perms = PermissionRules {
            autonomous: false,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec!["Bash(rm *)".to_string()],
            allowed_tools: vec![],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };
        let sys = "/tmp/sys.md";
        let msg = "/tmp/msg.md";

        for agent in &["kimi", "minimax"] {
            let runner = get_runner(agent);
            let cmd = runner.build_command(None, "", sys, msg, &perms);
            assert!(
                cmd.contains("--permission-mode acceptEdits"),
                "{agent}: expected acceptEdits"
            );
            assert!(
                cmd.contains("Bash(rm *)"),
                "{agent}: expected rm disallowed"
            );
        }
    }

    /// Test kimi/minimax get --allowedTools when allowed_tools is set.
    #[test]
    fn kimi_minimax_use_allowed_tools() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec!["Edit".to_string(), "Bash".to_string(), "git".to_string()],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };

        for agent in &["kimi", "minimax"] {
            let runner = get_runner(agent);
            let cmd = runner.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
            assert!(
                cmd.contains("--allowedTools"),
                "{agent}: expected --allowedTools, got: {cmd}"
            );
            assert!(
                cmd.contains("Bash(git *)"),
                "{agent}: expected Bash(git *) pattern, got: {cmd}"
            );
        }
    }

    // ── Allowed tools across agents ─────────────────────────────

    /// Test that allowed_tools generates --allowedTools for Claude.
    #[test]
    fn claude_allowed_tools_generates_allowedtools_flag() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec!["Bash(rm *)".to_string()],
            allowed_tools: vec![
                "Edit".to_string(),
                "Write".to_string(),
                "Read".to_string(),
                "Bash".to_string(),
                "git".to_string(),
            ],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };

        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            cmd.contains("--allowedTools"),
            "expected --allowedTools, got: {cmd}"
        );
        assert!(
            !cmd.contains("--disallowedTools"),
            "should not have --disallowedTools when allowed_tools is set"
        );
    }

    /// Test that codex/opencode ignore allowed_tools (no equivalent flag).
    #[test]
    fn codex_opencode_ignore_allowed_tools() {
        let perms = PermissionRules {
            autonomous: true,
            sandbox: SandboxLevel::WorkspaceWrite,
            disallowed_tools: vec![],
            allowed_tools: vec!["Edit".to_string(), "git".to_string()],
            allowed_edit_paths: vec![],
            deny_read_only: false,
            extra_writable_dirs: vec![],
        };

        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            !cmd.contains("--allowedTools"),
            "codex should not have --allowedTools, got: {cmd}"
        );

        let opencode = get_runner("opencode");
        let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
        assert!(
            !cmd.contains("--allowedTools"),
            "opencode should not have --allowedTools, got: {cmd}"
        );
    }

    // ── Integration: from_config() → agent translation ──────────

    /// Integration test: verify from_config() loads real config and agents
    /// translate it correctly. Requires ~/.orch/config.yml to exist.
    #[test]
    #[ignore = "reads the operator config"]
    fn integration_from_config_to_agent_commands() {
        let perms = PermissionRules::from_config();

        // Verify defaults are reasonable
        assert!(
            perms.autonomous,
            "from_config: expected autonomous=true by default"
        );

        // Verify each agent can build a command from the config-loaded rules
        for agent_name in &["claude", "codex", "opencode", "kimi", "minimax"] {
            let runner = get_runner(agent_name);
            let cmd =
                runner.build_command(None, "timeout 1800", "/tmp/sys.md", "/tmp/msg.md", &perms);
            assert!(
                !cmd.is_empty(),
                "{agent_name}: build_command returned empty string"
            );
            assert!(
                cmd.contains(agent_name) || *agent_name == "kimi" || *agent_name == "minimax",
                "{agent_name}: command should reference agent binary, got: {cmd}"
            );
        }
    }

    /// Integration test: verify from_config() handles supervised mode.
    /// Requires config with workflow.permissions.mode = "supervised".
    #[test]
    #[ignore = "reads the operator config"]
    fn integration_supervised_config_translates_correctly() {
        // This test requires config to have:
        // workflow:
        //   permissions:
        //     mode: supervised
        let perms = PermissionRules::from_config();

        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);

        if perms.autonomous {
            assert!(
                cmd.contains("bypassPermissions"),
                "autonomous config → bypassPermissions"
            );
        } else {
            assert!(
                cmd.contains("acceptEdits"),
                "supervised config → acceptEdits"
            );
        }

        let codex = get_runner("codex");
        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);

        if perms.autonomous {
            // autonomous codex uses --sandbox workspace-write -c 'approval_policy="never"'
            assert!(
                cmd.contains("--sandbox workspace-write"),
                "autonomous config → --sandbox workspace-write, got: {cmd}"
            );
            assert!(
                cmd.contains(r#"-c 'approval_policy="never"'"#),
                "autonomous config → -c approval_policy=never, got: {cmd}"
            );
        } else {
            assert!(
                cmd.contains(r#"-c 'approval_policy="on-request"'"#),
                "supervised config → -c approval_policy=on-request, got: {cmd}"
            );
        }
        assert!(
            !cmd.contains("--ask-for-approval"),
            "--ask-for-approval was removed in codex 0.133.0 and must not appear, got: {cmd}"
        );
    }

    // ── deny_read_only preset ───────────────────────────────────

    /// Test that deny_read_only() sets the right disallowed tools for control sessions.
    #[test]
    fn deny_read_only_blocks_reading_tools() {
        let perms = PermissionRules::deny_read_only();

        let read_tools = [
            "Bash(ls *)",
            "Bash(ls)",
            "Bash(find *)",
            "Bash(cat *)",
            "Bash(head *)",
            "Bash(tail *)",
            "Bash(fzf *)",
            "Bash(less *)",
            "Bash(more *)",
            "Read",
            "Glob",
            "Grep",
        ];

        for tool in read_tools {
            assert!(
                perms.disallowed_tools.contains(&tool.to_string()),
                "deny_read_only should block {tool}, got: {:?}",
                perms.disallowed_tools
            );
        }
    }

    /// Test that deny_read_only() produces correct Claude command for control session.
    #[test]
    fn deny_read_only_claude_command() {
        let perms = PermissionRules::deny_read_only();
        let claude = get_runner("claude");
        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);

        // Should contain Read, Glob, Grep disallow patterns
        assert!(
            cmd.contains("Read"),
            "should block Read for control session"
        );
        assert!(
            cmd.contains("Glob"),
            "should block Glob for control session"
        );
        assert!(
            cmd.contains("Grep"),
            "should block Grep for control session"
        );
        // Should block ls
        assert!(
            cmd.contains("Bash(ls") || cmd.contains("Bash(ls *)"),
            "should block ls"
        );
        // Should still have bypassPermissions (autonomous)
        assert!(
            cmd.contains("--permission-mode bypassPermissions"),
            "should be autonomous (bypassPermissions)"
        );
    }

    // --- synthesize_response_from_text structured extraction ---

    #[test]
    fn synthesize_extracts_file_paths() {
        let text = "Fixed the issue by modifying src/engine/runner/agents/mod.rs and tests/integration.rs.";
        let resp = synthesize_response_from_text(text).unwrap();
        assert!(
            resp.files
                .contains(&"src/engine/runner/agents/mod.rs".to_string()),
            "expected src/engine/runner/agents/mod.rs in files, got: {:?}",
            resp.files
        );
        assert!(
            resp.files.contains(&"tests/integration.rs".to_string()),
            "expected tests/integration.rs in files, got: {:?}",
            resp.files
        );
    }

    #[test]
    fn synthesize_extracts_accomplished_bullets() {
        let text = "All tests pass.\n- Added logging to src/foo.rs\n- Updated migration file";
        let resp = synthesize_response_from_text(text).unwrap();
        assert_eq!(resp.status, "done");
        assert!(
            resp.accomplished
                .iter()
                .any(|a| a.contains("Added logging")),
            "expected accomplished bullet, got: {:?}",
            resp.accomplished
        );
        assert!(
            resp.accomplished
                .iter()
                .any(|a| a.contains("Updated migration")),
            "expected accomplished bullet, got: {:?}",
            resp.accomplished
        );
    }

    #[test]
    fn synthesize_extracts_remaining_section() {
        let text = "Completed the main fix.\n- Patched src/lib.rs\n\nRemaining:\n- Write unit tests\n- Update docs";
        let resp = synthesize_response_from_text(text).unwrap();
        assert!(
            resp.remaining
                .iter()
                .any(|r| r.contains("Write unit tests")),
            "expected remaining item, got: {:?}",
            resp.remaining
        );
        assert!(
            resp.remaining.iter().any(|r| r.contains("Update docs")),
            "expected remaining item, got: {:?}",
            resp.remaining
        );
        assert!(
            resp.accomplished.iter().any(|a| a.contains("Patched")),
            "expected accomplished item, got: {:?}",
            resp.accomplished
        );
    }

    #[test]
    fn synthesize_fixed_phrase_is_done() {
        let text = "Fixed. The bug no longer reproduces.";
        let resp = synthesize_response_from_text(text).unwrap();
        assert_eq!(resp.status, "done", "expected done for 'Fixed.' text");
    }

    // ── detect_rate_limit false-positive guard ────────────────────────────
    // Regression: NDJSON telemetry blobs can contain "429" as a token count
    // (e.g. "outputTokens":429). `detect_rate_limit` should still flag those
    // because it cannot distinguish context without the terminal_reason guard.
    // The guard lives in review.rs, but here we verify the raw detector
    // behaviour so callers know they must apply the guard themselves.
    #[test]
    fn detect_rate_limit_fires_on_bare_429_in_token_count() {
        // This SHOULD return Some — the generic detector has no context.
        // The caller (review.rs) is responsible for suppressing it when
        // terminal_reason:completed is present.
        let payload = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
        assert!(
            patterns::detect_rate_limit(payload).is_some(),
            "detect_rate_limit must still fire on bare 429 so callers apply the guard"
        );
    }

    #[test]
    fn detect_rate_limit_ignores_429_inside_longer_number() {
        let uuid = r#"{"type":"hook","uuid":"a1b2c3d4-4295-4e5f-8a9b-0c1d2e3f4a5b"}"#;
        assert!(
            patterns::detect_rate_limit(uuid).is_none(),
            "429 inside a UUID digit run must not match"
        );
    }

    #[test]
    fn detect_rate_limit_ignores_429_in_uuid_hex_group() {
        let hook = r#"{"type":"system","subtype":"hook_response","hook_id":"18db61b6-7b72-429c-8279-fae3089bf565"}"#;
        assert!(patterns::detect_rate_limit(hook).is_none());
    }

    #[test]
    fn detect_rate_limit_429_message_comes_from_matched_line() {
        let filler = "unrelated agent prose that is long enough to fill the window. ".repeat(20);
        let text = format!("HTTP 429 Too Many Requests\n{filler}");
        match patterns::detect_rate_limit(&text) {
            Some(AgentError::RateLimit { message }) => assert!(message.contains("429")),
            other => panic!("expected RateLimit, got {other:?}"),
        }
    }

    // Verify the guard logic that review.rs uses: when raw NDJSON has
    // terminal_reason:completed without is_error:true, the result of
    // detect_rate_limit should be suppressed.
    #[test]
    fn terminal_reason_completed_guard_suppresses_false_rate_limit() {
        let raw_output = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
        let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
            && !raw_output.contains("\"is_error\":true");
        // Apply the same guard that review.rs now uses.
        let detected = (!ndjson_completed)
            .then(|| patterns::detect_rate_limit(raw_output))
            .flatten();
        assert!(
            detected.is_none(),
            "guard must suppress rate-limit false positive from token-count 429 when terminal_reason:completed"
        );
    }

    // Verify the guard does NOT suppress a real rate-limit error.
    #[test]
    fn terminal_reason_completed_guard_passes_real_rate_limit() {
        // Real rate-limit output has no terminal_reason:completed.
        let raw_output = "Error: 429 Too Many Requests — you have exceeded your quota";
        let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
            && !raw_output.contains("\"is_error\":true");
        let detected = (!ndjson_completed)
            .then(|| patterns::detect_rate_limit(raw_output))
            .flatten();
        assert!(
            detected.is_some(),
            "guard must NOT suppress a real rate-limit error"
        );
    }

    #[test]
    fn synthesize_no_false_positive_file_paths() {
        // URLs and version strings should not appear in files list.
        // The text is ambiguous (no error, no done signal, no explicit negation) so
        // synthesize_response_from_text returns None — no file extraction happens.
        let text = "See https://example.com/foo.rs for details. Version 1.2.3 is fine.";
        match synthesize_response_from_text(text) {
            None => {} // Ambiguous text correctly returns None — no files extracted.
            Some(resp) => {
                assert!(
                    resp.files.is_empty(),
                    "expected no file paths extracted from URL text, got: {:?}",
                    resp.files
                );
            }
        }
    }

    // Regression: issue #3197 — CLI arg-parser diagnostics were being synthesized as
    // agent responses. When a process (e.g. codex) fails with an invalid CLI flag, it
    // exits non-zero with a clap/help diagnostic on stderr. This should be rejected
    // (return None) rather than synthesized as a "needs_review" response.
    #[test]
    fn synthesize_rejects_cli_parser_diagnostics_unexpected_argument() {
        // Real clap error from the bug report (codex exit 141)
        let text = "error: unexpected argument '--ask-for-approval' found\n  \
                    tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
                    Usage: codex exec [OPTIONS] [PROMPT]";
        assert!(
            synthesize_response_from_text(text).is_none(),
            "CLI parser diagnostic must not synthesize as agent response"
        );
    }

    #[test]
    fn synthesize_rejects_cli_parser_diagnostics_usage_line() {
        let text = "Usage: mycommand [OPTIONS] <arg>";
        assert!(
            synthesize_response_from_text(text).is_none(),
            "Usage line must not synthesize as agent response"
        );
    }

    #[test]
    fn synthesize_rejects_cli_parser_diagnostics_help_hint() {
        let text = "Error: unknown flag --foo\nFor more information, try '--help'";
        assert!(
            synthesize_response_from_text(text).is_none(),
            "Help hint must not synthesize as agent response"
        );
    }

    #[test]
    fn synthesize_rejects_cli_parser_diagnostics_tip() {
        let text = "error: bad value\ntip: to pass '--flag' as a value, use '-- --flag'";
        assert!(
            synthesize_response_from_text(text).is_none(),
            "Clap tip must not synthesize as agent response"
        );
    }

    #[test]
    fn synthesize_accepts_agent_error_messages_that_mention_error() {
        // Agent returning plain text that happens to contain "error:" but is an actual
        // agent message (e.g. summarizing what went wrong) should still synthesize.
        let text = "I tried to run the command but got an error: permission denied on that file.";
        let response =
            synthesize_response_from_text(text).expect("agent error message should synthesize");
        assert_eq!(response.status, "needs_review");
        assert!(response.error.is_some());
    }

    // Regression: Issue #3197 — exact clap error from bug report.
    // When codex fails with an invalid CLI flag (e.g., --ask-for-approval with old codex versions),
    // it should return None, not synthesize as "needs_review". Without this fix, the run
    // would be marked as success and advance to in_review, wasting resources.
    #[test]
    fn synthesize_rejects_exact_codex_cli_error() {
        let stderr_from_codex = "error: unexpected argument '--ask-for-approval' found\n  \
                                 tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
                                 Usage: codex exec [OPTIONS] [PROMPT]";
        assert!(
            synthesize_response_from_text(stderr_from_codex).is_none(),
            "exact codex CLI error from #3197 must not synthesize as agent response"
        );
    }
}