cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
//! Shared acceptance operations for CLI and TUI modes.
//!
//! Provides acceptance test execution after apply and before archive.

#![allow(dead_code)]

/// Whether a declared repository-local verification still has evidence that
/// belongs to this exact tree, or has to be run again.
pub mod verification_evidence;

/// The runtime-owned manifest that closes the Acceptance blocking command set
/// and gives one invocation's input a stable identity.
pub mod execution_manifest;

/// Runtime-owned execution of the manifest's declared gates, before the
/// semantic reviewer starts and inside the same shared budget.
pub mod gate_execution;

/// Deriving the execution manifest from workspace evidence alone.
pub mod manifest_builder;

/// Where Acceptance evidence lives: one Conflux-owned external store per change,
/// resolved and proven before any declared gate runs, and never inside a target.
pub mod evidence_location;

use crate::agent::AgentRunner;
use crate::error::{OrchestratorError, Result};
use crate::history::{AcceptanceAttempt, OutputCollector};
use crate::openspec::Change;
use tracing::{info, warn};

use super::output::OutputHandler;

const ACCEPTANCE_OUTPUT_FALLBACK: &str = "No acceptance output captured";
pub const MAX_ACCEPTANCE_RETRY_CYCLES: u32 = 10;

/// First history/finding line recorded when an acceptance command completes
/// without emitting any canonical verdict. Deliberately distinct from the
/// explicit-CONTINUE marker ("Investigation incomplete - continue later") so
/// missing-verdict attempts never count toward the consecutive-CONTINUE retry
/// budget.
pub const MISSING_VERDICT_DIAGNOSTIC: &str = "Missing acceptance verdict: acceptance command \
     exited without emitting a canonical verdict (protocol failure; status-only or waiting \
     output is not a verdict)";

/// Maximum number of acceptance protocol retries permitted after the initial
/// protocol-failing attempt. The initial invocation plus these retries gives
/// three opportunities to satisfy the verdict protocol.
///
/// This budget is deliberately separate from the configured explicit-`CONTINUE`
/// budget (`acceptance_max_continues`): a completed-but-verdictless command, or
/// a compatibility `gated` token with no validated blocker payload, is a
/// protocol failure rather than an intentional continuation request.
pub const MAX_MISSING_VERDICT_RETRIES: u32 = 2;

/// Alias documenting that bare-blocker input reuses the same fixed bound.
pub const MAX_ACCEPTANCE_PROTOCOL_RETRIES: u32 = MAX_MISSING_VERDICT_RETRIES;

/// First history/finding line recorded when acceptance emits a `gated` (or
/// legacy `blocked`) compatibility token without a validated structured blocker.
pub const BARE_BLOCKER_DIAGNOSTIC: &str = "Bare acceptance blocker: acceptance emitted a gated \
     compatibility token without a validated structured blocker payload (protocol failure; a \
     stalled hold requires an explicit supported category, concrete evidence, next action, and \
     resumability)";

/// Which acceptance protocol contract the command failed to satisfy.
///
/// Both kinds share the same fixed retry bound and both re-invoke acceptance
/// only — neither reruns apply, consumes explicit-`CONTINUE` budget, nor
/// persists stalled state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceptanceProtocolError {
    /// The command exited without emitting any canonical verdict.
    MissingVerdict,
    /// The command emitted `gated`/legacy `blocked` without a validated
    /// structured blocker payload.
    BareBlocker,
    /// The command emitted a FAIL verdict whose structured finding payload did
    /// not validate.
    MalformedFinding,
}

impl AcceptanceProtocolError {
    /// Short label used in operator-facing diagnostics.
    pub fn label(self) -> &'static str {
        match self {
            AcceptanceProtocolError::MissingVerdict => "missing-verdict",
            AcceptanceProtocolError::BareBlocker => "bare-blocker",
            AcceptanceProtocolError::MalformedFinding => "malformed-finding",
        }
    }
}

/// First history/finding line recorded when acceptance emits a FAIL whose
/// structured finding payload does not validate.
pub const MALFORMED_FINDING_DIAGNOSTIC: &str =
    "Malformed acceptance finding: acceptance emitted a \
     FAIL verdict with a structured finding that is missing a stable id, severity, summary, \
     evidence, required_changes, or verification (protocol failure; runtime will not reduce it to \
     a path-only repair instruction)";

/// Marks an acceptance invocation as a protocol retry so the prompt builder can
/// inject the corrective continuation context for the specific contract that
/// was violated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AcceptanceProtocolRetry {
    /// Which protocol contract the previous attempt failed to satisfy.
    pub kind: AcceptanceProtocolError,
    /// 1-based retry index (the first retry after the initial attempt is 1).
    pub attempt: u32,
    /// Maximum number of retries permitted after the initial attempt.
    pub max: u32,
}

/// Routing decision for a completed acceptance command that violated one of the
/// verdict protocol contracts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingVerdictRetryDecision {
    /// Budget remains: re-invoke the normal configured acceptance command with
    /// the continuation context described by [`AcceptanceProtocolRetry`].
    Retry(AcceptanceProtocolRetry),
    /// Budget exhausted: route to the terminal protocol failure.
    Exhausted {
        kind: AcceptanceProtocolError,
        attempts: u32,
        max: u32,
    },
}

/// Consecutive protocol-failure accounting for one contract during a single
/// active orchestration run.
///
/// Per `openspec/CONSTITUTION.md` this is active-run memory only. It is never
/// persisted, so a process restart simply re-runs acceptance for an
/// applied-but-unarchived workspace instead of resuming a retry sequence.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProtocolRetryCounter {
    consecutive: u32,
}

impl ProtocolRetryCounter {
    /// Number of consecutive protocol failures observed so far.
    pub fn consecutive(&self) -> u32 {
        self.consecutive
    }

    /// Reset after any canonical verdict
    /// (PASS/FAIL/CONTINUE/validated-stall/permission-stall).
    pub fn reset(&mut self) {
        self.consecutive = 0;
    }

    /// Record one protocol failure of `kind` and return the routing decision.
    pub fn record(&mut self, kind: AcceptanceProtocolError) -> MissingVerdictRetryDecision {
        self.consecutive = self.consecutive.saturating_add(1);
        if self.consecutive <= MAX_ACCEPTANCE_PROTOCOL_RETRIES {
            MissingVerdictRetryDecision::Retry(AcceptanceProtocolRetry {
                kind,
                attempt: self.consecutive,
                max: MAX_ACCEPTANCE_PROTOCOL_RETRIES,
            })
        } else {
            MissingVerdictRetryDecision::Exhausted {
                kind,
                attempts: self.consecutive,
                max: MAX_ACCEPTANCE_PROTOCOL_RETRIES,
            }
        }
    }
}

fn bounded_missing_verdict_evidence(findings: &[String]) -> String {
    let evidence = findings
        .iter()
        .take(5)
        .cloned()
        .collect::<Vec<_>>()
        .join(" | ");
    if evidence.is_empty() {
        "no acceptance output captured".to_string()
    } else {
        evidence
    }
}

/// Non-terminal progress message for a protocol retry.
///
/// Deliberately worded as progress, not error: the change is still acceptance
/// work in progress while retry budget remains.
pub fn missing_verdict_retry_progress(
    retry: AcceptanceProtocolRetry,
    findings: &[String],
) -> String {
    let cause = match retry.kind {
        AcceptanceProtocolError::MissingVerdict => "without a canonical verdict",
        AcceptanceProtocolError::BareBlocker => "with a gated token but no validated blocker",
        AcceptanceProtocolError::MalformedFinding => {
            "with a FAIL verdict whose structured finding did not validate"
        }
    };
    format!(
        "Acceptance completed {cause}; retrying acceptance \
         (protocol retry {}/{}). Evidence: {}",
        retry.attempt,
        retry.max,
        bounded_missing_verdict_evidence(findings)
    )
}

/// Terminal diagnostic emitted once the protocol retry budget is spent.
pub fn missing_verdict_exhausted_error(attempts: u32, max: u32, findings: &[String]) -> String {
    protocol_exhausted_error(
        AcceptanceProtocolError::MissingVerdict,
        attempts,
        max,
        findings,
    )
}

/// Terminal diagnostic for either protocol contract.
pub fn protocol_exhausted_error(
    kind: AcceptanceProtocolError,
    attempts: u32,
    max: u32,
    findings: &[String],
) -> String {
    let cause = match kind {
        AcceptanceProtocolError::MissingVerdict => {
            "Acceptance completed without a canonical verdict (missing-verdict protocol failure); \
             status-only or waiting output is not a verdict."
        }
        AcceptanceProtocolError::BareBlocker => {
            "Acceptance emitted a gated compatibility token without a validated structured blocker \
             (bare-blocker protocol failure); a stalled hold requires an explicit supported \
             category, concrete evidence, next action, and resumability."
        }
        AcceptanceProtocolError::MalformedFinding => {
            "Acceptance emitted a FAIL verdict whose structured finding did not validate \
             (malformed-finding protocol failure); a structured finding requires a stable id, a \
             major/minor severity, a summary, concrete evidence, and repository-relative \
             required_changes and verification entries."
        }
    };
    format!(
        "{cause} Exhausted {attempts} consecutive attempts after {max} protocol retries. \
         Evidence: {}",
        bounded_missing_verdict_evidence(findings)
    )
}

/// Maximum Acceptance-only retries permitted after the initial command failure.
///
/// Fixed protocol safety bound rather than configuration: the initial invocation
/// plus these retries gives three consecutive opportunities for the configured
/// Acceptance command to run to completion. It is deliberately independent from
/// [`MAX_ACCEPTANCE_PROTOCOL_RETRIES`], the configured explicit-`CONTINUE`
/// budget, and [`MAX_ACCEPTANCE_RETRY_CYCLES`]: a command that could not run at
/// all produced no verdict to consume any of those.
pub const MAX_ACCEPTANCE_COMMAND_RETRIES: u32 = 2;

/// Bounded Conflux-managed diagnosis of one Acceptance command that failed to
/// complete.
///
/// This is transport evidence, never an Acceptance verdict: it can never be
/// parsed as a canonical outcome, appended as a FAIL finding, or merged into
/// canonical [`crate::history::AcceptanceHistory`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AcceptanceCommandDiagnostic {
    /// Human-facing error summary for the failed invocation.
    pub error: String,
    /// Child exit code when the process actually reported one.
    pub exit_code: Option<i32>,
    /// Bounded stdout tail captured by the existing output collector.
    pub stdout_tail: Option<String>,
    /// Bounded stderr tail captured by the existing output collector.
    pub stderr_tail: Option<String>,
}

impl AcceptanceCommandDiagnostic {
    /// One-line bounded summary used in operator-facing progress and terminal
    /// messages.
    pub fn summary(&self) -> String {
        const MAX_TAIL_CHARS: usize = 400;

        fn condense(tail: &str) -> String {
            let single_line = tail.split_whitespace().collect::<Vec<_>>().join(" ");
            match single_line.char_indices().nth(MAX_TAIL_CHARS) {
                Some((idx, _)) => format!("{}...", &single_line[..idx]),
                None => single_line,
            }
        }

        let mut parts = vec![self.error.clone()];
        if let Some(code) = self.exit_code {
            parts.push(format!("exit_code: {}", code));
        }
        // Both streams are reported, each bounded on its own. A command that
        // writes its diagnosis to stdout and an unrelated warning to stderr
        // would otherwise lose the diagnosis entirely.
        if let Some(stdout) = self.stdout_tail.as_deref().filter(|t| !t.trim().is_empty()) {
            parts.push(format!("stdout: {}", condense(stdout)));
        }
        if let Some(stderr) = self.stderr_tail.as_deref().filter(|t| !t.trim().is_empty()) {
            parts.push(format!("stderr: {}", condense(stderr)));
        }
        parts.join(" | ")
    }
}

/// Classify a permission/tool-policy denial from one failed Acceptance
/// invocation's bounded transport evidence.
///
/// Shared by the acceptance runner and its retry loop so both decide
/// "is this a policy denial?" from exactly the same bytes and the same
/// classifier parallel acceptance uses.
pub fn classify_acceptance_command_denial(
    diagnostic: &AcceptanceCommandDiagnostic,
) -> Option<crate::permission::PermissionDenial> {
    crate::permission::classify_permission_denial(&[
        diagnostic.stdout_tail.as_deref(),
        diagnostic.stderr_tail.as_deref(),
    ])
}

/// Routing decision for one Acceptance command that failed to complete.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceCommandRetryDecision {
    /// Budget remains: re-invoke only the configured Acceptance command against
    /// the same applied, clean workspace.
    Retry {
        /// 1-based retry index; the first retry after the initial failure is 1.
        attempt: u32,
        max_retries: u32,
        diagnostic: AcceptanceCommandDiagnostic,
    },
    /// Third consecutive failure: route to the terminal Acceptance command error.
    Exhausted {
        attempts: u32,
        max_retries: u32,
        diagnostic: AcceptanceCommandDiagnostic,
    },
}

/// Consecutive Acceptance command-failure accounting for one change during a
/// single active run.
///
/// Per `openspec/CONSTITUTION.md` this is active-run memory only. It is never
/// persisted, so a restart simply re-runs Acceptance against the applied, clean,
/// unarchived workspace with a fresh budget.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AcceptanceCommandRetryCounter {
    consecutive_failures: u32,
}

impl AcceptanceCommandRetryCounter {
    /// Consecutive command failures observed since the last completed
    /// non-command-failure invocation.
    pub fn consecutive_failures(&self) -> u32 {
        self.consecutive_failures
    }

    /// End the consecutive sequence.
    ///
    /// Called for every invocation that completes as any non-command-failure
    /// result — canonical PASS/FAIL/CONTINUE, validated stalled or
    /// permission-stalled, missing verdict, malformed finding, and bare blocker —
    /// before that result follows its own existing routing.
    pub fn reset(&mut self) {
        self.consecutive_failures = 0;
    }

    /// Record one command failure and return the routing decision.
    pub fn record_command_failure(
        &mut self,
        diagnostic: AcceptanceCommandDiagnostic,
    ) -> AcceptanceCommandRetryDecision {
        self.consecutive_failures = self.consecutive_failures.saturating_add(1);
        if self.consecutive_failures <= MAX_ACCEPTANCE_COMMAND_RETRIES {
            AcceptanceCommandRetryDecision::Retry {
                attempt: self.consecutive_failures,
                max_retries: MAX_ACCEPTANCE_COMMAND_RETRIES,
                diagnostic,
            }
        } else {
            AcceptanceCommandRetryDecision::Exhausted {
                attempts: self.consecutive_failures,
                max_retries: MAX_ACCEPTANCE_COMMAND_RETRIES,
                diagnostic,
            }
        }
    }
}

/// Non-terminal progress message for an Acceptance command retry.
///
/// Deliberately worded as progress, not error: the change is still Acceptance
/// work in progress while command-recovery budget remains.
pub fn acceptance_command_retry_progress(
    attempt: u32,
    max_retries: u32,
    diagnostic: &AcceptanceCommandDiagnostic,
) -> String {
    format!(
        "Acceptance command did not complete (command-failure recovery {attempt}/{max_retries}); \
         re-running only the configured acceptance command against the same applied workspace. \
         Evidence: {}",
        diagnostic.summary()
    )
}

/// Terminal diagnostic emitted after the third consecutive command failure.
pub fn acceptance_command_exhausted_error(
    attempts: u32,
    max_retries: u32,
    diagnostic: &AcceptanceCommandDiagnostic,
) -> String {
    format!(
        "Acceptance command failed to complete on {attempts} consecutive attempts after \
         {max_retries} command-failure retries. Evidence: {}",
        diagnostic.summary()
    )
}

/// What execution must do next after an Acceptance command
/// failure.
///
/// One shared decision so both frontends apply the same bound, the same
/// latest-only prompt context, and the same terminal shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceCommandRecovery {
    /// Re-invoke only the configured Acceptance command. The message is
    /// operator-facing progress, not an error.
    Retry { attempt: u32, progress: String },
    /// Budget spent: return the existing terminal Acceptance command failure.
    Exhausted { attempts: u32, error: String },
}

/// Shared Acceptance command-failure policy used by every
/// execution.
///
/// Records the failure against `counter`, stores the latest-only bounded
/// diagnosis on `agent` so the next normal Acceptance prompt can render it as
/// untrusted evidence, and returns the routing decision. Exhaustion clears the
/// prompt context because no further command retry follows it.
///
/// This never reruns Apply or cleanup-review and never touches the
/// missing-verdict/protocol, explicit-`CONTINUE`, or FAIL-to-Apply budgets.
pub fn decide_acceptance_command_failure(
    counter: &mut AcceptanceCommandRetryCounter,
    agent: &mut AgentRunner,
    change_id: &str,
    diagnostic: AcceptanceCommandDiagnostic,
) -> AcceptanceCommandRecovery {
    match counter.record_command_failure(diagnostic) {
        AcceptanceCommandRetryDecision::Retry {
            attempt,
            max_retries,
            diagnostic,
        } => {
            let progress = acceptance_command_retry_progress(attempt, max_retries, &diagnostic);
            agent.set_acceptance_command_recovery(change_id, diagnostic);
            AcceptanceCommandRecovery::Retry { attempt, progress }
        }
        AcceptanceCommandRetryDecision::Exhausted {
            attempts,
            max_retries,
            diagnostic,
        } => {
            agent.clear_acceptance_command_recovery(change_id);
            AcceptanceCommandRecovery::Exhausted {
                attempts,
                error: acceptance_command_exhausted_error(attempts, max_retries, &diagnostic),
            }
        }
    }
}

/// Shared reset boundary for Acceptance command recovery.
///
/// Any invocation that completes as a non-command-failure result ends the
/// consecutive sequence and clears the latest-only prompt context *before* that
/// result follows its existing canonical, missing/malformed protocol, stalled,
/// permission-stalled, or blocker routing. A later command failure therefore
/// starts a fresh sequence with fresh latest-only context.
pub fn observe_completed_acceptance_invocation(
    counter: &mut AcceptanceCommandRetryCounter,
    agent: &mut AgentRunner,
    change_id: &str,
) {
    counter.reset();
    agent.clear_acceptance_command_recovery(change_id);
}

/// Observe one Acceptance invocation's non-command-failure result against the
/// shared command-recovery budget.
///
/// A deliberate termination never *completed* an invocation: the absolute
/// runtime limit and an operator stop both ended the work rather than producing
/// evidence about it, so neither resets nor consumes the budget, and neither
/// creates corrective command-recovery prompt context. Every other result ends
/// the consecutive sequence before it follows its own existing routing.
///
/// The admissibility test lives inside this call on purpose. Leaving it at the
/// call site is what lets a second caller re-derive it slightly differently and
/// quietly count a terminated invocation as a completed one — which for a
/// runtime-limit expiry would mean resetting a budget the expiry is not
/// supposed to touch at all.
pub fn observe_acceptance_invocation_result(
    counter: &mut AcceptanceCommandRetryCounter,
    agent: &mut AgentRunner,
    change_id: &str,
    result: &AcceptanceResult,
) {
    if result.permits_acceptance_retry() {
        observe_completed_acceptance_invocation(counter, agent, change_id);
    }
}

/// Next step after an acceptance command violated a verdict protocol contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MissingVerdictRetryStep {
    /// Budget remains: re-invoke the normal configured acceptance command with
    /// `retry` as the continuation marker. `progress` is the non-terminal
    /// operator-visible message.
    Retry {
        retry: AcceptanceProtocolRetry,
        progress: String,
    },
    /// Budget exhausted: route to the terminal protocol failure.
    Exhausted { error: String },
}

/// Mode-independent driver for acceptance protocol-retry sequences.
///
/// Every frontend shares this driver so equivalent
/// observations produce equivalent routing. Each acceptance invocation reads its
/// continuation marker from [`Self::take_protocol_retry`] and reports the result
/// back through [`Self::observe_missing_verdict`],
/// [`Self::observe_bare_blocker`], or [`Self::observe_canonical_verdict`].
///
/// The two protocol contracts keep strictly independent counters: a bare
/// blocker never consumes missing-verdict budget and vice versa. Only a
/// canonical verdict resets either counter, so a run cannot alternate between
/// the two failure modes to buy unbounded retries.
///
/// All state is active-run memory. Nothing is written outside the worktree, so a
/// restarted process re-runs acceptance from workspace file/git state rather
/// than resuming a protocol-retry sequence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AcceptanceProtocolDriver {
    missing_verdict: ProtocolRetryCounter,
    bare_blocker: ProtocolRetryCounter,
    malformed_finding: ProtocolRetryCounter,
    pending: Option<AcceptanceProtocolRetry>,
}

impl AcceptanceProtocolDriver {
    /// Consume the continuation marker for the acceptance invocation that is
    /// about to start. `None` for an ordinary (non-retry) invocation.
    pub fn take_protocol_retry(&mut self) -> Option<AcceptanceProtocolRetry> {
        self.pending.take()
    }

    /// Consecutive missing verdicts observed so far.
    pub fn consecutive_missing_verdicts(&self) -> u32 {
        self.missing_verdict.consecutive()
    }

    /// Consecutive bare/invalid blocker verdicts observed so far.
    pub fn consecutive_bare_blockers(&self) -> u32 {
        self.bare_blocker.consecutive()
    }

    /// Record any canonical verdict
    /// (PASS/FAIL/CONTINUE/validated-stall/permission-stall).
    /// Canonical routing is unchanged; only the protocol sequences reset.
    pub fn observe_canonical_verdict(&mut self) {
        self.missing_verdict.reset();
        self.bare_blocker.reset();
        self.malformed_finding.reset();
        self.pending = None;
    }

    /// Consecutive malformed structured findings observed so far.
    pub fn consecutive_malformed_findings(&self) -> u32 {
        self.malformed_finding.consecutive()
    }

    /// Record a FAIL verdict whose structured finding payload did not validate.
    ///
    /// No repair work is dispatched: the runtime asks for a corrected verdict
    /// rather than guessing what the reviewer meant.
    pub fn observe_malformed_finding(
        &mut self,
        rejection: &crate::acceptance::FindingRejection,
    ) -> MissingVerdictRetryStep {
        let evidence = vec![MALFORMED_FINDING_DIAGNOSTIC.to_string(), rejection.reason()];
        let decision = self
            .malformed_finding
            .record(AcceptanceProtocolError::MalformedFinding);
        self.step_from(decision, &evidence)
    }

    /// Record a completed acceptance command that emitted no canonical verdict
    /// and return the resulting non-terminal or terminal step.
    pub fn observe_missing_verdict(&mut self, findings: &[String]) -> MissingVerdictRetryStep {
        let decision = self
            .missing_verdict
            .record(AcceptanceProtocolError::MissingVerdict);
        self.step_from(decision, findings)
    }

    /// Record a `gated`/legacy `blocked` verdict whose blocker payload did not
    /// validate, and return the resulting non-terminal or terminal step.
    ///
    /// No blocker category is inferred and no stalled state is created.
    pub fn observe_bare_blocker(
        &mut self,
        rejection: &crate::acceptance::BlockerRejection,
    ) -> MissingVerdictRetryStep {
        let evidence = vec![BARE_BLOCKER_DIAGNOSTIC.to_string(), rejection.reason()];
        let decision = self
            .bare_blocker
            .record(AcceptanceProtocolError::BareBlocker);
        self.step_from(decision, &evidence)
    }

    fn step_from(
        &mut self,
        decision: MissingVerdictRetryDecision,
        findings: &[String],
    ) -> MissingVerdictRetryStep {
        match decision {
            MissingVerdictRetryDecision::Retry(retry) => {
                self.pending = Some(retry);
                MissingVerdictRetryStep::Retry {
                    retry,
                    progress: missing_verdict_retry_progress(retry, findings),
                }
            }
            MissingVerdictRetryDecision::Exhausted {
                kind,
                attempts,
                max,
            } => {
                self.pending = None;
                MissingVerdictRetryStep::Exhausted {
                    error: protocol_exhausted_error(kind, attempts, max, findings),
                }
            }
        }
    }
}

// ── Bounded Acceptance escalation ──────────────────────────────────────────

/// The exact generic finding runtime substitutes when a FAIL verdict carried no
/// parsed findings at all.
///
/// It names no defect, no evidence, and no required change, so a FAIL reduced to
/// exactly this line is reviewer output that failed to say anything actionable —
/// which is why it is an escalation-eligible invalid result rather than repair
/// work. A FAIL carrying any other finding is a real defect report and keeps its
/// FAIL-to-Apply routing.
pub const GENERIC_ACCEPTANCE_FAIL_FINDING: &str =
    "Investigate acceptance failure and apply the required fix";

/// Which reviewer command template one Acceptance invocation runs.
///
/// The mode is a decision the shared policy makes; `AgentRunner` only resolves
/// the matching template. Nothing else about the invocation differs, so a
/// frontend cannot accidentally give the alternate reviewer a different prompt
/// contract, history window, or placeholder set.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AcceptanceCommandMode {
    /// The configured `acceptance_command`.
    #[default]
    Normal,
    /// The optional `acceptance_escalation_command`.
    Escalation,
}

impl AcceptanceCommandMode {
    /// Whether this invocation runs the alternate reviewer.
    pub fn is_escalation(self) -> bool {
        matches!(self, AcceptanceCommandMode::Escalation)
    }

    /// Short label used in operator-facing diagnostics.
    pub fn label(self) -> &'static str {
        match self {
            AcceptanceCommandMode::Normal => "acceptance_command",
            AcceptanceCommandMode::Escalation => "acceptance_escalation_command",
        }
    }
}

/// Resolve the reviewer command template one Acceptance invocation runs.
///
/// The single resolution point every frontend uses, so "which command did this
/// invocation actually run" has exactly one answer. Escalation is selected only
/// by [`AcceptanceEscalationDriver`], which never selects it without a
/// configured command; a missing template here therefore means a caller
/// bypassed that policy, and it fails loudly rather than silently running the
/// normal reviewer while reporting an escalation.
pub fn acceptance_command_template(
    config: &crate::config::OrchestratorConfig,
    command_mode: AcceptanceCommandMode,
) -> Result<&str> {
    match command_mode {
        AcceptanceCommandMode::Normal => config.get_acceptance_command(),
        AcceptanceCommandMode::Escalation => {
            config.get_acceptance_escalation_command().ok_or_else(|| {
                OrchestratorError::ConfigLoad(
                    "Missing optional config: acceptance_escalation_command. Acceptance \
                     escalation was selected without a configured alternate reviewer command."
                        .to_string(),
                )
            })
        }
    }
}

/// One completed Acceptance result whose reviewer output violated the verdict
/// contract badly enough that re-running the *same* reviewer is unlikely to
/// produce an actionable finding.
///
/// Deliberately closed: a canonical PASS, a FAIL with at least one actionable
/// finding, CONTINUE, a validated external blocker, a permission hold, a
/// command failure, a runtime limit, and a cancellation are all excluded, and
/// each keeps its own existing routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvalidAcceptanceResult {
    /// The command exited without emitting any canonical verdict.
    MissingVerdict,
    /// A `gated`/legacy `blocked` token arrived without a validated blocker.
    BareBlocker,
    /// A FAIL verdict's structured finding payload did not validate.
    MalformedFinding,
    /// A FAIL verdict whose finding list was empty, leaving only the exact
    /// generic fallback.
    EmptyFail,
}

impl InvalidAcceptanceResult {
    /// Short label used in operator-facing diagnostics.
    pub fn label(self) -> &'static str {
        match self {
            InvalidAcceptanceResult::MissingVerdict => "missing-verdict",
            InvalidAcceptanceResult::BareBlocker => "bare-blocker",
            InvalidAcceptanceResult::MalformedFinding => "malformed-finding",
            InvalidAcceptanceResult::EmptyFail => "empty-fail",
        }
    }

    /// Whether this class already owns an Acceptance-only protocol retry.
    ///
    /// The three protocol contracts do; an empty FAIL does not, which is why
    /// its alternate-review retry is bounded solely by the escalation use cap
    /// and why it otherwise follows the existing generic FAIL-to-Apply fallback.
    pub fn has_protocol_retry_budget(self) -> bool {
        !matches!(self, InvalidAcceptanceResult::EmptyFail)
    }
}

/// Whether a FAIL verdict's finding list is the exact generic empty-FAIL
/// fallback rather than an actionable defect report.
///
/// Both shapes are accepted because the substitution happens at different
/// layers: the parser may hand up an empty list, and the executors replace an
/// empty list with exactly one legacy finding carrying
/// [`GENERIC_ACCEPTANCE_FAIL_FINDING`]. Anything else — a structured finding, a
/// different legacy text, or more than one finding — is actionable repair work.
pub fn is_generic_empty_fail(findings: &[crate::acceptance::AcceptanceFinding]) -> bool {
    match findings {
        [] => true,
        [only] => {
            only.structured_payload().is_none() && only.text() == GENERIC_ACCEPTANCE_FAIL_FINDING
        }
        _ => false,
    }
}

/// Classify one completed Acceptance result for escalation eligibility.
///
/// Returns `None` for every result that is not an eligible invalid class,
/// including a semantic FAIL with actionable findings.
pub fn classify_invalid_acceptance_result(
    result: &AcceptanceResult,
) -> Option<InvalidAcceptanceResult> {
    match result {
        AcceptanceResult::MissingVerdict { .. } => Some(InvalidAcceptanceResult::MissingVerdict),
        AcceptanceResult::BareBlocker { .. } => Some(InvalidAcceptanceResult::BareBlocker),
        AcceptanceResult::MalformedFinding { .. } => {
            Some(InvalidAcceptanceResult::MalformedFinding)
        }
        AcceptanceResult::Fail { findings } => {
            is_generic_empty_fail(findings).then_some(InvalidAcceptanceResult::EmptyFail)
        }
        AcceptanceResult::Pass
        | AcceptanceResult::Continue
        | AcceptanceResult::Stalled { .. }
        | AcceptanceResult::PermissionStalled { .. }
        | AcceptanceResult::CommandFailed { .. }
        | AcceptanceResult::RuntimeLimit { .. }
        // A bounded execution hold is a boundary decision, not an invalid
        // reviewer response: escalating it would re-dispatch exactly the work
        // the boundary just stopped.
        | AcceptanceResult::ExecutionHold { .. }
        | AcceptanceResult::Cancelled => None,
    }
}

/// Why an eligible invalid result did not select the escalation command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EscalationDeclineReason {
    /// No `acceptance_escalation_command` is configured.
    NoCommandConfigured,
    /// Fewer consecutive invalid results than the configured threshold.
    BelowThreshold { after_invalid_results: u32 },
    /// The per-sequence use budget is spent.
    UseCapExhausted { max_uses_per_sequence: u32 },
}

impl EscalationDeclineReason {
    fn describe(self) -> String {
        match self {
            EscalationDeclineReason::NoCommandConfigured => {
                "no acceptance_escalation_command is configured".to_string()
            }
            EscalationDeclineReason::BelowThreshold {
                after_invalid_results,
            } => format!(
                "the configured threshold of {after_invalid_results} consecutive invalid results \
                 has not been reached"
            ),
            EscalationDeclineReason::UseCapExhausted {
                max_uses_per_sequence,
            } => format!(
                "the escalation budget of {max_uses_per_sequence} use(s) per invalid-result \
                 sequence is spent"
            ),
        }
    }
}

/// What one observed Acceptance result did to the escalation sequence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceEscalationOutcome {
    /// The invocation did not complete — a command failure, a runtime-limit
    /// expiry, or a cancellation. It produced no reviewer output to judge, so it
    /// neither consumes nor resets the sequence and any pending command mode
    /// survives into the retry the owning budget dispatches.
    NotObserved,
    /// A completed non-invalid result ended the sequence and cleared any pending
    /// escalation.
    SequenceReset,
    /// An eligible invalid result was recorded and the next permitted
    /// Acceptance-only retry uses the escalation command.
    Escalated {
        kind: InvalidAcceptanceResult,
        consecutive_invalid: u32,
        use_index: u32,
        max_uses_per_sequence: u32,
    },
    /// An eligible invalid result was recorded, but escalation was not selected.
    /// Existing routing for that result class is unchanged.
    Retained {
        kind: InvalidAcceptanceResult,
        consecutive_invalid: u32,
        reason: EscalationDeclineReason,
    },
}

impl AcceptanceEscalationOutcome {
    /// Whether the next Acceptance-only retry runs the alternate reviewer.
    pub fn escalation_selected(&self) -> bool {
        matches!(self, AcceptanceEscalationOutcome::Escalated { .. })
    }

    /// Operator-facing line for this observation, or `None` when there is
    /// nothing worth reporting.
    ///
    /// Reset and non-observation are deliberately silent: they are the ordinary
    /// case and a log line per Acceptance invocation would bury the two events
    /// an operator actually needs to see.
    pub fn diagnostic(&self) -> Option<String> {
        match self {
            AcceptanceEscalationOutcome::NotObserved
            | AcceptanceEscalationOutcome::SequenceReset => None,
            AcceptanceEscalationOutcome::Escalated {
                kind,
                consecutive_invalid,
                use_index,
                max_uses_per_sequence,
            } => Some(format!(
                "Acceptance produced an invalid result ({}); the next acceptance-only retry uses \
                 acceptance_escalation_command (invalid results: {}, escalation use \
                 {}/{}).",
                kind.label(),
                consecutive_invalid,
                use_index,
                max_uses_per_sequence
            )),
            AcceptanceEscalationOutcome::Retained {
                kind,
                consecutive_invalid,
                reason,
            } => Some(format!(
                "Acceptance produced an invalid result ({}, consecutive invalid results: {}); \
                 keeping the normal acceptance_command because {}.",
                kind.label(),
                consecutive_invalid,
                reason.describe()
            )),
        }
    }
}

/// Whether this observation replaces an empty FAIL's generic repair dispatch
/// with an acceptance-only alternate review.
///
/// The empty FAIL is the one eligible class whose *routing* escalation changes:
/// every other class already owns an Acceptance-only retry and only learns which
/// reviewer runs it. The answer is read from the kind the driver already
/// returned, so an execution frontend never re-classifies the result to decide
/// its own routing.
pub fn escalates_empty_fail(outcome: &AcceptanceEscalationOutcome) -> bool {
    matches!(
        outcome,
        AcceptanceEscalationOutcome::Escalated {
            kind: InvalidAcceptanceResult::EmptyFail,
            ..
        }
    )
}

/// Bounded invalid-result accounting and reviewer-command selection for one
/// change during a single active run.
///
/// Per `openspec/CONSTITUTION.md` this is active-run memory only. Nothing is
/// written outside the worktree, so a restarted process runs ordinary Acceptance
/// from workspace file and Git evidence instead of resuming an escalation
/// sequence.
///
/// Escalation never creates a retry opportunity of its own for a class that
/// already has one: it changes *which* command the existing Acceptance-only
/// retry runs. The one class with no pre-existing Acceptance-only retry — an
/// empty FAIL — is bounded solely by [`Self::max_uses_per_sequence`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptanceEscalationDriver {
    command_configured: bool,
    after_invalid_results: u32,
    max_uses_per_sequence: u32,
    consecutive_invalid: u32,
    uses_in_sequence: u32,
    pending_escalation: bool,
    last_revision: Option<String>,
}

impl AcceptanceEscalationDriver {
    /// Build the driver from merged configuration.
    pub fn from_config(config: &crate::config::OrchestratorConfig) -> Self {
        let policy = config.get_acceptance_escalation();
        Self {
            command_configured: config.get_acceptance_escalation_command().is_some(),
            after_invalid_results: policy.after_invalid_results(),
            max_uses_per_sequence: policy.max_uses_per_sequence(),
            consecutive_invalid: 0,
            uses_in_sequence: 0,
            pending_escalation: false,
            last_revision: None,
        }
    }

    /// Consecutive eligible invalid results observed in the current sequence.
    pub fn consecutive_invalid(&self) -> u32 {
        self.consecutive_invalid
    }

    /// Escalation-command uses already spent in the current sequence.
    pub fn uses_in_sequence(&self) -> u32 {
        self.uses_in_sequence
    }

    /// Consume the command mode for the Acceptance invocation that is about to
    /// start.
    ///
    /// Every invocation reads this exactly once, so an ordinary invocation and
    /// an escalation retry cannot both claim the same selection.
    pub fn take_command_mode(&mut self) -> AcceptanceCommandMode {
        if std::mem::take(&mut self.pending_escalation) {
            AcceptanceCommandMode::Escalation
        } else {
            AcceptanceCommandMode::Normal
        }
    }

    /// Observe one Acceptance result against the escalation policy.
    ///
    /// `revision` is the workspace revision this result was produced against.
    /// A revision that moved since the previous observation is real repository
    /// progress, so it starts a fresh sequence before this result is classified
    /// — that is what keeps an empty-FAIL sequence alive across an Apply round
    /// that changed nothing, without letting it survive one that did.
    pub fn observe(
        &mut self,
        result: &AcceptanceResult,
        revision: Option<&str>,
    ) -> AcceptanceEscalationOutcome {
        if let Some(revision) = revision {
            if self
                .last_revision
                .as_deref()
                .is_some_and(|previous| previous != revision)
            {
                self.reset_sequence();
            }
            self.last_revision = Some(revision.to_string());
        }

        // A deliberate termination and a command that never completed produced
        // no reviewer output, so neither is evidence about reviewer quality.
        // Leaving the sequence untouched is what lets a pending escalation
        // survive into the retry the command-recovery budget dispatches.
        if !result.permits_acceptance_retry()
            || matches!(result, AcceptanceResult::CommandFailed { .. })
        {
            return AcceptanceEscalationOutcome::NotObserved;
        }

        let Some(kind) = classify_invalid_acceptance_result(result) else {
            self.reset_sequence();
            return AcceptanceEscalationOutcome::SequenceReset;
        };

        self.consecutive_invalid = self.consecutive_invalid.saturating_add(1);

        let decline = if !self.command_configured {
            Some(EscalationDeclineReason::NoCommandConfigured)
        } else if self.consecutive_invalid < self.after_invalid_results {
            Some(EscalationDeclineReason::BelowThreshold {
                after_invalid_results: self.after_invalid_results,
            })
        } else if self.uses_in_sequence >= self.max_uses_per_sequence {
            Some(EscalationDeclineReason::UseCapExhausted {
                max_uses_per_sequence: self.max_uses_per_sequence,
            })
        } else {
            None
        };

        match decline {
            Some(reason) => AcceptanceEscalationOutcome::Retained {
                kind,
                consecutive_invalid: self.consecutive_invalid,
                reason,
            },
            None => {
                // The budget is consumed at selection, not at consumption: a
                // pending escalation carried across a command-failure retry must
                // not be counted twice.
                self.uses_in_sequence = self.uses_in_sequence.saturating_add(1);
                self.pending_escalation = true;
                AcceptanceEscalationOutcome::Escalated {
                    kind,
                    consecutive_invalid: self.consecutive_invalid,
                    use_index: self.uses_in_sequence,
                    max_uses_per_sequence: self.max_uses_per_sequence,
                }
            }
        }
    }

    fn reset_sequence(&mut self) {
        self.consecutive_invalid = 0;
        self.uses_in_sequence = 0;
        self.pending_escalation = false;
    }
}

/// Shared, mode-independent routing for an acceptance result that carries (or
/// claims to carry) an external blocker.
///
/// This is the single decision API every frontend uses so
/// equivalent observations produce equivalent retry, stall, and terminal
/// protocol-error outcomes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceBlockerDecision {
    /// Bare or invalid blocker input with budget remaining: re-invoke
    /// acceptance only, with corrective context. Apply is never rerun and no
    /// stalled state is created.
    ProtocolRetry {
        retry: AcceptanceProtocolRetry,
        progress: String,
    },
    /// Bare or invalid blocker input with budget spent: terminal acceptance
    /// protocol error requiring explicit retry.
    ProtocolExhausted { error: String },
    /// Structured external blocker facts that passed acceptance-payload
    /// validation.
    ///
    /// This is still only *reported evidence*. The orchestrator's classifier
    /// makes the final lifecycle call, which for a complete payload is external
    /// `blocked` — never `stalled`, and never a dependency edge.
    ExternalBlocker {
        blocker: crate::acceptance::AcceptanceBlocker,
    },
}

/// Route an acceptance result through the shared blocker/protocol policy.
///
/// Returns `None` for results this policy does not own (PASS, FAIL, CONTINUE,
/// command failure, cancellation, missing verdict), leaving their existing
/// routing untouched.
pub fn decide_acceptance_blocker(
    driver: &mut AcceptanceProtocolDriver,
    result: &AcceptanceResult,
) -> Option<AcceptanceBlockerDecision> {
    match result {
        AcceptanceResult::BareBlocker { rejection } => {
            Some(match driver.observe_bare_blocker(rejection) {
                MissingVerdictRetryStep::Retry { retry, progress } => {
                    AcceptanceBlockerDecision::ProtocolRetry { retry, progress }
                }
                MissingVerdictRetryStep::Exhausted { error } => {
                    AcceptanceBlockerDecision::ProtocolExhausted { error }
                }
            })
        }
        AcceptanceResult::MalformedFinding { rejection } => {
            Some(match driver.observe_malformed_finding(rejection) {
                MissingVerdictRetryStep::Retry { retry, progress } => {
                    AcceptanceBlockerDecision::ProtocolRetry { retry, progress }
                }
                MissingVerdictRetryStep::Exhausted { error } => {
                    AcceptanceBlockerDecision::ProtocolExhausted { error }
                }
            })
        }
        AcceptanceResult::Stalled { blocker } => {
            // A validated blocker payload is a canonical verdict: it resets every
            // protocol sequence and hands complete facts to the orchestrator's
            // lifecycle classifier.
            driver.observe_canonical_verdict();
            Some(AcceptanceBlockerDecision::ExternalBlocker {
                blocker: blocker.clone(),
            })
        }
        _ => None,
    }
}

/// A finding paired with its compact comparison identity.
///
/// `identity` exists purely for retry accounting and reconciliation. `finding`
/// keeps the complete actionable payload, so nothing downstream has to
/// reconstruct evidence, required changes, or verification from the identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizedFinding {
    pub identity: String,
    pub text: String,
    pub external: bool,
    pub finding: crate::acceptance::AcceptanceFinding,
}

/// Derive comparison identities for a finding list.
///
/// A structured finding's identity is its reviewer-authored `id`, so changed
/// prose, line numbers, evidence, or cited paths cannot manufacture a new
/// identity. Legacy string findings keep the historical deterministic fallback.
pub fn normalize_findings(
    findings: &[crate::acceptance::AcceptanceFinding],
) -> Vec<NormalizedFinding> {
    let mut normalized = findings
        .iter()
        .filter_map(|finding| {
            let structured = finding.structured_payload()?;
            Some(NormalizedFinding {
                identity: format!("repository|id|{}", structured.id),
                text: finding.text().to_string(),
                external: false,
                finding: finding.clone(),
            })
        })
        .collect::<Vec<_>>();
    normalized.extend(normalize_legacy_findings(
        findings
            .iter()
            .filter(|finding| finding.structured_payload().is_none()),
    ));
    normalized.sort_by(|left, right| left.identity.cmp(&right.identity));
    normalized.dedup_by(|left, right| left.identity == right.identity);
    normalized
}

fn normalize_legacy_findings<'a, I>(findings: I) -> Vec<NormalizedFinding>
where
    I: IntoIterator<Item = &'a crate::acceptance::AcceptanceFinding>,
{
    let texts = findings
        .into_iter()
        .map(|finding| finding.text().to_string())
        .collect::<Vec<_>>();
    normalize_legacy_texts(&texts)
}

/// Legacy fallback identity derivation, retained verbatim for string findings.
pub fn normalize_legacy_texts(findings: &[String]) -> Vec<NormalizedFinding> {
    fn rule_kind(text: &str) -> &'static str {
        if ["test", "coverage", "verification", "evidence"]
            .iter()
            .any(|word| text.contains(word))
        {
            "verification"
        } else if ["spec", "proposal", "requirement"]
            .iter()
            .any(|word| text.contains(word))
        {
            "specification"
        } else if ["task", "checklist", "truthful"]
            .iter()
            .any(|word| text.contains(word))
        {
            "task-truthfulness"
        } else if text.contains("dirty working tree") {
            "workspace-cleanliness"
        } else {
            "implementation"
        }
    }

    let mut normalized = findings
        .iter()
        .filter_map(|finding| {
            let normalized = finding.split_whitespace().collect::<Vec<_>>().join(" ");
            (!normalized.is_empty()).then(|| {
                let lower = normalized.to_ascii_lowercase();
                let finding_code = lower
                    .split_whitespace()
                    .next()
                    .filter(|word| word.starts_with('[') && word.ends_with(']'));
                let path_token = lower
                    .split_whitespace()
                    .find(|word| {
                        word.contains('/') || word.ends_with(".rs") || word.ends_with(".md")
                    })
                    .unwrap_or("");
                let path = path_token
                    .trim_matches(|character: char| {
                        matches!(character, '`' | '(' | ')' | '[' | ']' | ',' | '.' | ';')
                    })
                    .split(':')
                    .next()
                    .unwrap_or("");
                // An explicit non-mockable prerequisite is external only when the
                // finding has no repository target or requested repository repair.
                let external = path.is_empty()
                    && !lower.contains("fix ")
                    && !lower.contains("repair ")
                    && [
                        "external non-mockable",
                        "non-mockable external",
                        "external prerequisite",
                        "external service outage",
                        "missing non-mockable external credential",
                    ]
                    .iter()
                    .any(|needle| lower.contains(needle));
                let scope = if external { "external" } else { "repository" };
                NormalizedFinding {
                    identity: finding_code.map_or_else(
                        || {
                            let location = if path.is_empty() {
                                lower.as_str()
                            } else {
                                path
                            };
                            format!("{scope}|{location}|{}", rule_kind(&lower))
                        },
                        |code| format!("{scope}|code|{code}"),
                    ),
                    finding: crate::acceptance::AcceptanceFinding::legacy(normalized.clone()),
                    text: normalized,
                    external,
                }
            })
        })
        .collect::<Vec<_>>();
    normalized.sort_by(|left, right| left.identity.cmp(&right.identity));
    normalized.dedup_by(|left, right| left.identity == right.identity);
    normalized
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceRetryDecision {
    Retry {
        reason: &'static str,
    },
    Stall {
        reason: &'static str,
        external_blockers: Vec<String>,
    },
}

/// Findings that repository work can resolve.
///
/// Structured findings are always repository-scoped: they declare repository
/// paths. Only legacy strings can be classified as external prerequisites.
pub fn repository_findings(
    findings: &[crate::acceptance::AcceptanceFinding],
) -> Vec<crate::acceptance::AcceptanceFinding> {
    findings
        .iter()
        .filter(|finding| {
            finding.structured_payload().is_some()
                || normalize_legacy_texts(&[finding.text().to_string()])
                    .first()
                    .is_some_and(|normalized| !normalized.external)
        })
        .cloned()
        .collect()
}

pub fn semantic_progress_fingerprint(workspace: &std::path::Path) -> std::io::Result<String> {
    /// The task artifact a repository path carries, if any.
    ///
    /// Both supported basenames are task evidence, so a JSON-only change is
    /// visible to progress detection exactly as a Markdown one is. The format
    /// travels with the answer because the runtime-owned follow-up has to be
    /// stripped differently in each.
    fn task_file_format(path: &str) -> Option<crate::task_file::TaskFileFormat> {
        path.rsplit('/')
            .next()
            .and_then(crate::task_file::TaskFileFormat::from_file_name)
    }
    // Conflux-owned runtime artifacts no longer live in the target, so there is
    // no Conflux path left to filter out here: the only exclusions remaining are
    // Git's own directory and the repository-owned locations this fingerprint
    // was never about. `.cflx.jsonc` stays *included* — it is a repository file
    // the project owns, and editing it is real progress.
    fn include(path: &str) -> bool {
        !path.starts_with(".git/")
            && !path.contains("/APPLY_BLOCKED/")
            && !path.starts_with("logs/")
            && !path.starts_with("history/")
            && (path.starts_with("src/")
                || path.starts_with("tests/")
                || path.starts_with("config/")
                || path.starts_with("openspec/specs/")
                || path.contains("/specs/")
                || path == ".cflx.jsonc"
                || path.ends_with("/.cflx.jsonc")
                || path.ends_with("Cargo.toml")
                || task_file_format(path).is_some())
    }
    /// Remove the runtime-owned follow-up from a task artifact's bytes.
    ///
    /// Runtime FAIL writes must never look like Apply progress, in either
    /// format. Markdown drops the trailing follow-up sections; JSON drops the
    /// `acceptance_follow_up` key and re-serializes the rest deterministically.
    /// Bytes that do not parse are hashed as they are: a malformed artifact is
    /// still repository content, and guessing at its structure would be worse
    /// than hashing it verbatim.
    fn strip_runtime_follow_up(
        format: crate::task_file::TaskFileFormat,
        contents: Vec<u8>,
    ) -> Vec<u8> {
        match format {
            crate::task_file::TaskFileFormat::Markdown => {
                let text = String::from_utf8_lossy(&contents);
                text.split("\n## Current Acceptance Follow-up")
                    .next()
                    .unwrap_or(&text)
                    .split("\n## Acceptance #")
                    .next()
                    .unwrap_or(&text)
                    .as_bytes()
                    .to_vec()
            }
            crate::task_file::TaskFileFormat::Json => {
                match serde_json::from_slice::<serde_json::Value>(&contents) {
                    Ok(serde_json::Value::Object(mut root)) => {
                        root.remove(crate::task_file::FOLLOW_UP_KEY);
                        serde_json::to_vec(&serde_json::Value::Object(root)).unwrap_or(contents)
                    }
                    _ => contents,
                }
            }
        }
    }
    fn visit(
        root: &std::path::Path,
        directory: &std::path::Path,
        output: &mut Vec<(String, Vec<u8>)>,
    ) -> std::io::Result<()> {
        for entry in std::fs::read_dir(directory)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit(root, &path, output)?;
                continue;
            }
            let relative = path
                .strip_prefix(root)
                .unwrap()
                .to_string_lossy()
                .replace('\\', "/");
            if include(&relative) {
                let mut contents = std::fs::read(path)?;
                if let Some(format) = task_file_format(&relative) {
                    contents = strip_runtime_follow_up(format, contents);
                }
                output.push((relative, contents));
            }
        }
        Ok(())
    }
    let mut files = Vec::new();
    visit(workspace, workspace, &mut files)?;
    files.sort_by(|left, right| left.0.cmp(&right.0));
    let hash = files
        .into_iter()
        .flat_map(|(path, bytes)| path.into_bytes().into_iter().chain(bytes))
        .fold(0xcbf29ce484222325u64, |hash, byte| {
            (hash ^ byte as u64).wrapping_mul(0x100000001b3)
        });
    Ok(format!("{hash:016x}"))
}

/// Stop reason for a repair hold that precedes the next Acceptance invocation.
///
/// Both reasons are temporary, evidenced, resumable holds. Neither proves
/// implementation completion, finding closure, PASS, archive readiness, or
/// merge eligibility, and neither writes anything into the managed worktree.
pub const REMEDIATION_MISMATCH_REASON: &str = "acceptance_remediation_mismatch";
/// Stop reason used when the same finding ID survives its one repair Apply.
pub const REPEATED_FINDING_REASON: &str = "repeated_acceptance_finding";

/// Result of comparing declared finding work against the actual repair delta.
///
/// This is a coverage gate, not semantic acceptance: passing it only authorizes
/// the next Acceptance invocation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RemediationCoverage {
    /// Files observed in the repair delta, sorted and deduplicated.
    pub changed_files: Vec<String>,
    /// Declared `required_changes` paths absent from the delta, per finding ID.
    pub missing_required: Vec<(String, String)>,
    /// Declared `verification` paths absent from the delta, per finding ID.
    pub missing_verification: Vec<(String, String)>,
    /// Changed files not declared by any finding.
    pub unrelated_files: Vec<String>,
    /// Findings that declare no path set and therefore keep legacy behavior.
    pub legacy_finding_texts: Vec<String>,
}

impl RemediationCoverage {
    /// Whether every declared implementation and verification path was covered.
    pub fn is_complete(&self) -> bool {
        self.missing_required.is_empty() && self.missing_verification.is_empty()
    }

    /// Uncovered declared paths, formatted for operator diagnostics.
    pub fn uncovered(&self) -> Vec<String> {
        self.missing_required
            .iter()
            .map(|(id, file)| format!("{id}: required_changes {file}"))
            .chain(
                self.missing_verification
                    .iter()
                    .map(|(id, file)| format!("{id}: verification {file}")),
            )
            .collect()
    }
}

/// Normalize one raw changed-path entry from a VCS status/diff listing.
fn normalize_changed_path(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    // `git diff --name-status` renames arrive as `old -> new`; both sides count
    // as touched so a finding satisfied by moving a file is still covered.
    crate::acceptance::normalize_repository_path(trimmed)
}

/// Collect the distinct repository-relative files in a repair delta.
pub fn normalize_changed_files<I, S>(paths: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut files = paths
        .into_iter()
        .flat_map(|path| {
            path.as_ref()
                .split(" -> ")
                .filter_map(normalize_changed_path)
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();
    files.sort();
    files.dedup();
    files
}

/// Validate that a repair delta covers every declared finding expectation.
///
/// Pure over the changed-file list so the decision is unit-testable without a
/// real repository. Coverage never claims the finding is semantically resolved.
pub fn evaluate_remediation_coverage(
    findings: &[crate::acceptance::AcceptanceFinding],
    changed_files: &[String],
) -> RemediationCoverage {
    let changed = normalize_changed_files(changed_files);
    let mut coverage = RemediationCoverage {
        changed_files: changed.clone(),
        ..RemediationCoverage::default()
    };
    let mut declared = std::collections::BTreeSet::new();

    for finding in findings {
        // A finding that declares no path set keeps legacy compatibility
        // behavior: strict coverage has nothing to enforce against.
        if !finding.declares_paths() {
            coverage
                .legacy_finding_texts
                .push(finding.text().to_string());
            continue;
        }
        let Some(structured) = finding.structured_payload() else {
            continue;
        };
        for file in structured.required_files() {
            declared.insert(file.clone());
            if !changed.contains(&file) {
                coverage
                    .missing_required
                    .push((structured.id.clone(), file));
            }
        }
        for file in structured.verification_files() {
            declared.insert(file.clone());
            if !changed.contains(&file) {
                coverage
                    .missing_verification
                    .push((structured.id.clone(), file));
            }
        }
    }

    coverage.unrelated_files = changed
        .into_iter()
        .filter(|file| !declared.contains(file))
        .collect();
    coverage
}

/// Per-finding automatic repair accounting for one active orchestration run.
///
/// Each stable ID gets exactly one automatic repair Apply after its first FAIL
/// observation. Unrelated semantic progress never resets that budget.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FindingRepairLedger {
    /// Identities that have already consumed their one automatic repair Apply.
    repaired: std::collections::BTreeSet<String>,
    /// How many canonical FAIL results reported each identity.
    occurrences: std::collections::BTreeMap<String, u32>,
}

/// What runtime should do after ingesting a canonical FAIL result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FindingRepairDecision {
    /// Every open finding still has its automatic repair opportunity.
    Repair {
        /// Identities granted (or continuing to hold) a repair opportunity.
        identities: Vec<String>,
    },
    /// At least one identity already consumed its repair opportunity.
    ///
    /// Runtime stops atomically: no partial Apply is dispatched even when other
    /// identities in the same verdict are new.
    Stop {
        reason: &'static str,
        repeated_identities: Vec<String>,
    },
}

impl FindingRepairLedger {
    /// Occurrence count for one identity across this run.
    pub fn occurrences(&self, identity: &str) -> u32 {
        self.occurrences.get(identity).copied().unwrap_or(0)
    }

    /// Every observed identity with its occurrence count, for diagnostics.
    pub fn occurrence_report(&self) -> Vec<(String, u32)> {
        self.occurrences
            .iter()
            .map(|(identity, count)| (identity.clone(), *count))
            .collect()
    }

    /// Whether an identity already consumed its automatic repair opportunity.
    pub fn has_consumed_repair(&self, identity: &str) -> bool {
        self.repaired.contains(identity)
    }

    /// Ingest a canonical FAIL result and decide whether repair may proceed.
    ///
    /// Identities absent from `findings` were closed by Acceptance, so their
    /// accounting is dropped: only Acceptance closes a finding.
    pub fn observe_fail(&mut self, findings: &[NormalizedFinding]) -> FindingRepairDecision {
        let identities = findings
            .iter()
            .filter(|finding| !finding.external)
            .map(|finding| finding.identity.clone())
            .collect::<Vec<_>>();
        let open = identities
            .iter()
            .cloned()
            .collect::<std::collections::BTreeSet<_>>();

        self.occurrences
            .retain(|identity, _| open.contains(identity));
        self.repaired.retain(|identity| open.contains(identity));
        for identity in &identities {
            *self.occurrences.entry(identity.clone()).or_insert(0) += 1;
        }

        let repeated = identities
            .iter()
            .filter(|identity| self.repaired.contains(*identity))
            .cloned()
            .collect::<Vec<_>>();
        if !repeated.is_empty() {
            return FindingRepairDecision::Stop {
                reason: REPEATED_FINDING_REASON,
                repeated_identities: repeated,
            };
        }
        FindingRepairDecision::Repair { identities }
    }

    /// Record that the automatic repair Apply for `identities` was dispatched.
    pub fn record_repair_dispatched(&mut self, identities: &[String]) {
        for identity in identities {
            self.repaired.insert(identity.clone());
        }
    }

    /// Drop all accounting, used when an operator authorizes a new attempt.
    ///
    /// Occurrence diagnostics are the caller's to preserve; this only releases
    /// the automatic budget so an explicit retry can proceed.
    pub fn reset_for_explicit_retry(&mut self) {
        self.repaired.clear();
    }
}

/// Structured, mode-independent diagnostics for a repair stop.
///
/// Every frontend builds this from the same inputs so equivalent
/// observations produce equivalent operator evidence. It is in-memory state for
/// one process lifetime and controls only stalled presentation, dispatch
/// suppression, and explicit-retry eligibility: it never proves implementation
/// completion, finding closure, Acceptance PASS, archive readiness, or merge
/// eligibility, and it is never written into a managed worktree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptanceRepairStop {
    pub change_id: String,
    pub reason: &'static str,
    /// Every open finding, complete and unmodified.
    pub findings: Vec<crate::acceptance::AcceptanceFinding>,
    /// Comparison identity plus how many canonical FAILs reported it.
    pub occurrences: Vec<(String, u32)>,
    /// Identities that already consumed their one automatic repair.
    pub repeated_identities: Vec<String>,
    /// Revision recorded when the FAIL was observed.
    pub fail_revision: Option<String>,
    /// Revision produced by the repair Apply.
    pub apply_revision: Option<String>,
    /// Declared implementation and verification paths.
    pub required_files: Vec<String>,
    pub verification_files: Vec<String>,
    /// Coverage result over the actual repair delta.
    pub coverage: RemediationCoverage,
    /// Apply-authored remediation evidence recovered from workspace follow-up.
    pub remediation_evidence: Vec<String>,
    pub resumable: bool,
    pub next_action: String,
}

impl AcceptanceRepairStop {
    /// Machine-readable diagnostics for CLI/TUI/event consumers.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "change_id": self.change_id,
            "stop_reason": self.reason,
            "findings": self.findings.iter().map(|finding| finding.to_json()).collect::<Vec<_>>(),
            "finding_occurrences": self
                .occurrences
                .iter()
                .map(|(identity, count)| serde_json::json!({"identity": identity, "occurrences": count}))
                .collect::<Vec<_>>(),
            "repeated_identities": self.repeated_identities,
            "fail_revision": self.fail_revision,
            "apply_revision": self.apply_revision,
            "required_files": self.required_files,
            "verification_files": self.verification_files,
            "changed_files": self.coverage.changed_files,
            "uncovered_files": self.coverage.uncovered(),
            "coverage_complete": self.coverage.is_complete(),
            "unrelated_files": self.coverage.unrelated_files,
            "legacy_findings_without_declared_paths": self.coverage.legacy_finding_texts,
            "remediation_evidence": self.remediation_evidence,
            "resumable": self.resumable,
            "next_action": self.next_action,
            "proves_completion": false,
            "proves_acceptance_pass": false,
            "proves_archive_readiness": false,
        })
    }

    /// Identities present in the occurrence report, in stable order.
    pub fn occurrence_identities(&self) -> Vec<String> {
        self.occurrences
            .iter()
            .map(|(identity, _)| identity.clone())
            .collect()
    }

    /// One-line operator-facing summary used as the process-result error text.
    pub fn summary(&self) -> String {
        format!(
            "Acceptance stopped automatic repair for {} ({}). {} Diagnostics: {}",
            self.change_id,
            self.reason,
            self.next_action,
            self.to_json()
        )
    }
}

/// What runtime should do before invoking Acceptance again after a repair Apply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepairGateDecision {
    /// Declared coverage is satisfied (or nothing was declared): Acceptance may
    /// run. This authorizes only the next review, never semantic resolution.
    Proceed,
    /// Coverage is incomplete: hold with evidence and do not spend an Acceptance
    /// invocation.
    Stop(Box<AcceptanceRepairStop>),
}

/// Validate a repair delta against every open structured finding.
///
/// Pure over `changed_files` and `remediation_evidence` so every frontend
/// share one decision and it stays unit-testable without a real repository.
pub fn decide_repair_gate(
    change_id: &str,
    findings: &[crate::acceptance::AcceptanceFinding],
    ledger: &FindingRepairLedger,
    fail_revision: Option<&str>,
    apply_revision: Option<&str>,
    changed_files: &[String],
    remediation_evidence: &[String],
) -> RepairGateDecision {
    let coverage = evaluate_remediation_coverage(findings, changed_files);
    if coverage.is_complete() {
        return RepairGateDecision::Proceed;
    }
    let uncovered = coverage.uncovered().join(", ");
    RepairGateDecision::Stop(Box::new(AcceptanceRepairStop {
        change_id: change_id.to_string(),
        reason: REMEDIATION_MISMATCH_REASON,
        findings: findings.to_vec(),
        occurrences: ledger.occurrence_report(),
        repeated_identities: Vec::new(),
        fail_revision: fail_revision.map(str::to_string),
        apply_revision: apply_revision.map(str::to_string),
        required_files: declared_files(findings, true),
        verification_files: declared_files(findings, false),
        coverage,
        remediation_evidence: remediation_evidence.to_vec(),
        resumable: true,
        next_action: format!(
            "Change the declared files still missing from the repair delta ({uncovered}), then \
             retry explicitly. Unrelated or comment-only changes cannot satisfy the finding \
             contract, and coverage alone never proves the finding is resolved."
        ),
    }))
}

/// Build the repeated-finding stop record for an ingested canonical FAIL.
#[allow(clippy::too_many_arguments)]
pub fn repeated_finding_stop(
    change_id: &str,
    findings: &[crate::acceptance::AcceptanceFinding],
    ledger: &FindingRepairLedger,
    repeated_identities: Vec<String>,
    fail_revision: Option<&str>,
    apply_revision: Option<&str>,
    changed_files: &[String],
    remediation_evidence: &[String],
) -> AcceptanceRepairStop {
    AcceptanceRepairStop {
        change_id: change_id.to_string(),
        reason: REPEATED_FINDING_REASON,
        findings: findings.to_vec(),
        occurrences: ledger.occurrence_report(),
        next_action: format!(
            "Finding {} is still open after its one automatic repair. Review the finding and the \
             recorded remediation evidence, then retry explicitly; unrelated changed files do not \
             grant another automatic repair.",
            repeated_identities.join(", ")
        ),
        repeated_identities,
        fail_revision: fail_revision.map(str::to_string),
        apply_revision: apply_revision.map(str::to_string),
        required_files: declared_files(findings, true),
        verification_files: declared_files(findings, false),
        coverage: evaluate_remediation_coverage(findings, changed_files),
        remediation_evidence: remediation_evidence.to_vec(),
        resumable: true,
    }
}

fn declared_files(
    findings: &[crate::acceptance::AcceptanceFinding],
    required: bool,
) -> Vec<String> {
    let mut files = findings
        .iter()
        .filter_map(|finding| finding.structured_payload())
        .flat_map(|finding| {
            if required {
                finding.required_files()
            } else {
                finding.verification_files()
            }
        })
        .collect::<Vec<_>>();
    files.sort();
    files.dedup();
    files
}

/// Collect the repair delta and Apply-authored remediation evidence for a
/// change, so both execution modes feed [`decide_repair_gate`] identically.
///
/// Missing git or follow-up state degrades to empty inputs rather than an
/// inferred pass: an empty delta simply fails coverage for a declared finding.
pub async fn collect_repair_gate_inputs(
    workspace: &std::path::Path,
    change_id: &str,
    fail_revision: Option<&str>,
) -> (Vec<String>, Option<String>, Vec<String>) {
    let changed_files = match fail_revision {
        Some(revision) => crate::vcs::git::commands::get_changed_files_since(workspace, revision)
            .await
            .unwrap_or_default(),
        None => Vec::new(),
    };
    let apply_revision = crate::vcs::git::commands::get_current_commit(workspace)
        .await
        .ok();
    let remediation_evidence =
        crate::task_parser::resolve_acceptance_follow_up_tasks_path(change_id, workspace)
            .ok()
            .and_then(|path| crate::task_parser::read_acceptance_follow_up_evidence(&path).ok())
            .unwrap_or_default();
    (changed_files, apply_revision, remediation_evidence)
}

pub fn decide_acceptance_retry(
    previous_identities: &[String],
    previous_fingerprint: Option<&str>,
    findings: &[NormalizedFinding],
    semantic_fingerprint: &str,
    cycle_count: u32,
) -> AcceptanceRetryDecision {
    let identities = findings
        .iter()
        .map(|finding| finding.identity.clone())
        .collect::<Vec<_>>();
    let external_blockers = findings
        .iter()
        .filter(|finding| finding.external)
        .map(|finding| finding.identity.clone())
        .collect();
    if cycle_count >= MAX_ACCEPTANCE_RETRY_CYCLES {
        return AcceptanceRetryDecision::Stall {
            reason: "acceptance_cycle_limit_exhausted",
            external_blockers,
        };
    }
    if !findings.is_empty() && findings.iter().all(|finding| finding.external) {
        return AcceptanceRetryDecision::Stall {
            reason: "external_acceptance_blocker",
            external_blockers,
        };
    }
    if previous_identities.is_empty() {
        return AcceptanceRetryDecision::Retry {
            reason: "first_acceptance_failure",
        };
    }
    if previous_identities != identities || previous_fingerprint != Some(semantic_fingerprint) {
        return AcceptanceRetryDecision::Retry {
            reason: "finding_or_semantic_progress_changed",
        };
    }
    AcceptanceRetryDecision::Stall {
        reason: "repeated_acceptance_findings",
        external_blockers,
    }
}

pub fn build_acceptance_tail_findings(
    stdout_tail: Option<String>,
    stderr_tail: Option<String>,
) -> Vec<String> {
    let stdout = stdout_tail.filter(|text| !text.trim().is_empty());
    let stderr = stderr_tail.filter(|text| !text.trim().is_empty());
    let selected = stdout
        .or(stderr)
        .unwrap_or_else(|| ACCEPTANCE_OUTPUT_FALLBACK.to_string());
    let lines = selected
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            // Filter out empty lines, ACCEPTANCE: markers, and FINDINGS: lines
            !trimmed.is_empty()
                && !trimmed.starts_with("ACCEPTANCE:")
                && !trimmed.starts_with("FINDINGS:")
        })
        .map(|line| line.to_string())
        .collect::<Vec<_>>();
    if lines.is_empty() {
        vec![ACCEPTANCE_OUTPUT_FALLBACK.to_string()]
    } else {
        lines
    }
}

/// Typed evidence for an Acceptance invocation stopped by its runtime limit.
///
/// Carries the configured limit that expired and the owned process group's
/// cleanup evidence, because "we stopped it" and "it is actually gone" are
/// separate facts and an unproven group must never be reported as quiescent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptanceRuntimeLimit {
    /// The effective absolute limit, in seconds, that this invocation exceeded.
    pub limit_secs: u64,
    /// Whether the owned process group was proven quiescent after termination.
    pub cleanup_confirmed: bool,
    /// One-line process-group cleanup diagnostics from the runner's own report.
    pub cleanup_diagnostics: String,
}

impl AcceptanceRuntimeLimit {
    /// Another attempt at the same invocation is never admissible.
    ///
    /// The limit is a boundary decision, not transient evidence: re-running it
    /// would re-run exactly the work the limit just stopped. Operator-triggered
    /// recovery stays explicit and repository-derived.
    pub fn permits_retry(&self) -> bool {
        false
    }

    /// Actionable operator-facing summary used as the workspace error text.
    pub fn summary(&self, change_id: &str) -> String {
        let cleanup = if self.cleanup_confirmed {
            "owned process group confirmed quiescent".to_string()
        } else {
            format!(
                "owned process group NOT confirmed quiescent — {}",
                self.cleanup_diagnostics
            )
        };
        format!(
            "Acceptance for '{}' was terminated by its absolute runtime limit of {}s \
             (`acceptance_max_runtime_secs`); {}. This invocation is not retried automatically: \
             it is not a PASS, not an external block, not an inactivity timeout, and not a \
             missing-verdict continuation. Reduce the proposal's Acceptance scope or raise \
             `acceptance_max_runtime_secs`, then retry explicitly.",
            change_id, self.limit_secs, cleanup
        )
    }
}

/// Classify one Acceptance invocation's typed termination.
///
/// Returns `Some` only for absolute-runtime-limit expiry. Every other reason —
/// an ordinary exit, an inactivity timeout, cancellation, or an invocation that
/// never started — keeps its existing routing, so this can never turn a verdict
/// or an operator stop into a runtime-limit failure. The reason is read from the
/// runner's typed termination rather than inferred from the exit status, because
/// a SIGKILLed agent reports the same status a crash does.
pub fn classify_acceptance_runtime_limit(
    termination: crate::process_manager::CommandTermination,
    limit_secs: u64,
    cleanup: &crate::process_manager::ProcessGroupCleanupReport,
) -> Option<AcceptanceRuntimeLimit> {
    if !termination.is_runtime_limit() {
        return None;
    }
    Some(AcceptanceRuntimeLimit {
        limit_secs,
        cleanup_confirmed: cleanup.is_confirmed(),
        cleanup_diagnostics: cleanup.diagnostics(),
    })
}

/// Result of an acceptance operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceResult {
    /// Acceptance passed - can proceed to archive.
    Pass,
    /// Acceptance failed - must return to apply loop.
    Fail {
        findings: Vec<crate::acceptance::AcceptanceFinding>,
    },
    /// Acceptance requires more investigation - retry acceptance.
    Continue,
    /// A FAIL verdict carried a structured `findings` entry that did not
    /// validate. Bounded protocol error: acceptance is re-invoked for a
    /// corrected verdict and no ambiguous repair work is dispatched.
    MalformedFinding {
        rejection: crate::acceptance::FindingRejection,
    },
    /// A `gated`/legacy `blocked` compatibility token arrived without a
    /// validated structured blocker. This is a bounded protocol error: it never
    /// creates a stalled lifecycle transition, blocker category, or durable
    /// record, and it never reruns apply.
    BareBlocker {
        rejection: crate::acceptance::BlockerRejection,
    },
    /// A validated structured external blocker - enter the non-terminal
    /// `stalled` hold and stop the apply loop.
    Stalled {
        blocker: crate::acceptance::AcceptanceBlocker,
    },
    /// Acceptance command execution failed (non-zero exit).
    ///
    /// `diagnostic` carries the bounded, latest-only Conflux-managed transport
    /// evidence used by the shared command-failure recovery policy. It is never
    /// a verdict and never becomes a FAIL finding payload.
    CommandFailed {
        error: String,
        findings: Vec<String>,
        diagnostic: AcceptanceCommandDiagnostic,
    },
    /// Acceptance detected a repeated unresolved permission/policy blocker.
    PermissionStalled {
        blocker: crate::events::StalledBlocker,
    },
    /// Acceptance command completed without emitting any canonical verdict.
    /// This is a protocol failure (for example a status-only "waiting for
    /// verification" exit) and is intentionally distinct from an explicit
    /// canonical `Continue`; it must never consume the explicit-CONTINUE
    /// retry path.
    MissingVerdict { findings: Vec<String> },
    /// Acceptance exceeded its own absolute runtime limit and was terminated.
    ///
    /// Terminal for this invocation and deliberately distinct from every other
    /// variant: it is not a verdict, so it never reaches verdict routing; it is
    /// not `CommandFailed`, so it never consumes command-recovery retry; it is
    /// not `MissingVerdict`, so it never enters no-verdict protocol
    /// continuation; and it is not `Cancelled`, so an operator stop and a
    /// runaway Acceptance stay distinguishable in reporting.
    RuntimeLimit { limit: AcceptanceRuntimeLimit },
    /// The bounded Acceptance boundary settled without a verdict and without an
    /// external prerequisite: a non-resumable execution hold.
    ///
    /// This is the variant that makes [`AcceptanceResult::RuntimeLimit`] rare.
    /// A declared gate that ran out of shared budget, a reviewer that reached
    /// the reserved finalization window with no canonical verdict, an unproven
    /// process group, a malformed manifest, or a runtime defect all settle here
    /// *before* the outer absolute limit, carrying a stable category and the
    /// input fingerprint that refuses an unchanged retry. The outer runtime
    /// limit remains only a defect-containment fallback.
    ///
    /// Not a verdict: a review that ran out of time says nothing about whether
    /// the implementation is correct, so this never reaches verdict routing and
    /// never enters missing-verdict continuation.
    ExecutionHold {
        hold: execution_manifest::AcceptanceExecutionHold,
    },
    /// Acceptance was cancelled (e.g., by user or timeout).
    Cancelled,
}

impl AcceptanceResult {
    /// Returns true if acceptance passed.
    pub fn is_pass(&self) -> bool {
        matches!(self, AcceptanceResult::Pass)
    }

    /// Returns true when the acceptance command emitted a canonical verdict
    /// (PASS/FAIL/CONTINUE/validated-stall/permission-stall).
    ///
    /// A missing verdict and a bare blocker are protocol failures, and command
    /// failure and cancellation are not verdicts at all: none of them are
    /// canonical, so none of them reset or consume a protocol retry budget
    /// other than their own.
    pub fn is_canonical_verdict(&self) -> bool {
        matches!(
            self,
            AcceptanceResult::Pass
                | AcceptanceResult::Fail { .. }
                | AcceptanceResult::Continue
                | AcceptanceResult::Stalled { .. }
                | AcceptanceResult::PermissionStalled { .. }
        )
    }

    /// Returns true when this invocation was stopped by its absolute runtime
    /// limit.
    pub fn is_runtime_limit(&self) -> bool {
        matches!(self, AcceptanceResult::RuntimeLimit { .. })
    }

    /// Whether another Acceptance invocation for the same work is admissible in
    /// the active run.
    ///
    /// Deliberate terminations — the absolute runtime limit and cancellation —
    /// are decisions rather than transient evidence, so neither is re-dispatched
    /// automatically. Every other result keeps its own existing routing.
    pub fn permits_acceptance_retry(&self) -> bool {
        !matches!(
            self,
            AcceptanceResult::RuntimeLimit { .. }
                | AcceptanceResult::Cancelled
                | AcceptanceResult::ExecutionHold { .. }
        )
    }

    /// Returns true when this invocation settled as a non-resumable bounded
    /// execution hold.
    pub fn is_execution_hold(&self) -> bool {
        matches!(self, AcceptanceResult::ExecutionHold { .. })
    }
}

/// Run acceptance test for a change with streaming output.
///
/// # Arguments
/// * `change` - The change to test
/// * `agent` - The agent runner for history tracking
/// * `ai_runner` - The AI command runner for command execution
/// * `config` - Orchestrator configuration
/// * `output` - Output handler for streaming command output
/// * `cancel_check` - Function to check if operation should be cancelled
///
/// # Returns
/// * `Ok((AcceptanceResult::Pass, attempt_number))` - Acceptance passed
/// * `Ok((AcceptanceResult::Fail { findings }, attempt_number))` - Acceptance failed with findings
/// * `Ok((AcceptanceResult::CommandFailed { error, findings }, attempt_number))` - Command execution failed
/// * `Ok((AcceptanceResult::Cancelled, attempt_number))` - Operation was cancelled
/// * `Err(e)` - An error occurred
///
/// The attempt_number is the number of the acceptance attempt that was just recorded.
///
/// `protocol_retry` is `Some` only when this invocation continues a previous
/// attempt that exited without a canonical verdict.
///
/// `previous_denial` carries the permission/tool-policy denial classified from
/// the immediately preceding invocation, if any. The same signature observed
/// again against an unchanged revision is a repeated unresolved denial, which
/// enters the existing non-terminal hold instead of consuming corrective command
/// retries — the same rule parallel acceptance already applies.
#[allow(clippy::too_many_arguments)]
pub async fn acceptance_test_streaming<O, F>(
    change: &Change,
    agent: &mut AgentRunner,
    ai_runner: &crate::ai_command_runner::AiCommandRunner,
    _config: &crate::config::OrchestratorConfig,
    output: &O,
    cancel_check: F,
    protocol_retry: Option<AcceptanceProtocolRetry>,
    previous_denial: Option<&crate::permission::PermissionDenial>,
    command_mode: AcceptanceCommandMode,
) -> Result<(AcceptanceResult, u32, String)>
where
    O: OutputHandler,
    F: Fn() -> bool,
{
    use crate::agent::OutputLine;

    info!("Running acceptance test for: {}", change.id);
    output.on_info(&format!("Acceptance test: {}", change.id));

    // Capture current commit hash for diff tracking
    let commit_hash = crate::vcs::git::commands::get_current_commit(".")
        .await
        .ok(); // Allow to fail silently (non-git repos)

    // Get current branch for diff context (first acceptance needs base branch)
    let base_branch = crate::vcs::git::commands::get_current_branch(".")
        .await
        .ok()
        .flatten(); // None if in detached HEAD or non-git repo

    // Execute acceptance command with streaming via AiCommandRunner (real process handle)
    let (mut child, mut output_rx, start_time, command) = agent
        .run_acceptance_streaming_with_runner(
            &change.id,
            ai_runner,
            None,
            base_branch.as_deref(),
            protocol_retry,
            command_mode,
        )
        .await?;

    // Log acceptance started with command
    output.on_info(&format!("Acceptance started: {}", change.id));
    output.on_info(&format!(
        "  {}",
        crate::events::command_log_summary(&command)
    ));

    // Create output collector for history and parsing
    let mut output_collector = OutputCollector::new();
    let mut full_stdout = String::new();

    // Grace period after detecting an acceptance marker before terminating the process.
    // This handles the case where the agent process (or its child processes) does not exit
    // promptly after emitting ACCEPTANCE: PASS/FAIL/etc., for example because
    // child processes (MCP servers) keep stdout/stderr pipes open.
    const MARKER_GRACE_PERIOD: std::time::Duration = std::time::Duration::from_secs(30);

    // Stream output until channel closes or acceptance marker detected + grace period
    let mut marker_detected = false;
    let mut verdict_stream_detector = crate::acceptance::VerdictStreamDetector::default();
    let mut marker_deadline: Option<tokio::time::Instant> = None;
    let mut early_terminated = false;

    loop {
        let recv_future = output_rx.recv();

        let line = if let Some(deadline) = marker_deadline {
            // After marker detection, apply a timeout for remaining output
            match tokio::time::timeout_at(deadline, recv_future).await {
                Ok(Some(line)) => line,
                Ok(None) => break, // Channel closed normally
                Err(_) => {
                    // Grace period expired — terminate the process
                    warn!(
                        "Acceptance marker grace period expired for {}, terminating process",
                        change.id
                    );
                    let _ = child.terminate();
                    early_terminated = true;
                    break;
                }
            }
        } else {
            match tokio::time::timeout(std::time::Duration::from_millis(50), recv_future).await {
                Ok(Some(line)) => line,
                Ok(None) => break, // Channel closed normally
                Err(_) => {
                    if cancel_check() {
                        warn!("Acceptance test cancelled while waiting for output");
                        output.on_warn("Acceptance test cancelled");
                        let _ = child.terminate();
                        return Ok((AcceptanceResult::Cancelled, 0, command));
                    }
                    continue;
                }
            }
        };

        // Check for cancellation
        if cancel_check() {
            warn!("Acceptance test cancelled for: {}", change.id);
            output.on_warn("Acceptance test cancelled");
            let _ = child.terminate();
            // Note: For cancellation, we don't record an attempt, so return 0
            return Ok((AcceptanceResult::Cancelled, 0, command));
        }

        match line {
            OutputLine::Stdout(s) => {
                output_collector.add_stdout(&s);
                full_stdout.push_str(&s);
                full_stdout.push('\n');
                output.on_stdout(&s);

                // Detect a canonical verdict in stdout to start the grace
                // period. This prevents indefinite blocking when the agent
                // process does not exit after emitting the verdict. The
                // detector recognises the primary strict JSON verdict (as a
                // standalone line or wrapped in a supported agent JSONL event)
                // and, as fallback, the legacy standalone plain-text
                // marker. Malformed markers with trailing text (for example
                // "ACCEPTANCE: PASSAll ...") do NOT trigger early completion.
                if !marker_detected && verdict_stream_detector.detect(&s).is_some() {
                    marker_detected = true;
                    marker_deadline = Some(tokio::time::Instant::now() + MARKER_GRACE_PERIOD);
                    info!(
                        "Acceptance canonical verdict detected for {}, starting {}s grace period",
                        change.id,
                        MARKER_GRACE_PERIOD.as_secs()
                    );
                }
            }
            OutputLine::Stderr(s) => {
                output_collector.add_stderr(&s);
                output.on_agent_stderr(&s);
            }
        }
    }

    // Child has exited, wait for status. Keep this cancellation-aware because
    // the output channel may close before the process status is reaped.
    let status = loop {
        if cancel_check() {
            warn!(
                "Acceptance test cancelled while waiting for child status for: {}",
                change.id
            );
            output.on_warn("Acceptance test cancelled");
            let _ = child.terminate();
            return Ok((AcceptanceResult::Cancelled, 0, command));
        }

        match tokio::time::timeout(std::time::Duration::from_millis(50), child.wait()).await {
            Ok(status) => {
                break status.map_err(|e| {
                    OrchestratorError::AgentCommand(format!(
                        "Failed to wait for acceptance command for change '{}': {}",
                        change.id, e
                    ))
                })?;
            }
            Err(_) => continue,
        }
    };

    // Record attempt
    let stdout_tail = output_collector.stdout_tail();
    let stderr_tail = output_collector.stderr_tail();

    // Build tail findings for history recording (last N lines, used in AcceptanceAttempt).
    let tail_findings = build_acceptance_tail_findings(stdout_tail.clone(), stderr_tail.clone());

    // A verdict-finalized run is one we terminated after observing the
    // canonical standalone verdict. The non-zero exit from termination is
    // expected — the verdict drives the final result.
    let verdict_finalized_run = early_terminated && marker_detected;

    // Check if command failed (skip when verdict already finalized).
    if !status.success() && !verdict_finalized_run {
        let error_msg = format!(
            "Acceptance command failed with exit code: {:?}",
            status.code()
        );
        output.on_error(&error_msg);

        // A command that never completed produced no verdict, so it produces no
        // canonical `AcceptanceAttempt`: transport evidence must not enter
        // Acceptance history, where it would be replayed as previous findings
        // and would consume attempt numbering. The bounded diagnosis below is
        // the only place this output is carried, and the shared command-recovery
        // policy renders it as untrusted latest-only context.
        let diagnostic = AcceptanceCommandDiagnostic {
            error: error_msg.clone(),
            exit_code: status.code(),
            stdout_tail,
            stderr_tail,
        };

        // Permission/tool-policy denial is classified before generic command
        // recovery, exactly as parallel acceptance does: a repeated unresolved
        // denial against an unchanged revision is not a transient crash, so it
        // enters the existing non-terminal hold instead of spending corrective
        // command retries.
        if let Some(denial) = classify_acceptance_command_denial(&diagnostic) {
            let end_commit_hash = crate::vcs::git::commands::get_current_commit(".")
                .await
                .ok();
            // "Unchanged" means no evidence that the workspace moved: two
            // unresolvable revisions (a non-Git checkout) compare equal, while a
            // revision that resolved on only one side is treated as movement.
            let revision_unchanged = commit_hash == end_commit_hash;
            let repeated_unresolved = previous_denial
                .is_some_and(|previous| previous.signature() == denial.signature())
                && revision_unchanged;
            if repeated_unresolved {
                warn!(
                    change_id = %change.id,
                    category = denial.category.as_str(),
                    denied_target = %denial.denied_target,
                    "Repeated unresolved permission/tool policy denial during acceptance; entering non-terminal hold without a corrective command retry"
                );
                return Ok((
                    AcceptanceResult::PermissionStalled {
                        blocker: crate::events::StalledBlocker::permission_denial(
                            "acceptance",
                            &denial,
                        ),
                    },
                    0,
                    command,
                ));
            }
        }

        return Ok((
            AcceptanceResult::CommandFailed {
                error: error_msg,
                findings: tail_findings,
                diagnostic,
            },
            // No canonical attempt was recorded, so no attempt number is
            // reported — the same contract cancellation already uses.
            0,
            command,
        ));
    }

    // Parse acceptance output to determine result
    let parsed_result = crate::acceptance::parse_acceptance_output(&full_stdout);

    let (result, passed) = match parsed_result {
        crate::acceptance::AcceptanceResult::Pass => {
            info!("Acceptance test passed for: {}", change.id);
            output.on_info("Acceptance test: PASS");
            (AcceptanceResult::Pass, true)
        }
        crate::acceptance::AcceptanceResult::Fail {
            findings: parsed_findings,
        } => {
            info!("Acceptance test failed for: {}", change.id);
            output.on_warn("Acceptance test: FAIL");
            let findings = if parsed_findings.is_empty() {
                crate::acceptance::legacy_findings([GENERIC_ACCEPTANCE_FAIL_FINDING])
            } else {
                parsed_findings
            };
            (AcceptanceResult::Fail { findings }, false)
        }
        crate::acceptance::AcceptanceResult::Continue => {
            info!("Acceptance requires continuation for: {}", change.id);
            output.on_info("Acceptance test: CONTINUE");
            (AcceptanceResult::Continue, false)
        }
        crate::acceptance::AcceptanceResult::Stalled { blocker } => {
            info!(
                "Acceptance reported a validated external blocker for: {} (category {})",
                change.id, blocker.category
            );
            output.on_warn(&format!(
                "Acceptance test: STALLED ({}) - {}",
                blocker.category, blocker.next_action
            ));
            (AcceptanceResult::Stalled { blocker }, false)
        }
        crate::acceptance::AcceptanceResult::MalformedFinding { rejection } => {
            warn!(
                "Acceptance emitted a malformed structured finding for: {} ({})",
                change.id,
                rejection.reason()
            );
            output.on_error(&format!(
                "Acceptance test: MALFORMED FINDING (protocol failure — {})",
                rejection.reason()
            ));
            (AcceptanceResult::MalformedFinding { rejection }, false)
        }
        crate::acceptance::AcceptanceResult::BareBlocker { rejection } => {
            warn!(
                "Acceptance emitted a bare blocker compatibility token for: {} ({})",
                change.id,
                rejection.reason()
            );
            output.on_error(&format!(
                "Acceptance test: BARE BLOCKER (protocol failure — {})",
                rejection.reason()
            ));
            (AcceptanceResult::BareBlocker { rejection }, false)
        }
        crate::acceptance::AcceptanceResult::MissingVerdict => {
            warn!(
                "Acceptance completed without a canonical verdict for: {} (missing-verdict protocol failure)",
                change.id
            );
            output.on_error("Acceptance test: MISSING VERDICT (protocol failure — the acceptance command exited without a canonical verdict; status-only or waiting output is not a verdict)");
            (
                AcceptanceResult::MissingVerdict {
                    findings: tail_findings.clone(),
                },
                false,
            )
        }
    };

    let history_findings = match &result {
        AcceptanceResult::Fail { findings } => Some(findings.clone()),
        AcceptanceResult::Continue => Some(crate::acceptance::legacy_findings([
            "Investigation incomplete - continue later",
        ])),
        AcceptanceResult::Stalled { blocker } => {
            let mut evidence = vec![format!(
                "Validated external blocker (category {}): {}",
                blocker.category, blocker.next_action
            )];
            evidence.extend(blocker.evidence.iter().cloned());
            Some(crate::acceptance::legacy_findings(evidence))
        }
        AcceptanceResult::BareBlocker { rejection } => Some(crate::acceptance::legacy_findings([
            BARE_BLOCKER_DIAGNOSTIC.to_string(),
            rejection.reason(),
        ])),
        AcceptanceResult::MalformedFinding { rejection } => {
            Some(crate::acceptance::legacy_findings([
                MALFORMED_FINDING_DIAGNOSTIC.to_string(),
                rejection.reason(),
            ]))
        }
        AcceptanceResult::Pass => None,
        AcceptanceResult::MissingVerdict { findings } => {
            let mut evidence = vec![MISSING_VERDICT_DIAGNOSTIC.to_string()];
            evidence.extend(findings.iter().cloned());
            Some(crate::acceptance::legacy_findings(evidence))
        }
        // Unreachable by construction: verdict parsing never produces a runtime
        // limit, which is classified from the runner's typed termination before
        // any output is parsed. A terminated invocation carries no findings.
        AcceptanceResult::RuntimeLimit { .. } => None,
        // Same reason: the bounded execution hold is decided by the runtime
        // before or instead of verdict parsing, so it records no canonical
        // attempt and contributes no findings.
        AcceptanceResult::ExecutionHold { .. } => None,
        AcceptanceResult::CommandFailed { .. }
        | AcceptanceResult::PermissionStalled { .. }
        | AcceptanceResult::Cancelled => {
            Some(crate::acceptance::legacy_findings(tail_findings.clone()))
        }
    };
    let attempt_number = agent.next_acceptance_attempt_number(&change.id);
    let attempt = AcceptanceAttempt {
        attempt: attempt_number,
        passed,
        duration: start_time.elapsed(),
        findings: history_findings,
        exit_code: status.code(),
        stdout_tail,
        stderr_tail,
        commit_hash: commit_hash.clone(),
    };
    agent.record_acceptance_attempt(&change.id, attempt);
    match &result {
        AcceptanceResult::Fail { findings } => {
            if !findings.is_empty() {
                agent.record_acceptance_follow_up(&change.id, attempt_number, findings.clone());
            }
        }
        AcceptanceResult::Pass => agent.clear_acceptance_follow_up(&change.id),
        _ => {}
    }
    Ok((result, attempt_number, command))
}

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

    // === Acceptance absolute runtime limit ===

    /// Acceptance is a reviewer, not an implementation worker, so it carries a
    /// dedicated non-disableable deadline. Every claim here is about a decision,
    /// so nothing in this module spawns a process or reads a configuration file;
    /// the real-process enforcement of that decision lives in
    /// `tests/process_cleanup_test.rs`.
    mod runtime_limit {
        use super::super::*;
        use crate::process_manager::{
            CommandTermination, ProcessGroupCleanupReport, ProcessGroupQuiescence,
        };

        const ACCEPTANCE_DEFAULT: u64 = 1_800;
        const COMMON_DEFAULT: u64 = 10_800;

        fn confirmed_cleanup() -> ProcessGroupCleanupReport {
            ProcessGroupCleanupReport::for_test(
                ProcessGroupQuiescence::Confirmed,
                Some(4242),
                "group empty after SIGTERM",
            )
        }

        fn unprovable_cleanup() -> ProcessGroupCleanupReport {
            ProcessGroupCleanupReport::for_test(
                ProcessGroupQuiescence::Unverifiable,
                Some(4242),
                "a SIGTERM-immune descendant outlived the verification budget",
            )
        }

        /// One runner bounds Acceptance and every other command class at once.
        ///
        /// There is no forked Acceptance runner to build and no per-call-site
        /// limit to pass: the class-specific deadline is selected from the
        /// operation type, so the *same* runner reports 1,800 seconds for
        /// Acceptance and the untouched common limit for everything else.
        #[test]
        fn routing_bounds_acceptance_without_moving_other_command_classes() {
            use crate::ai_command_runner::AiCommandRunner;
            use crate::command_queue::ACCEPTANCE_OPERATION_TYPE;
            use crate::config::OrchestratorConfig;
            use std::sync::Arc;
            use tokio::sync::Mutex;

            let config = OrchestratorConfig {
                command_max_runtime_secs: Some(COMMON_DEFAULT),
                acceptance_max_runtime_secs: Some(ACCEPTANCE_DEFAULT),
                command_inactivity_timeout_secs: Some(900),
                ..OrchestratorConfig::default()
            };
            let runner =
                AiCommandRunner::from_orchestrator_config(&config, Arc::new(Mutex::new(None)));
            let queue = runner.queue_config();

            assert_eq!(
                queue.effective_max_runtime_secs(Some(ACCEPTANCE_OPERATION_TYPE)),
                ACCEPTANCE_DEFAULT,
                "the Acceptance invocation runs under the dedicated limit"
            );
            for class in [
                Some("apply"),
                Some("archive"),
                Some("analyze"),
                Some("resolve"),
                Some("cleanup-review"),
                None,
            ] {
                assert_eq!(
                    queue.effective_max_runtime_secs(class),
                    COMMON_DEFAULT,
                    "{class:?} keeps `command_max_runtime_secs`"
                );
            }
            assert_eq!(
                queue.max_runtime_secs, COMMON_DEFAULT,
                "the stored common limit is never rewritten for one command class"
            );
        }

        /// Only the runtime limit classifies as one. A SIGKILLed agent, an agent
        /// that crashed, and an agent an operator stopped all report a non-zero
        /// status, so the reason has to come from the typed termination.
        #[test]
        fn only_runtime_limit_termination_classifies_as_one() {
            for termination in [
                CommandTermination::Exited,
                CommandTermination::InactivityTimeout,
                CommandTermination::Cancelled,
                CommandTermination::NotStarted,
            ] {
                assert!(
                    classify_acceptance_runtime_limit(
                        termination,
                        ACCEPTANCE_DEFAULT,
                        &confirmed_cleanup(),
                    )
                    .is_none(),
                    "{} must keep its own routing",
                    termination.as_str()
                );
            }

            let limit = classify_acceptance_runtime_limit(
                CommandTermination::RuntimeLimit,
                ACCEPTANCE_DEFAULT,
                &confirmed_cleanup(),
            )
            .expect("runtime-limit termination classifies as a runtime limit");
            assert_eq!(limit.limit_secs, ACCEPTANCE_DEFAULT);
            assert!(limit.cleanup_confirmed);
        }

        /// Expiry is a boundary decision, so the same invocation is never
        /// re-dispatched, and the operator-facing text has to name both the knob
        /// and that decision.
        #[test]
        fn expiry_is_terminal_for_the_invocation_and_says_so() {
            let limit = classify_acceptance_runtime_limit(
                CommandTermination::RuntimeLimit,
                ACCEPTANCE_DEFAULT,
                &confirmed_cleanup(),
            )
            .expect("classified");

            assert!(
                !limit.permits_retry(),
                "a timed-out Acceptance invocation is never retried automatically"
            );

            let summary = limit.summary("change-a");
            assert!(summary.contains("1800s"), "the configured limit: {summary}");
            assert!(
                summary.contains("acceptance_max_runtime_secs"),
                "the knob an operator has to change: {summary}"
            );
            assert!(
                summary.contains("not retried automatically"),
                "the retry decision must be visible: {summary}"
            );
            assert!(
                summary.contains("change-a"),
                "the affected proposal: {summary}"
            );
        }

        /// Terminating is not the same fact as proving the group is gone. An
        /// unprovable sweep is reported, never acknowledged as quiescence.
        #[test]
        fn cleanup_failure_is_not_hidden() {
            let limit = classify_acceptance_runtime_limit(
                CommandTermination::RuntimeLimit,
                ACCEPTANCE_DEFAULT,
                &unprovable_cleanup(),
            )
            .expect("classified");

            assert!(
                !limit.cleanup_confirmed,
                "an unswept owned group must never count as quiescent"
            );
            assert!(
                limit.cleanup_diagnostics.contains("SIGTERM-immune"),
                "the runner's own evidence must survive: {}",
                limit.cleanup_diagnostics
            );

            let summary = limit.summary("change-a");
            assert!(
                summary.contains("NOT confirmed quiescent"),
                "unproven cleanup must be stated, not implied: {summary}"
            );
            assert!(
                summary.contains("SIGTERM-immune"),
                "the actionable cleanup diagnostics must reach the operator: {summary}"
            );
            assert!(
                !limit.permits_retry(),
                "unprovable cleanup never converts the limit into a retry"
            );
        }

        /// The result must not be mistakable for a verdict, for cancellation, or
        /// for any of the bounded retry protocols keyed off the other variants.
        #[test]
        fn runtime_limit_is_its_own_terminal_result() {
            let limit = classify_acceptance_runtime_limit(
                CommandTermination::RuntimeLimit,
                ACCEPTANCE_DEFAULT,
                &confirmed_cleanup(),
            )
            .expect("classified");
            let result = AcceptanceResult::RuntimeLimit { limit };

            assert!(result.is_runtime_limit());
            assert!(
                !result.is_pass(),
                "a terminated invocation can never be a PASS"
            );
            assert!(
                !result.is_canonical_verdict(),
                "no verdict was emitted, so no verdict protocol may consume it"
            );
            assert!(
                !result.permits_acceptance_retry(),
                "the invocation that the limit stopped is not re-dispatched"
            );
            assert!(
                !matches!(
                    result,
                    AcceptanceResult::MissingVerdict { .. }
                        | AcceptanceResult::CommandFailed { .. }
                        | AcceptanceResult::Stalled { .. }
                        | AcceptanceResult::BareBlocker { .. }
                        | AcceptanceResult::PermissionStalled { .. }
                        | AcceptanceResult::Cancelled
                ),
                "runtime-limit expiry is not a missing verdict, a command failure, \
                 an external block, or a cancellation"
            );
        }

        /// Cancellation is the one other deliberate termination, and it keeps its
        /// own reporting: an operator stop and a runaway Acceptance must stay
        /// distinguishable even though neither is retried.
        #[test]
        fn cancellation_and_runtime_limit_stay_distinct() {
            assert!(!AcceptanceResult::Cancelled.is_runtime_limit());
            assert!(!AcceptanceResult::Cancelled.permits_acceptance_retry());
            assert!(
                AcceptanceResult::Pass.permits_acceptance_retry(),
                "only deliberate terminations close acceptance re-dispatch"
            );
            assert!(AcceptanceResult::MissingVerdict {
                findings: Vec::new()
            }
            .permits_acceptance_retry());
        }
    }

    // === Acceptance command-failure recovery ===

    mod command_recovery {
        use super::super::*;

        fn diagnostic(marker: &str) -> AcceptanceCommandDiagnostic {
            AcceptanceCommandDiagnostic {
                error: format!("Acceptance command failed with exit code: Some(1) [{marker}]"),
                exit_code: Some(1),
                stdout_tail: Some(format!("stdout {marker}")),
                stderr_tail: Some(format!("stderr {marker}")),
            }
        }

        fn agent() -> AgentRunner {
            AgentRunner::new(crate::config::OrchestratorConfig::default())
        }

        #[test]
        fn two_retries_follow_the_initial_failure_and_the_third_exhausts() {
            let mut counter = AcceptanceCommandRetryCounter::default();

            assert!(matches!(
                counter.record_command_failure(diagnostic("a")),
                AcceptanceCommandRetryDecision::Retry {
                    attempt: 1,
                    max_retries: 2,
                    ..
                }
            ));
            assert!(matches!(
                counter.record_command_failure(diagnostic("b")),
                AcceptanceCommandRetryDecision::Retry {
                    attempt: 2,
                    max_retries: 2,
                    ..
                }
            ));

            let third = counter.record_command_failure(diagnostic("c"));
            let AcceptanceCommandRetryDecision::Exhausted {
                attempts,
                max_retries,
                diagnostic,
            } = third
            else {
                panic!("the third consecutive command failure must exhaust the budget");
            };
            assert_eq!((attempts, max_retries), (3, MAX_ACCEPTANCE_COMMAND_RETRIES));
            assert!(
                diagnostic.error.contains("[c]"),
                "exhaustion reports the latest evidence, not the first: {diagnostic:?}"
            );
        }

        #[test]
        fn the_terminal_error_carries_attempt_count_and_latest_bounded_evidence() {
            let mut counter = AcceptanceCommandRetryCounter::default();
            counter.record_command_failure(diagnostic("a"));
            counter.record_command_failure(diagnostic("b"));
            let AcceptanceCommandRetryDecision::Exhausted {
                attempts,
                max_retries,
                diagnostic,
            } = counter.record_command_failure(diagnostic("c"))
            else {
                panic!("expected exhaustion");
            };

            let error = acceptance_command_exhausted_error(attempts, max_retries, &diagnostic);
            assert!(error.contains("3 consecutive attempts"), "{error}");
            assert!(error.contains("2 command-failure retries"), "{error}");
            assert!(error.contains("exit_code: 1"), "{error}");
            assert!(error.contains("stderr c"), "{error}");
            assert!(
                !error.contains("stderr a"),
                "only the latest evidence is reported: {error}"
            );
        }

        #[test]
        fn the_terminal_error_reports_exit_code_and_both_distinct_bounded_tails() {
            // Streams that disagree: the actionable diagnosis is on stdout while
            // stderr carries only an unrelated warning. Reporting one stream
            // would drop the diagnosis entirely.
            let diagnostic = AcceptanceCommandDiagnostic {
                error: "Acceptance command failed with exit code: Some(42)".to_string(),
                exit_code: Some(42),
                stdout_tail: Some(format!("the-actual-diagnosis {}", "s".repeat(10_000))),
                stderr_tail: Some(format!("unrelated-warning {}", "e".repeat(10_000))),
            };

            let error =
                acceptance_command_exhausted_error(3, MAX_ACCEPTANCE_COMMAND_RETRIES, &diagnostic);

            assert!(error.contains("exit_code: 42"), "{error}");
            assert!(
                error.contains("stdout: ") && error.contains("the-actual-diagnosis"),
                "the stdout tail must survive a present stderr: {error}"
            );
            assert!(
                error.contains("stderr: ") && error.contains("unrelated-warning"),
                "the stderr tail must be reported alongside stdout: {error}"
            );
            // Each stream is bounded on its own, so a flood on one cannot crowd
            // the other out of the terminal diagnostic.
            assert!(
                error.len() < 1_200,
                "both tails must stay bounded, got {} chars",
                error.len()
            );
        }

        #[test]
        fn retry_progress_also_reports_both_streams() {
            let diagnostic = AcceptanceCommandDiagnostic {
                error: "Acceptance command failed with exit code: Some(7)".to_string(),
                exit_code: Some(7),
                stdout_tail: Some("stdout-evidence".to_string()),
                stderr_tail: Some("stderr-evidence".to_string()),
            };

            let progress =
                acceptance_command_retry_progress(1, MAX_ACCEPTANCE_COMMAND_RETRIES, &diagnostic);

            assert!(progress.contains("stdout-evidence"), "{progress}");
            assert!(progress.contains("stderr-evidence"), "{progress}");
        }

        #[test]
        fn any_completed_non_command_failure_result_resets_the_sequence() {
            let mut counter = AcceptanceCommandRetryCounter::default();
            let mut agent = agent();

            // Every completed result kind ends consecutiveness, including the
            // protocol failures that keep their own independent budgets.
            for _ in 0..3 {
                counter.record_command_failure(diagnostic("a"));
                counter.record_command_failure(diagnostic("b"));
                assert_eq!(counter.consecutive_failures(), 2);

                observe_completed_acceptance_invocation(&mut counter, &mut agent, "change-a");
                assert_eq!(counter.consecutive_failures(), 0);
                assert!(agent.acceptance_command_recovery("change-a").is_none());
            }
        }

        #[test]
        fn protocol_completion_breaks_command_failure_consecutiveness() {
            let mut counter = AcceptanceCommandRetryCounter::default();
            let mut protocol = AcceptanceProtocolDriver::default();
            let mut agent = agent();

            // CommandFailed -> MissingVerdict -> CommandFailed.
            assert!(matches!(
                counter.record_command_failure(diagnostic("first")),
                AcceptanceCommandRetryDecision::Retry { attempt: 1, .. }
            ));

            // The completed missing-verdict invocation resets command recovery
            // first, then follows its own existing protocol accounting.
            observe_completed_acceptance_invocation(&mut counter, &mut agent, "change-a");
            let missing = protocol.observe_missing_verdict(&["waiting".to_string()]);
            assert!(matches!(missing, MissingVerdictRetryStep::Retry { .. }));

            assert!(
                matches!(
                    counter.record_command_failure(diagnostic("second")),
                    AcceptanceCommandRetryDecision::Retry { attempt: 1, .. }
                ),
                "the final command failure starts a new sequence"
            );
            assert_eq!(
                protocol.consecutive_missing_verdicts(),
                1,
                "the missing-verdict budget keeps its own independent accounting"
            );
        }

        #[test]
        fn budgets_stay_independent_when_one_is_exhausted() {
            let mut counter = AcceptanceCommandRetryCounter::default();
            let mut protocol = AcceptanceProtocolDriver::default();

            for _ in 0..3 {
                counter.record_command_failure(diagnostic("boom"));
            }

            assert_eq!(counter.consecutive_failures(), 3);
            assert_eq!(
                protocol.consecutive_missing_verdicts(),
                0,
                "command failures never consume the protocol budget"
            );
            assert_eq!(protocol.consecutive_bare_blockers(), 0);
            assert_eq!(protocol.consecutive_malformed_findings(), 0);
            assert!(
                protocol.take_protocol_retry().is_none(),
                "command failures never schedule a protocol continuation"
            );
        }

        #[test]
        fn the_shared_policy_stores_latest_only_prompt_context_and_clears_on_exhaustion() {
            let mut counter = AcceptanceCommandRetryCounter::default();
            let mut agent = agent();

            let first = decide_acceptance_command_failure(
                &mut counter,
                &mut agent,
                "change-a",
                diagnostic("a"),
            );
            assert!(matches!(
                first,
                AcceptanceCommandRecovery::Retry { attempt: 1, .. }
            ));
            assert!(agent
                .acceptance_command_recovery("change-a")
                .expect("a retry stores the latest diagnosis")
                .error
                .contains("[a]"));

            decide_acceptance_command_failure(
                &mut counter,
                &mut agent,
                "change-a",
                diagnostic("b"),
            );
            let stored = agent
                .acceptance_command_recovery("change-a")
                .expect("still recovering");
            assert!(stored.error.contains("[b]"), "{stored:?}");
            assert!(
                !stored.error.contains("[a]"),
                "prior command failures are never replayed: {stored:?}"
            );

            let third = decide_acceptance_command_failure(
                &mut counter,
                &mut agent,
                "change-a",
                diagnostic("c"),
            );
            let AcceptanceCommandRecovery::Exhausted { attempts, error } = third else {
                panic!("the third consecutive failure must exhaust");
            };
            assert_eq!(attempts, 3);
            assert!(error.contains("[c]"), "{error}");
            assert!(
                agent.acceptance_command_recovery("change-a").is_none(),
                "no further command retry follows exhaustion, so the context is cleared"
            );
        }

        #[test]
        fn command_recovery_context_is_tracked_per_change() {
            let mut counter_a = AcceptanceCommandRetryCounter::default();
            let mut counter_b = AcceptanceCommandRetryCounter::default();
            let mut agent = agent();

            decide_acceptance_command_failure(
                &mut counter_a,
                &mut agent,
                "change-a",
                diagnostic("a"),
            );
            decide_acceptance_command_failure(
                &mut counter_b,
                &mut agent,
                "change-b",
                diagnostic("b"),
            );

            observe_completed_acceptance_invocation(&mut counter_a, &mut agent, "change-a");

            assert!(agent.acceptance_command_recovery("change-a").is_none());
            assert!(
                agent.acceptance_command_recovery("change-b").is_some(),
                "one change's reset must not clear another change's context"
            );
        }

        #[test]
        fn the_progress_message_is_worded_as_recovery_not_failure() {
            let mut counter = AcceptanceCommandRetryCounter::default();
            let AcceptanceCommandRetryDecision::Retry {
                attempt,
                max_retries,
                diagnostic,
            } = counter.record_command_failure(diagnostic("a"))
            else {
                panic!("expected a retry");
            };

            let progress = acceptance_command_retry_progress(attempt, max_retries, &diagnostic);
            assert!(
                progress.contains("command-failure recovery 1/2"),
                "{progress}"
            );
            assert!(
                progress.contains("re-running only the configured acceptance command"),
                "{progress}"
            );
        }
    }

    /// A minimal validated external blocker, used wherever a canonical stalled
    /// verdict is needed.
    fn sample_blocker() -> crate::acceptance::AcceptanceBlocker {
        crate::acceptance::AcceptanceBlocker {
            category: "pending_verification".to_string(),
            evidence: vec!["managed verification job 42 is still running".to_string()],
            unblock_condition: "managed verification job 42 reports a terminal result".to_string(),
            next_action: "wait for job 42 then retry acceptance".to_string(),
            resumable: true,
            prerequisite_owner: None,
            evidence_ids: Vec::new(),
        }
    }

    fn bare_blocker() -> AcceptanceResult {
        AcceptanceResult::BareBlocker {
            rejection: crate::acceptance::BlockerRejection::Missing,
        }
    }

    /// Table-driven contract for the dedicated missing-verdict budget: the
    /// initial attempt plus two retries, then terminal exhaustion.
    #[test]
    fn missing_verdict_budget_allows_two_retries_then_exhausts() {
        let mut state = ProtocolRetryCounter::default();
        let expected = [
            MissingVerdictRetryDecision::Retry(AcceptanceProtocolRetry {
                kind: AcceptanceProtocolError::MissingVerdict,
                attempt: 1,
                max: 2,
            }),
            MissingVerdictRetryDecision::Retry(AcceptanceProtocolRetry {
                kind: AcceptanceProtocolError::MissingVerdict,
                attempt: 2,
                max: 2,
            }),
            MissingVerdictRetryDecision::Exhausted {
                kind: AcceptanceProtocolError::MissingVerdict,
                attempts: 3,
                max: 2,
            },
        ];

        for (index, want) in expected.iter().enumerate() {
            assert_eq!(
                state.record(AcceptanceProtocolError::MissingVerdict),
                *want,
                "consecutive missing verdict #{} must route as {:?}",
                index + 1,
                want
            );
        }
        assert_eq!(MAX_MISSING_VERDICT_RETRIES, 2);
        assert_eq!(
            state.consecutive(),
            3,
            "a fourth protocol retry must never be offered after exhaustion"
        );
        assert!(matches!(
            state.record(AcceptanceProtocolError::MissingVerdict),
            MissingVerdictRetryDecision::Exhausted { .. }
        ));
    }

    #[test]
    fn missing_verdict_canonical_verdict_resets_consecutive_sequence() {
        let mut state = ProtocolRetryCounter::default();
        assert!(matches!(
            state.record(AcceptanceProtocolError::MissingVerdict),
            MissingVerdictRetryDecision::Retry(AcceptanceProtocolRetry { attempt: 1, .. })
        ));
        assert!(matches!(
            state.record(AcceptanceProtocolError::MissingVerdict),
            MissingVerdictRetryDecision::Retry(AcceptanceProtocolRetry { attempt: 2, .. })
        ));

        // PASS/FAIL/CONTINUE/GATED/stalled-hold all reach this reset.
        state.reset();
        assert_eq!(state.consecutive(), 0);

        assert_eq!(
            state.record(AcceptanceProtocolError::MissingVerdict),
            MissingVerdictRetryDecision::Retry(AcceptanceProtocolRetry {
                kind: AcceptanceProtocolError::MissingVerdict,
                attempt: 1,
                max: 2
            }),
            "a later missing verdict must start a fresh protocol-retry sequence"
        );
    }

    /// The protocol budget is fixed and independent from the configured
    /// explicit-`CONTINUE` budget, whatever that budget is set to.
    #[test]
    fn missing_verdict_budget_is_independent_of_configured_continue_count() {
        for configured_continues in [0u32, 1, 5, 50] {
            let mut state = ProtocolRetryCounter::default();
            let mut retries = 0u32;
            loop {
                match state.record(AcceptanceProtocolError::MissingVerdict) {
                    MissingVerdictRetryDecision::Retry(retry) => {
                        assert_eq!(retry.max, MAX_MISSING_VERDICT_RETRIES);
                        retries += 1;
                    }
                    MissingVerdictRetryDecision::Exhausted { attempts, max, .. } => {
                        assert_eq!(attempts, MAX_MISSING_VERDICT_RETRIES + 1);
                        assert_eq!(max, MAX_MISSING_VERDICT_RETRIES);
                        break;
                    }
                }
            }
            assert_eq!(
                retries, MAX_MISSING_VERDICT_RETRIES,
                "configured acceptance_max_continues={configured_continues} must not change the \
                 dedicated missing-verdict budget"
            );
        }
    }

    #[test]
    fn missing_verdict_diagnostics_are_bounded_and_distinguish_progress_from_terminal() {
        let findings = (0..10)
            .map(|index| format!("evidence line {index}"))
            .collect::<Vec<_>>();

        let progress = missing_verdict_retry_progress(
            AcceptanceProtocolRetry {
                kind: AcceptanceProtocolError::MissingVerdict,
                attempt: 1,
                max: 2,
            },
            &findings,
        );
        assert!(progress.contains("protocol retry 1/2"));
        assert!(progress.contains("evidence line 4"));
        assert!(
            !progress.contains("evidence line 5"),
            "evidence must stay bounded to the first five findings, got {progress}"
        );
        assert!(
            !progress.to_ascii_lowercase().contains("protocol failure"),
            "an available retry must not read as a terminal failure: {progress}"
        );

        let terminal = missing_verdict_exhausted_error(3, 2, &findings);
        assert!(terminal.contains("missing-verdict protocol failure"));
        assert!(terminal.contains("Exhausted 3 consecutive attempts after 2 protocol retries"));
        assert!(terminal.contains("evidence line 4"));
        assert!(!terminal.contains("evidence line 5"));

        assert!(
            missing_verdict_exhausted_error(3, 2, &[]).contains("no acceptance output captured"),
            "empty evidence must still produce an actionable diagnostic"
        );
    }

    /// Replay an acceptance verdict sequence through the shared driver exactly
    /// as orchestration does, and report what each invocation
    /// received plus how the sequence terminated.
    fn replay_missing_verdict_sequence(
        sequence: &[AcceptanceResult],
    ) -> (
        Vec<Option<AcceptanceProtocolRetry>>,
        Option<AcceptanceResult>,
        Option<String>,
    ) {
        let mut protocol = AcceptanceProtocolDriver::default();
        let mut received = Vec::new();
        for result in sequence {
            received.push(protocol.take_protocol_retry());
            match result {
                AcceptanceResult::MissingVerdict { findings } => {
                    match protocol.observe_missing_verdict(findings) {
                        MissingVerdictRetryStep::Retry { .. } => continue,
                        MissingVerdictRetryStep::Exhausted { error } => {
                            return (received, None, Some(error))
                        }
                    }
                }
                canonical => {
                    protocol.observe_canonical_verdict();
                    return (received, Some(canonical.clone()), None);
                }
            }
        }
        (received, None, None)
    }

    fn missing_verdict(evidence: &str) -> AcceptanceResult {
        AcceptanceResult::MissingVerdict {
            findings: vec![evidence.to_string()],
        }
    }

    #[test]
    fn missing_verdict_driver_retries_twice_then_accepts_canonical_pass() {
        let (received, canonical, error) = replay_missing_verdict_sequence(&[
            missing_verdict("waiting for verification"),
            missing_verdict("still waiting"),
            AcceptanceResult::Pass,
        ]);

        assert_eq!(received.len(), 3, "acceptance must be invoked three times");
        assert_eq!(
            received,
            vec![
                None,
                Some(AcceptanceProtocolRetry {
                    kind: AcceptanceProtocolError::MissingVerdict,
                    attempt: 1,
                    max: 2
                }),
                Some(AcceptanceProtocolRetry {
                    kind: AcceptanceProtocolError::MissingVerdict,
                    attempt: 2,
                    max: 2
                }),
            ],
            "only the retries may carry a continuation marker"
        );
        assert_eq!(canonical, Some(AcceptanceResult::Pass));
        assert!(
            error.is_none(),
            "a canonical verdict within budget must not produce a terminal error"
        );
    }

    #[test]
    fn missing_verdict_driver_exhausts_after_three_consecutive_missing_verdicts() {
        let (received, canonical, error) = replay_missing_verdict_sequence(&[
            missing_verdict("waiting one"),
            missing_verdict("waiting two"),
            missing_verdict("waiting three"),
            missing_verdict("never reached"),
        ]);

        assert_eq!(
            received.len(),
            3,
            "no fourth protocol retry may start after exhaustion"
        );
        assert!(canonical.is_none());
        let error = error.expect("third consecutive missing verdict must be terminal");
        assert!(error.contains("missing-verdict protocol failure"));
        assert!(error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"));
        assert!(
            error.contains("waiting three"),
            "terminal diagnostic must carry bounded evidence, got {error}"
        );
    }

    /// Every canonical outcome — not just PASS — resets the protocol sequence
    /// and keeps its own routing untouched.
    #[test]
    fn missing_verdict_driver_treats_every_canonical_outcome_as_a_reset() {
        for canonical in [
            AcceptanceResult::Pass,
            AcceptanceResult::Fail {
                findings: vec!["src/lib.rs:1 fix".to_string().into()],
            },
            AcceptanceResult::Continue,
            AcceptanceResult::Stalled {
                blocker: sample_blocker(),
            },
            AcceptanceResult::PermissionStalled {
                blocker: crate::events::StalledBlocker::acceptance_external(
                    "pending_verification",
                    "denied",
                ),
            },
        ] {
            let mut protocol = AcceptanceProtocolDriver::default();
            assert!(matches!(
                protocol.observe_missing_verdict(&["waiting".to_string()]),
                MissingVerdictRetryStep::Retry { .. }
            ));
            assert!(protocol.take_protocol_retry().is_some());

            protocol.observe_canonical_verdict();
            assert_eq!(
                protocol.consecutive_missing_verdicts(),
                0,
                "{canonical:?} must reset the consecutive protocol counter"
            );
            assert!(
                protocol.take_protocol_retry().is_none(),
                "{canonical:?} must clear any pending continuation marker"
            );

            // The next protocol failure starts a fresh full budget.
            assert!(matches!(
                protocol.observe_missing_verdict(&["waiting again".to_string()]),
                MissingVerdictRetryStep::Retry {
                    retry: AcceptanceProtocolRetry { attempt: 1, .. },
                    ..
                }
            ));
        }
    }

    // --- Shared bare-blocker / validated-stall decision API ---

    fn drive_blockers(sequence: &[AcceptanceResult]) -> Vec<AcceptanceBlockerDecision> {
        let mut driver = AcceptanceProtocolDriver::default();
        let mut decisions = Vec::new();
        for result in sequence {
            if let Some(decision) = decide_acceptance_blocker(&mut driver, result) {
                decisions.push(decision);
            } else {
                driver.observe_canonical_verdict();
            }
        }
        decisions
    }

    /// Bare input gets the initial attempt plus exactly two acceptance-only
    /// retries, then a terminal protocol error. Nothing stalls, ever.
    #[test]
    fn bare_blocker_budget_allows_two_retries_then_exhausts() {
        let decisions = drive_blockers(&[bare_blocker(), bare_blocker(), bare_blocker()]);

        assert_eq!(decisions.len(), 3);
        for (index, expected_attempt) in [1u32, 2].iter().enumerate() {
            match &decisions[index] {
                AcceptanceBlockerDecision::ProtocolRetry { retry, progress } => {
                    assert_eq!(retry.kind, AcceptanceProtocolError::BareBlocker);
                    assert_eq!(retry.attempt, *expected_attempt);
                    assert_eq!(retry.max, MAX_ACCEPTANCE_PROTOCOL_RETRIES);
                    assert!(progress.contains("no validated blocker"), "{progress}");
                    assert!(
                        progress.contains("retrying acceptance")
                            && progress.contains(&format!("protocol retry {expected_attempt}/2")),
                        "an available retry must read as progress: {progress}"
                    );
                    assert!(
                        !progress.contains("Exhausted"),
                        "an available retry must be distinguishable from the terminal \
                         diagnostic: {progress}"
                    );
                }
                other => panic!("attempt {expected_attempt} must retry, got {other:?}"),
            }
        }
        match &decisions[2] {
            AcceptanceBlockerDecision::ProtocolExhausted { error } => {
                assert!(error.contains("bare-blocker protocol failure"), "{error}");
                assert!(
                    error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"),
                    "{error}"
                );
            }
            other => panic!("third consecutive bare blocker must be terminal, got {other:?}"),
        }
    }

    /// Every canonical outcome — including a validated stall — resets the
    /// bare-blocker sequence.
    #[test]
    fn canonical_verdict_resets_the_bare_blocker_sequence() {
        for canonical in [
            AcceptanceResult::Pass,
            AcceptanceResult::Fail {
                findings: vec!["src/lib.rs:1 fix".to_string().into()],
            },
            AcceptanceResult::Continue,
            AcceptanceResult::Stalled {
                blocker: sample_blocker(),
            },
        ] {
            let mut driver = AcceptanceProtocolDriver::default();
            for _ in 0..2 {
                assert!(matches!(
                    decide_acceptance_blocker(&mut driver, &bare_blocker()),
                    Some(AcceptanceBlockerDecision::ProtocolRetry { .. })
                ));
            }
            assert_eq!(driver.consecutive_bare_blockers(), 2);

            if decide_acceptance_blocker(&mut driver, &canonical).is_none() {
                driver.observe_canonical_verdict();
            }
            assert_eq!(
                driver.consecutive_bare_blockers(),
                0,
                "{canonical:?} must reset the consecutive bare-blocker counter"
            );
            assert!(
                driver.take_protocol_retry().is_none(),
                "{canonical:?} must clear any pending continuation marker"
            );

            assert!(
                matches!(
                    decide_acceptance_blocker(&mut driver, &bare_blocker()),
                    Some(AcceptanceBlockerDecision::ProtocolRetry {
                        retry: AcceptanceProtocolRetry { attempt: 1, .. },
                        ..
                    })
                ),
                "a later bare blocker must start a fresh full budget"
            );
        }
    }

    /// The two protocol contracts keep strictly independent counters, so a run
    /// cannot alternate between them to buy unbounded retries.
    #[test]
    fn bare_blocker_and_missing_verdict_budgets_are_independent_but_both_bounded() {
        let mut driver = AcceptanceProtocolDriver::default();

        assert!(matches!(
            decide_acceptance_blocker(&mut driver, &bare_blocker()),
            Some(AcceptanceBlockerDecision::ProtocolRetry { .. })
        ));
        assert!(matches!(
            driver.observe_missing_verdict(&["waiting".to_string()]),
            MissingVerdictRetryStep::Retry { .. }
        ));
        assert_eq!(driver.consecutive_bare_blockers(), 1);
        assert_eq!(driver.consecutive_missing_verdicts(), 1);

        // Neither protocol failure resets the other, so alternating still
        // exhausts both budgets rather than renewing them.
        assert!(matches!(
            decide_acceptance_blocker(&mut driver, &bare_blocker()),
            Some(AcceptanceBlockerDecision::ProtocolRetry { .. })
        ));
        assert!(matches!(
            decide_acceptance_blocker(&mut driver, &bare_blocker()),
            Some(AcceptanceBlockerDecision::ProtocolExhausted { .. })
        ));
        assert!(matches!(
            driver.observe_missing_verdict(&["waiting".to_string()]),
            MissingVerdictRetryStep::Retry { .. }
        ));
        assert!(matches!(
            driver.observe_missing_verdict(&["waiting".to_string()]),
            MissingVerdictRetryStep::Exhausted { .. }
        ));
    }

    /// Every structural rejection routes to the same bounded protocol path and
    /// never to a stall, and the diagnostic names the actual defect.
    #[test]
    fn every_invalid_blocker_payload_routes_to_bounded_protocol_retry() {
        use crate::acceptance::BlockerRejection;

        let rejections = [
            BlockerRejection::Missing,
            BlockerRejection::NotAnObject,
            BlockerRejection::MissingCategory,
            BlockerRejection::UnsupportedCategory("flaky_test".to_string()),
            BlockerRejection::EmptyEvidence,
            BlockerRejection::MissingNextAction,
            BlockerRejection::MissingResumable,
        ];

        for rejection in rejections {
            let mut driver = AcceptanceProtocolDriver::default();
            match decide_acceptance_blocker(
                &mut driver,
                &AcceptanceResult::BareBlocker {
                    rejection: rejection.clone(),
                },
            ) {
                Some(AcceptanceBlockerDecision::ProtocolRetry { progress, .. }) => {
                    assert!(
                        progress.contains(&rejection.reason()),
                        "diagnostic must name the defect ({rejection:?}): {progress}"
                    );
                }
                other => panic!("{rejection:?} must retry, got {other:?}"),
            }
        }
    }

    /// A validated blocker becomes a stall with its explicit category intact,
    /// and prose in the evidence never changes that category.
    #[test]
    fn validated_blocker_stalls_with_its_explicit_category_preserved() {
        let blocker = crate::acceptance::AcceptanceBlocker {
            category: "human_decision".to_string(),
            evidence: vec!["the credential token auth story needs an owner decision".to_string()],
            unblock_condition: "the architecture owner records a decision".to_string(),
            next_action: "owner decides the approach".to_string(),
            resumable: false,
            prerequisite_owner: Some("architecture".to_string()),
            evidence_ids: vec!["adr-7".to_string()],
        };
        let mut driver = AcceptanceProtocolDriver::default();

        match decide_acceptance_blocker(
            &mut driver,
            &AcceptanceResult::Stalled {
                blocker: blocker.clone(),
            },
        ) {
            Some(AcceptanceBlockerDecision::ExternalBlocker { blocker: stalled }) => {
                assert_eq!(stalled, blocker);
                assert_eq!(
                    stalled.category, "human_decision",
                    "credential/token/auth prose must not override the explicit category"
                );
            }
            other => panic!("a validated blocker must stall, got {other:?}"),
        }
    }

    /// The decision API owns only blocker-bearing results and leaves every other
    /// verdict's routing untouched.
    #[test]
    fn blocker_decision_api_ignores_non_blocker_results() {
        let mut driver = AcceptanceProtocolDriver::default();
        for result in [
            AcceptanceResult::Pass,
            AcceptanceResult::Fail {
                findings: Vec::new(),
            },
            AcceptanceResult::Continue,
            AcceptanceResult::MissingVerdict {
                findings: Vec::new(),
            },
            AcceptanceResult::CommandFailed {
                error: "exit 1".to_string(),
                findings: Vec::new(),
                diagnostic: AcceptanceCommandDiagnostic::default(),
            },
            AcceptanceResult::Cancelled,
        ] {
            assert!(
                decide_acceptance_blocker(&mut driver, &result).is_none(),
                "{result:?} must keep its own routing"
            );
        }
    }

    /// Every caller drives the same API, so identical observation
    /// sequences must produce identical decisions.
    #[test]
    fn bare_blocker_decisions_have_caller_parity() {
        let sequences: [Vec<AcceptanceResult>; 3] = [
            vec![bare_blocker(), bare_blocker(), AcceptanceResult::Pass],
            vec![bare_blocker(), bare_blocker(), bare_blocker()],
            vec![
                bare_blocker(),
                AcceptanceResult::Stalled {
                    blocker: sample_blocker(),
                },
                bare_blocker(),
            ],
        ];

        for sequence in sequences {
            let first = drive_blockers(&sequence);
            let parallel = drive_blockers(&sequence);
            assert_eq!(
                first, parallel,
                "equivalent observations must produce equivalent decisions for {sequence:?}"
            );
        }
    }

    /// Routing matrix: only canonical verdicts reset the protocol sequence,
    /// only a missing verdict may consume it, and command failure or
    /// cancellation is never reclassified as a missing-verdict retry.
    #[test]
    fn acceptance_routing_matrix_keeps_missing_verdict_distinct() {
        let cases: [(AcceptanceResult, bool, bool); 8] = [
            (AcceptanceResult::Pass, true, false),
            (
                AcceptanceResult::Fail {
                    findings: vec!["src/lib.rs:1 fix".to_string().into()],
                },
                true,
                false,
            ),
            (AcceptanceResult::Continue, true, false),
            (
                AcceptanceResult::Stalled {
                    blocker: sample_blocker(),
                },
                true,
                false,
            ),
            (
                AcceptanceResult::PermissionStalled {
                    blocker: crate::events::StalledBlocker::acceptance_external(
                        "pending_verification",
                        "denied",
                    ),
                },
                true,
                false,
            ),
            (missing_verdict("waiting"), false, true),
            (
                AcceptanceResult::CommandFailed {
                    error: "exit code 1".to_string(),
                    findings: vec!["boom".to_string()],
                    diagnostic: AcceptanceCommandDiagnostic::default(),
                },
                false,
                false,
            ),
            (AcceptanceResult::Cancelled, false, false),
        ];

        for (result, canonical, missing) in cases {
            assert_eq!(
                result.is_canonical_verdict(),
                canonical,
                "{result:?} canonical-verdict classification"
            );
            assert_eq!(
                matches!(result, AcceptanceResult::MissingVerdict { .. }),
                missing,
                "{result:?} must not be confused with a missing verdict"
            );
            assert!(
                !(canonical && missing),
                "{result:?} cannot be both canonical and a protocol failure"
            );
        }

        // Command failure keeps its own routing: it neither resets nor consumes
        // the protocol budget, so a later missing verdict still gets a full one.
        let mut protocol = AcceptanceProtocolDriver::default();
        for result in [
            AcceptanceResult::CommandFailed {
                error: "exit code 1".to_string(),
                findings: Vec::new(),
                diagnostic: AcceptanceCommandDiagnostic::default(),
            },
            AcceptanceResult::Cancelled,
        ] {
            assert!(!result.is_canonical_verdict());
            assert!(protocol.take_protocol_retry().is_none());
            assert_eq!(protocol.consecutive_missing_verdicts(), 0);
        }
        assert!(matches!(
            protocol.observe_missing_verdict(&["waiting".to_string()]),
            MissingVerdictRetryStep::Retry {
                retry: AcceptanceProtocolRetry {
                    kind: AcceptanceProtocolError::MissingVerdict,
                    attempt: 1,
                    max: 2
                },
                ..
            }
        ));
    }

    /// Every caller uses the same driver; equivalent observations must
    /// produce equivalent routing.
    #[test]
    fn missing_verdict_driver_has_caller_routing_parity() {
        let sequence = [
            missing_verdict("waiting"),
            missing_verdict("waiting"),
            AcceptanceResult::Fail {
                findings: vec!["src/lib.rs:1 missing coverage".to_string().into()],
            },
        ];

        let first = replay_missing_verdict_sequence(&sequence);
        let parallel = replay_missing_verdict_sequence(&sequence);
        assert_eq!(first, parallel);
        assert_eq!(first.0.len(), 3);
        assert!(matches!(first.1, Some(AcceptanceResult::Fail { .. })));
        assert!(first.2.is_none());
    }

    #[test]
    fn semantic_fingerprint_excludes_runtime_bookkeeping() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join("src")).unwrap();
        std::fs::write(temp.path().join("src/lib.rs"), "one").unwrap();
        let before = semantic_progress_fingerprint(temp.path()).unwrap();
        std::fs::create_dir_all(temp.path().join(".cflx")).unwrap();
        std::fs::write(temp.path().join(".cflx/runtime.json"), "runtime").unwrap();
        assert_eq!(before, semantic_progress_fingerprint(temp.path()).unwrap());
        std::fs::write(temp.path().join("src/lib.rs"), "two").unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
    }

    #[test]
    fn finding_identity_prefers_code_and_uses_structural_fallback() {
        let coded = normalize_findings(&[
            "[MISSING_RETRY_TEST] old evidence at src/run.rs:10".into(),
            "[MISSING_RETRY_TEST] changed summary at tests/run.rs:99".into(),
        ]);
        assert_eq!(coded.len(), 1);
        assert_eq!(coded[0].identity, "repository|code|[missing_retry_test]");

        let changed_detail = normalize_findings(&[
            "Missing retry test at src/run.rs:10 because the branch is uncovered".into(),
            "Regression coverage absent in src/run.rs:77; add a focused test".into(),
        ]);
        assert_eq!(changed_detail.len(), 1);
        assert_eq!(
            changed_detail[0].identity,
            "repository|src/run.rs|verification"
        );

        let distinct = normalize_findings(&[
            "Missing test at src/run.rs:10".into(),
            "Incorrect implementation at src/run.rs:11".into(),
            "Missing test at src/other.rs:10".into(),
        ]);
        assert_eq!(
            distinct.len(),
            3,
            "rule and location must prevent collisions"
        );
    }

    #[test]
    fn retry_decision_normalizes_order_whitespace_duplicates_and_stalls_repeats() {
        let findings = normalize_findings(&[
            " src/lib.rs:10   missing  test ".to_string().into(),
            "src/lib.rs:11 missing test".to_string().into(),
        ]);
        assert_eq!(findings.len(), 1);
        let decision = decide_acceptance_retry(
            &[findings[0].identity.clone()],
            Some("unchanged"),
            &findings,
            "unchanged",
            2,
        );
        assert!(matches!(
            decision,
            AcceptanceRetryDecision::Stall {
                reason: "repeated_acceptance_findings",
                ..
            }
        ));
    }

    #[test]
    fn retry_decision_stalls_external_only_and_allows_progress_changed() {
        let findings = normalize_findings(&["external service outage".to_string().into()]);
        assert!(findings[0].external);
        assert!(matches!(
            decide_acceptance_retry(&[], None, &findings, "one", 1),
            AcceptanceRetryDecision::Stall {
                reason: "external_acceptance_blocker",
                ..
            }
        ));
        assert!(
            matches!(decide_acceptance_retry(&[], None, &findings, "one", MAX_ACCEPTANCE_RETRY_CYCLES), AcceptanceRetryDecision::Stall { reason: "acceptance_cycle_limit_exhausted", external_blockers } if external_blockers.len() == 1)
        );
    }

    #[test]
    fn semantic_fingerprint_tracks_change_specs_and_jsonc_but_excludes_runtime_follow_up() {
        let temp = tempfile::TempDir::new().unwrap();
        let tasks = temp.path().join("openspec/changes/example/tasks.md");
        let spec = temp
            .path()
            .join("openspec/changes/example/specs/runtime/spec.md");
        std::fs::create_dir_all(spec.parent().unwrap()).unwrap();
        std::fs::write(&tasks, "## Implementation Tasks\n- [x] work\n").unwrap();
        std::fs::write(&spec, "requirement one").unwrap();
        std::fs::write(temp.path().join(".cflx.jsonc"), "{ \"mode\": 1 }").unwrap();
        let before = semantic_progress_fingerprint(temp.path()).unwrap();
        std::fs::write(&tasks, "## Implementation Tasks\n- [x] work\n\n## Acceptance #2 Failure Follow-up\n- [ ] runtime finding\n").unwrap();
        assert_eq!(before, semantic_progress_fingerprint(temp.path()).unwrap());
        std::fs::write(&spec, "requirement two").unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
        std::fs::write(temp.path().join(".cflx.jsonc"), "{ \"mode\": 2 }").unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
    }

    /// A JSON-only change's task artifact is progress evidence exactly as the
    /// Markdown one is: real task movement changes the fingerprint, and a
    /// runtime-owned follow-up rewrite does not.
    #[test]
    fn semantic_fingerprint_tracks_json_tasks_but_excludes_runtime_follow_up() {
        fn document(status: &str, follow_up: &str) -> String {
            format!(
                r#"{{"schema_version":1,"tasks":[{{"id":"a","title":"A","status":"{status}","section":"implementation"}}]{follow_up}}}"#
            )
        }

        let temp = tempfile::TempDir::new().unwrap();
        let tasks = temp.path().join("openspec/changes/example/tasks.json");
        std::fs::create_dir_all(tasks.parent().unwrap()).unwrap();
        std::fs::write(&tasks, document("pending", "")).unwrap();
        let before = semantic_progress_fingerprint(temp.path()).unwrap();

        // Runtime bookkeeping: a FAIL write is never Apply progress.
        std::fs::write(
            &tasks,
            document(
                "pending",
                r#","acceptance_follow_up":{"attempt":2,"findings":[{"identity":"repository|src/a.rs|verification","text":"Add the missing test","remediation_claimed":false}]}"#,
            ),
        )
        .unwrap();
        assert_eq!(before, semantic_progress_fingerprint(temp.path()).unwrap());

        // Real task movement: pending -> completed must be visible.
        std::fs::write(&tasks, document("completed", "")).unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
    }

    /// A task artifact whose bytes do not parse is still repository content.
    /// It is hashed verbatim rather than guessed at, so a repair of the
    /// malformed file registers as progress.
    #[test]
    fn semantic_fingerprint_hashes_malformed_json_tasks_verbatim() {
        let temp = tempfile::TempDir::new().unwrap();
        let tasks = temp.path().join("openspec/changes/example/tasks.json");
        std::fs::create_dir_all(tasks.parent().unwrap()).unwrap();
        std::fs::write(&tasks, "{not json").unwrap();
        let before = semantic_progress_fingerprint(temp.path()).unwrap();
        std::fs::write(
            &tasks,
            r#"{"schema_version":1,"tasks":[{"id":"a","title":"A","status":"pending","section":"implementation"}]}"#,
        )
        .unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
    }

    #[test]
    fn generic_credential_and_unavailable_errors_remain_repository_fixable() {
        let findings = normalize_findings(&[
            "missing API key in test fixture".to_string().into(),
            "src/client.rs: rate limit retry missing".to_string().into(),
            "network unreachable: fix retry handling".to_string().into(),
            "dns resolution failed while repairing src/client.rs"
                .to_string()
                .into(),
            "missing non-mockable external credential"
                .to_string()
                .into(),
        ]);
        assert_eq!(
            findings.iter().filter(|finding| finding.external).count(),
            1
        );
        assert!(findings[0].identity.starts_with("external|"));
        assert_eq!(
            repository_findings(&[
                "missing API key in test fixture".to_string().into(),
                "src/client.rs: rate limit retry missing".to_string().into(),
                "network unreachable: fix retry handling".to_string().into(),
                "dns resolution failed while repairing src/client.rs"
                    .to_string()
                    .into(),
                "missing non-mockable external credential"
                    .to_string()
                    .into(),
            ])
            .len(),
            4
        );
    }

    #[test]
    fn alternating_continue_and_fail_keeps_fail_retry_history_deterministic() {
        let findings = normalize_findings(&["src/lib.rs:10 missing regression coverage".into()]);
        let identities = findings
            .iter()
            .map(|finding| finding.identity.clone())
            .collect::<Vec<_>>();

        // CONTINUE never enters the FAIL retry decision; the first later FAIL
        // remains the repair opportunity and the repeated FAIL then stalls.
        assert!(matches!(
            decide_acceptance_retry(&[], None, &findings, "unchanged", 1),
            AcceptanceRetryDecision::Retry {
                reason: "first_acceptance_failure"
            }
        ));
        assert!(matches!(
            decide_acceptance_retry(&identities, Some("unchanged"), &findings, "unchanged", 2),
            AcceptanceRetryDecision::Stall {
                reason: "repeated_acceptance_findings",
                ..
            }
        ));
    }

    #[test]
    fn identical_inputs_have_retry_outcome_parity() {
        let findings = normalize_findings(&[
            "src/lib.rs:10 missing regression coverage".into(),
            "external non-mockable prerequisite unavailable".into(),
        ]);
        let previous = findings
            .iter()
            .map(|finding| finding.identity.clone())
            .collect::<Vec<_>>();

        // Both execution modes call this shared pure decision with checkpoint
        // state. Keep an explicit parity fixture for their common boundary.
        let first = decide_acceptance_retry(&previous, Some("same"), &findings, "same", 2);
        let parallel = decide_acceptance_retry(&previous, Some("same"), &findings, "same", 2);
        assert_eq!(first, parallel);
        assert!(matches!(
            first,
            AcceptanceRetryDecision::Stall {
                reason: "repeated_acceptance_findings",
                ref external_blockers
            } if external_blockers.len() == 1
        ));
    }

    #[test]
    fn retry_decision_handles_mixed_and_findingless_failures() {
        let mixed = normalize_findings(&[
            "src/lib.rs:1 fix test".into(),
            "external service outage".into(),
        ]);
        assert!(matches!(
            decide_acceptance_retry(&[], None, &mixed, "one", 1),
            AcceptanceRetryDecision::Retry { .. }
        ));
        assert!(matches!(
            decide_acceptance_retry(&[], None, &[], "one", 1),
            AcceptanceRetryDecision::Retry { .. }
        ));
        assert_eq!(
            repository_findings(&[
                "src/lib.rs:1 fix test".into(),
                "external service outage".into(),
            ]),
            vec!["src/lib.rs:1 fix test"]
        );
    }

    #[test]
    fn test_build_acceptance_tail_findings_prefers_stdout() {
        let findings = build_acceptance_tail_findings(
            Some("stdout line 1\nstdout line 2".to_string()),
            Some("stderr line".to_string()),
        );

        assert_eq!(findings, vec!["stdout line 1", "stdout line 2"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_falls_back_to_stderr() {
        let findings =
            build_acceptance_tail_findings(Some("  ".to_string()), Some("stderr".to_string()));

        assert_eq!(findings, vec!["stderr"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_fallback_message() {
        let findings = build_acceptance_tail_findings(None, Some("\n\n".to_string()));

        assert_eq!(findings, vec!["No acceptance output captured"]);
    }

    #[test]
    fn test_acceptance_result_is_pass() {
        assert!(AcceptanceResult::Pass.is_pass());
        assert!(!AcceptanceResult::Fail {
            findings: vec!["error".to_string().into()]
        }
        .is_pass());
        assert!(!AcceptanceResult::CommandFailed {
            error: "test".to_string(),
            findings: vec!["failure".to_string()],
            diagnostic: AcceptanceCommandDiagnostic::default(),
        }
        .is_pass());
        assert!(!AcceptanceResult::PermissionStalled {
            blocker: crate::events::StalledBlocker::acceptance_external(
                "pending_verification",
                "permission denied"
            ),
        }
        .is_pass());
        assert!(!AcceptanceResult::MissingVerdict {
            findings: vec!["status-only output".to_string()],
        }
        .is_pass());
        assert!(!AcceptanceResult::Cancelled.is_pass());
        assert!(!AcceptanceResult::Stalled {
            blocker: sample_blocker()
        }
        .is_pass());
    }

    #[test]
    fn test_build_acceptance_tail_findings_filters_acceptance_marker() {
        let findings = build_acceptance_tail_findings(
            Some("line 1\nACCEPTANCE: FAIL\nline 2".to_string()),
            None,
        );

        assert_eq!(findings, vec!["line 1", "line 2"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_filters_findings_line() {
        let findings = build_acceptance_tail_findings(
            Some("error 1\nFINDINGS:\n- item 1\n- item 2".to_string()),
            None,
        );

        assert_eq!(findings, vec!["error 1", "- item 1", "- item 2"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_filters_both_markers() {
        let findings = build_acceptance_tail_findings(
            Some("ACCEPTANCE: FAIL\nFINDINGS:\nactual error\nanother line".to_string()),
            None,
        );

        assert_eq!(findings, vec!["actual error", "another line"]);
    }

    // Characterization tests: document the difference between tail_findings
    // and parse_acceptance_output findings so the refactor is clearly motivated.

    #[test]
    fn test_tail_findings_includes_preamble_parse_does_not() {
        // tail_findings includes all non-marker lines (preamble, postamble, items).
        // parse_acceptance_output findings includes only FINDINGS section items.
        // The refactor unifies the FAIL path to use parse_acceptance_output findings.
        let stdout = "preamble\nACCEPTANCE: FAIL\nFINDINGS:\n- Finding 1\n- Finding 2\npostamble"
            .to_string();

        let tail = build_acceptance_tail_findings(Some(stdout.clone()), None);
        // tail includes preamble, finding items, postamble
        assert!(tail.iter().any(|l| l.contains("preamble")));
        assert!(tail.iter().any(|l| l.contains("postamble")));
        assert!(tail.iter().any(|l| l.contains("Finding 1")));

        // parse_acceptance_output returns only the FINDINGS section items
        match crate::acceptance::parse_acceptance_output(&stdout) {
            crate::acceptance::AcceptanceResult::Fail { findings } => {
                assert_eq!(findings, vec!["Finding 1", "Finding 2"]);
                assert!(!findings.iter().any(|f| f.contains("preamble")));
                assert!(!findings.iter().any(|f| f.contains("postamble")));
            }
            _ => panic!("Expected Fail"),
        }
    }

    #[test]
    fn test_parse_findings_is_preferred_source_for_fail_result() {
        // After the refactor: for AcceptanceResult::Fail, findings come from
        // parse_acceptance_output (FINDINGS section), not from build_acceptance_tail_findings.
        let stdout =
            "ACCEPTANCE: FAIL\nFINDINGS:\n- src/foo.rs:10 issue A\n- src/bar.rs:5 issue B\n"
                .to_string();

        match crate::acceptance::parse_acceptance_output(&stdout) {
            crate::acceptance::AcceptanceResult::Fail { findings } => {
                assert_eq!(findings.len(), 2);
                assert_eq!(findings[0], "src/foo.rs:10 issue A");
                assert_eq!(findings[1], "src/bar.rs:5 issue B");
            }
            _ => panic!("Expected Fail"),
        }
    }
    // --- Remediation-to-diff coverage ---

    use crate::acceptance::AcceptanceFinding;

    fn finding(id: &str, implementation: &str, verification: &str) -> AcceptanceFinding {
        AcceptanceFinding::structured(crate::acceptance::RepositoryFinding {
            id: id.to_string(),
            severity: crate::acceptance::FindingSeverity::Minor,
            summary: "Challenge and proof leakage is not tested by value".to_string(),
            evidence: vec!["relay exposes counts but not issued values".to_string()],
            required_changes: vec![crate::acceptance::FindingFileExpectation {
                file: implementation.to_string(),
                description: "Expose issued challenge and presented proof values".to_string(),
            }],
            verification: vec![crate::acceptance::FindingFileExpectation {
                file: verification.to_string(),
                description: "Assert recorded values are absent from audit output".to_string(),
            }],
        })
    }

    fn secret_value_finding() -> AcceptanceFinding {
        finding(
            "acceptance-secret-value-scan",
            "tests/support/relay.ts",
            "runtime/recovery.integration.test.ts",
        )
    }

    fn changed(paths: &[&str]) -> Vec<String> {
        paths.iter().map(|path| path.to_string()).collect()
    }

    #[test]
    fn complete_coverage_permits_semantic_review_without_claiming_resolution() {
        let findings = [secret_value_finding()];
        let coverage = evaluate_remediation_coverage(
            &findings,
            &changed(&[
                "tests/support/relay.ts",
                "runtime/recovery.integration.test.ts",
            ]),
        );

        assert!(coverage.is_complete());
        assert!(coverage.uncovered().is_empty());
        assert!(coverage.unrelated_files.is_empty());
        assert_eq!(
            decide_repair_gate(
                "change-a",
                &findings,
                &FindingRepairLedger::default(),
                Some("fail-rev"),
                Some("apply-rev"),
                &changed(&[
                    "tests/support/relay.ts",
                    "runtime/recovery.integration.test.ts",
                ]),
                &[],
            ),
            RepairGateDecision::Proceed
        );
    }

    #[test]
    fn missing_implementation_or_verification_path_fails_coverage() {
        let findings = [secret_value_finding()];

        let missing_implementation = evaluate_remediation_coverage(
            &findings,
            &changed(&["runtime/recovery.integration.test.ts"]),
        );
        assert!(!missing_implementation.is_complete());
        assert_eq!(
            missing_implementation.missing_required,
            [(
                "acceptance-secret-value-scan".to_string(),
                "tests/support/relay.ts".to_string()
            )]
        );
        assert!(missing_implementation.missing_verification.is_empty());

        let missing_verification =
            evaluate_remediation_coverage(&findings, &changed(&["tests/support/relay.ts"]));
        assert!(!missing_verification.is_complete());
        assert_eq!(
            missing_verification.missing_verification,
            [(
                "acceptance-secret-value-scan".to_string(),
                "runtime/recovery.integration.test.ts".to_string()
            )]
        );
    }

    #[test]
    fn calibration_only_change_stops_before_acceptance_with_evidence() {
        // Regression shape: Apply touched only a calibration test and a comment.
        let findings = [secret_value_finding()];
        let delta = changed(&["tests/calibration.test.ts", "src/unrelated.rs"]);

        let RepairGateDecision::Stop(stop) = decide_repair_gate(
            "change-a",
            &findings,
            &FindingRepairLedger::default(),
            Some("fail-rev"),
            Some("apply-rev"),
            &delta,
            &["adjusted calibration threshold".to_string()],
        ) else {
            panic!("calibration-only repair must not authorize another acceptance run");
        };

        assert_eq!(stop.reason, REMEDIATION_MISMATCH_REASON);
        assert!(stop.resumable);
        assert_eq!(stop.fail_revision.as_deref(), Some("fail-rev"));
        assert_eq!(stop.apply_revision.as_deref(), Some("apply-rev"));
        assert_eq!(stop.required_files, ["tests/support/relay.ts"]);
        assert_eq!(
            stop.verification_files,
            ["runtime/recovery.integration.test.ts"]
        );
        assert_eq!(
            stop.coverage.unrelated_files,
            ["src/unrelated.rs", "tests/calibration.test.ts"],
            "every changed file is retained as a diagnostic, sorted"
        );
        assert_eq!(stop.coverage.changed_files.len(), delta.len());
        assert_eq!(
            stop.remediation_evidence,
            ["adjusted calibration threshold"]
        );
        // The complete finding is retained for the operator.
        assert_eq!(stop.findings, findings);

        let json = stop.to_json();
        assert_eq!(json["coverage_complete"], false);
        assert_eq!(json["proves_acceptance_pass"], false);
        assert_eq!(json["proves_archive_readiness"], false);
        assert_eq!(json["proves_completion"], false);
    }

    #[test]
    fn coverage_normalizes_renames_and_untracked_paths() {
        let findings = [secret_value_finding()];
        // A rename entry from `--name-status` counts both sides as touched, and
        // `./`-prefixed untracked entries normalize to the same repository path.
        let coverage = evaluate_remediation_coverage(
            &findings,
            &changed(&[
                "tests/support/old-relay.ts -> tests/support/relay.ts",
                "./runtime/recovery.integration.test.ts",
            ]),
        );

        assert!(coverage.is_complete(), "{coverage:?}");
        assert_eq!(
            coverage.unrelated_files,
            ["tests/support/old-relay.ts".to_string()]
        );
    }

    #[test]
    fn legacy_findings_without_declared_paths_keep_compatibility_behavior() {
        let findings = crate::acceptance::legacy_findings(["src/a.rs:10 missing coverage"]);
        let coverage = evaluate_remediation_coverage(&findings, &changed(&["docs/readme.md"]));

        assert!(
            coverage.is_complete(),
            "a legacy finding declares no path set, so strict coverage cannot apply"
        );
        assert_eq!(
            coverage.legacy_finding_texts,
            ["src/a.rs:10 missing coverage"]
        );
        assert_eq!(
            decide_repair_gate(
                "change-a",
                &findings,
                &FindingRepairLedger::default(),
                None,
                None,
                &changed(&["docs/readme.md"]),
                &[],
            ),
            RepairGateDecision::Proceed
        );
    }

    #[test]
    fn empty_repair_delta_cannot_satisfy_a_declared_finding() {
        let findings = [secret_value_finding()];
        assert!(matches!(
            decide_repair_gate(
                "change-a",
                &findings,
                &FindingRepairLedger::default(),
                Some("fail-rev"),
                Some("fail-rev"),
                &[],
                &[],
            ),
            RepairGateDecision::Stop(_)
        ));
    }

    // --- Per-finding automatic repair budget ---

    fn observe(
        ledger: &mut FindingRepairLedger,
        findings: &[AcceptanceFinding],
    ) -> FindingRepairDecision {
        ledger.observe_fail(&normalize_findings(findings))
    }

    #[test]
    fn first_observation_grants_one_repair_opportunity() {
        let mut ledger = FindingRepairLedger::default();
        let findings = [secret_value_finding()];

        let FindingRepairDecision::Repair { identities } = observe(&mut ledger, &findings) else {
            panic!("first observation must allow one repair");
        };
        assert_eq!(identities, ["repository|id|acceptance-secret-value-scan"]);
        assert_eq!(
            ledger.occurrences("repository|id|acceptance-secret-value-scan"),
            1
        );
        assert!(!ledger.has_consumed_repair("repository|id|acceptance-secret-value-scan"));

        ledger.record_repair_dispatched(&identities);
        assert!(ledger.has_consumed_repair("repository|id|acceptance-secret-value-scan"));
    }

    #[test]
    fn repeated_id_stops_before_a_second_repair_regardless_of_progress() {
        let mut ledger = FindingRepairLedger::default();
        let findings = [secret_value_finding()];
        let FindingRepairDecision::Repair { identities } = observe(&mut ledger, &findings) else {
            panic!("first observation must allow one repair");
        };
        ledger.record_repair_dispatched(&identities);

        // The same defect, reported with changed prose, changed evidence, a
        // changed line number, and a different cited path.
        let restated = AcceptanceFinding::structured(crate::acceptance::RepositoryFinding {
            id: "acceptance-secret-value-scan".to_string(),
            severity: crate::acceptance::FindingSeverity::Major,
            summary: "Rewritten summary at a new line".to_string(),
            evidence: vec!["different evidence at src/other.rs:99".to_string()],
            required_changes: vec![crate::acceptance::FindingFileExpectation {
                file: "src/other.rs".to_string(),
                description: "different described change".to_string(),
            }],
            verification: vec![crate::acceptance::FindingFileExpectation {
                file: "tests/other.rs".to_string(),
                description: "different described proof".to_string(),
            }],
        });

        let FindingRepairDecision::Stop {
            reason,
            repeated_identities,
        } = observe(&mut ledger, std::slice::from_ref(&restated))
        else {
            panic!("a repeated ID must stop automatic repair");
        };
        assert_eq!(reason, REPEATED_FINDING_REASON);
        assert_eq!(
            repeated_identities,
            ["repository|id|acceptance-secret-value-scan"]
        );
        assert_eq!(
            ledger.occurrences("repository|id|acceptance-secret-value-scan"),
            2
        );

        // Unrelated semantic progress does not change the decision, and the stop
        // record retains the complete finding.
        let stop = repeated_finding_stop(
            "change-a",
            &[restated],
            &ledger,
            repeated_identities,
            Some("fail-rev"),
            Some("apply-rev"),
            &changed(&["src/other.rs", "tests/other.rs", "docs/notes.md"]),
            &["claimed a repair".to_string()],
        );
        assert_eq!(stop.reason, REPEATED_FINDING_REASON);
        assert!(
            stop.coverage.is_complete(),
            "coverage passing is irrelevant"
        );
        assert_eq!(
            stop.occurrences,
            [("repository|id|acceptance-secret-value-scan".to_string(), 2)]
        );
        assert!(stop.resumable);
        assert_eq!(stop.remediation_evidence, ["claimed a repair"]);
    }

    #[test]
    fn a_new_finding_id_receives_its_own_repair_opportunity() {
        let mut ledger = FindingRepairLedger::default();
        let first = [secret_value_finding()];
        let FindingRepairDecision::Repair { identities } = observe(&mut ledger, &first) else {
            panic!("first observation must allow one repair");
        };
        ledger.record_repair_dispatched(&identities);

        // Acceptance closed the prior ID and reported a genuinely new one.
        let second = [finding(
            "acceptance-new-defect",
            "src/new.rs",
            "tests/new.rs",
        )];
        let FindingRepairDecision::Repair { identities } = observe(&mut ledger, &second) else {
            panic!("a new ID gets its own opportunity");
        };
        assert_eq!(identities, ["repository|id|acceptance-new-defect"]);
        assert_eq!(
            ledger.occurrences("repository|id|acceptance-secret-value-scan"),
            0,
            "an ID acceptance stopped reporting is closed, not carried forward"
        );
    }

    #[test]
    fn mixed_repeated_and_new_ids_stop_atomically_with_every_finding_retained() {
        let mut ledger = FindingRepairLedger::default();
        let repeated = secret_value_finding();
        let FindingRepairDecision::Repair { identities } =
            observe(&mut ledger, std::slice::from_ref(&repeated))
        else {
            panic!("first observation must allow one repair");
        };
        ledger.record_repair_dispatched(&identities);

        let fresh = finding("acceptance-new-defect", "src/new.rs", "tests/new.rs");
        let mixed = [repeated, fresh];
        let FindingRepairDecision::Stop {
            reason,
            repeated_identities,
        } = observe(&mut ledger, &mixed)
        else {
            panic!("a mixed payload containing a repeated ID must stop atomically");
        };
        assert_eq!(reason, REPEATED_FINDING_REASON);
        assert_eq!(
            repeated_identities,
            ["repository|id|acceptance-secret-value-scan"],
            "only the repeated ID is the stop reason"
        );

        let stop = repeated_finding_stop(
            "change-a",
            &mixed,
            &ledger,
            repeated_identities,
            None,
            None,
            &[],
            &[],
        );
        assert_eq!(stop.findings.len(), 2, "diagnostics retain every finding");
        assert_eq!(
            stop.occurrence_identities(),
            [
                "repository|id|acceptance-new-defect".to_string(),
                "repository|id|acceptance-secret-value-scan".to_string(),
            ]
        );
    }

    #[test]
    fn explicit_retry_reset_releases_the_automatic_budget_only() {
        let mut ledger = FindingRepairLedger::default();
        let findings = [secret_value_finding()];
        let FindingRepairDecision::Repair { identities } = observe(&mut ledger, &findings) else {
            panic!("first observation must allow one repair");
        };
        ledger.record_repair_dispatched(&identities);

        ledger.reset_for_explicit_retry();

        assert!(!ledger.has_consumed_repair("repository|id|acceptance-secret-value-scan"));
        assert_eq!(
            ledger.occurrences("repository|id|acceptance-secret-value-scan"),
            1,
            "prior occurrence evidence is preserved for review"
        );
        assert!(matches!(
            observe(&mut ledger, &findings),
            FindingRepairDecision::Repair { .. }
        ));
    }

    #[test]
    fn legacy_findings_use_the_fallback_identity_for_the_repair_budget() {
        let mut ledger = FindingRepairLedger::default();
        let findings = crate::acceptance::legacy_findings(["Missing retry test at src/run.rs:10"]);
        let FindingRepairDecision::Repair { identities } = observe(&mut ledger, &findings) else {
            panic!("first observation must allow one repair");
        };
        assert_eq!(identities, ["repository|src/run.rs|verification"]);
        ledger.record_repair_dispatched(&identities);

        // Same defect, different prose and line number: the fallback identity is
        // stable, so the repeated-finding stop still fires.
        let restated =
            crate::acceptance::legacy_findings(["Regression coverage absent in src/run.rs:99"]);
        assert!(matches!(
            observe(&mut ledger, &restated),
            FindingRepairDecision::Stop { .. }
        ));
    }

    #[test]
    fn structured_finding_identity_is_the_reviewer_id_not_its_prose() {
        let first = normalize_findings(&[secret_value_finding()]);
        let restated = normalize_findings(&[AcceptanceFinding::structured(
            crate::acceptance::RepositoryFinding {
                id: "acceptance-secret-value-scan".to_string(),
                severity: crate::acceptance::FindingSeverity::Major,
                summary: "totally different words".to_string(),
                evidence: vec!["totally different evidence".to_string()],
                required_changes: vec![crate::acceptance::FindingFileExpectation {
                    file: "src/elsewhere.rs".to_string(),
                    description: "d".to_string(),
                }],
                verification: vec![crate::acceptance::FindingFileExpectation {
                    file: "tests/elsewhere.rs".to_string(),
                    description: "d".to_string(),
                }],
            },
        )]);

        assert_eq!(first[0].identity, restated[0].identity);
        assert_ne!(
            first[0].text, restated[0].text,
            "identity is stable while the payload stays free to change"
        );
    }

    // === Bounded Acceptance escalation ===

    /// Every claim in this module is about a *decision*, so nothing here spawns
    /// a process, touches a worktree, or reads a configuration file: the driver
    /// is fed typed results and reports typed outcomes. Real reviewer execution
    /// of those decisions is covered by the acceptance execution tests.
    mod acceptance_escalation {
        use super::*;
        use crate::acceptance::{
            AcceptanceFinding, BlockerRejection, FindingFileExpectation, FindingRejection,
            FindingSeverity, RepositoryFinding,
        };
        use crate::config::{AcceptanceEscalationConfig, OrchestratorConfig};

        fn config_with(command: Option<&str>, policy: Option<(u32, u32)>) -> OrchestratorConfig {
            OrchestratorConfig {
                acceptance_command: Some("accept {change_id} {prompt}".to_string()),
                acceptance_escalation_command: command.map(str::to_string),
                acceptance_escalation: policy.map(|(after, max)| AcceptanceEscalationConfig {
                    after_invalid_results: Some(after),
                    max_uses_per_sequence: Some(max),
                }),
                ..Default::default()
            }
        }

        fn driver(command: Option<&str>, policy: Option<(u32, u32)>) -> AcceptanceEscalationDriver {
            AcceptanceEscalationDriver::from_config(&config_with(command, policy))
        }

        fn default_driver() -> AcceptanceEscalationDriver {
            driver(Some("deep-accept {change_id} {prompt}"), None)
        }

        fn empty_fail() -> AcceptanceResult {
            AcceptanceResult::Fail {
                findings: crate::acceptance::legacy_findings([GENERIC_ACCEPTANCE_FAIL_FINDING]),
            }
        }

        fn actionable_fail() -> AcceptanceResult {
            AcceptanceResult::Fail {
                findings: vec![AcceptanceFinding::structured(RepositoryFinding {
                    id: "finding-1".to_string(),
                    severity: FindingSeverity::Major,
                    summary: "escalation policy is unbounded".to_string(),
                    evidence: vec!["src/orchestration/acceptance.rs:1".to_string()],
                    required_changes: vec![FindingFileExpectation {
                        file: "src/orchestration/acceptance.rs".to_string(),
                        description: "bound the sequence".to_string(),
                    }],
                    verification: vec![FindingFileExpectation {
                        file: "src/orchestration/acceptance.rs".to_string(),
                        description: "prove the bound".to_string(),
                    }],
                })],
            }
        }

        fn missing_verdict() -> AcceptanceResult {
            AcceptanceResult::MissingVerdict {
                findings: vec!["waiting for verification".to_string()],
            }
        }

        fn bare_blocker() -> AcceptanceResult {
            AcceptanceResult::BareBlocker {
                rejection: BlockerRejection::Missing,
            }
        }

        fn malformed_finding() -> AcceptanceResult {
            AcceptanceResult::MalformedFinding {
                rejection: FindingRejection::MissingId,
            }
        }

        // --- Eligibility ---

        /// Every eligible invalid class is classified, and each one alone
        /// selects the alternate reviewer under the default policy.
        #[test]
        fn every_eligible_invalid_class_selects_the_alternate_reviewer() {
            for (result, expected) in [
                (missing_verdict(), InvalidAcceptanceResult::MissingVerdict),
                (bare_blocker(), InvalidAcceptanceResult::BareBlocker),
                (
                    malformed_finding(),
                    InvalidAcceptanceResult::MalformedFinding,
                ),
                (empty_fail(), InvalidAcceptanceResult::EmptyFail),
            ] {
                assert_eq!(
                    classify_invalid_acceptance_result(&result),
                    Some(expected),
                    "{expected:?} must be an eligible invalid result"
                );

                let mut escalation = default_driver();
                let outcome = escalation.observe(&result, None);
                assert!(
                    outcome.escalation_selected(),
                    "{expected:?} must select escalation under the default policy: {outcome:?}"
                );
                assert_eq!(
                    escalation.take_command_mode(),
                    AcceptanceCommandMode::Escalation
                );
            }
        }

        /// A semantic FAIL that reports a real defect is repair work, not
        /// malformed reviewer output: it never counts and never escalates.
        #[test]
        fn actionable_fail_never_escalates_and_resets_the_sequence() {
            assert_eq!(classify_invalid_acceptance_result(&actionable_fail()), None);

            let mut escalation = default_driver();
            assert!(escalation
                .observe(&missing_verdict(), None)
                .escalation_selected());

            let outcome = escalation.observe(&actionable_fail(), None);
            assert_eq!(outcome, AcceptanceEscalationOutcome::SequenceReset);
            assert_eq!(escalation.consecutive_invalid(), 0);
            assert_eq!(escalation.uses_in_sequence(), 0);
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal,
                "a real defect report must not leave an alternate reviewer pending"
            );
        }

        /// A FAIL keeps its normal routing as soon as it carries anything other
        /// than the exact generic fallback.
        #[test]
        fn only_the_exact_generic_fallback_counts_as_an_empty_fail() {
            assert!(is_generic_empty_fail(&[]));
            assert!(is_generic_empty_fail(&crate::acceptance::legacy_findings(
                [GENERIC_ACCEPTANCE_FAIL_FINDING]
            )));
            assert!(!is_generic_empty_fail(&crate::acceptance::legacy_findings(
                ["Investigate acceptance failure and apply the required fix now"]
            )));
            assert!(!is_generic_empty_fail(&crate::acceptance::legacy_findings(
                [
                    GENERIC_ACCEPTANCE_FAIL_FINDING,
                    GENERIC_ACCEPTANCE_FAIL_FINDING,
                ]
            )));
        }

        /// Excluded results are excluded for their own reasons, and the ones
        /// that completed also end an active sequence.
        #[test]
        fn excluded_results_never_escalate() {
            let excluded = [
                AcceptanceResult::Pass,
                AcceptanceResult::Continue,
                actionable_fail(),
                AcceptanceResult::Stalled {
                    blocker: crate::acceptance::AcceptanceBlocker {
                        category: "credential".to_string(),
                        evidence: vec!["missing token".to_string()],
                        unblock_condition: "token provisioned".to_string(),
                        next_action: "ask the owner".to_string(),
                        resumable: true,
                        prerequisite_owner: None,
                        evidence_ids: Vec::new(),
                    },
                },
                AcceptanceResult::PermissionStalled {
                    blocker: crate::events::StalledBlocker::permission_denial(
                        "acceptance",
                        &crate::permission::PermissionDenial {
                            category: crate::permission::PermissionDenialCategory::ToolAccess,
                            denied_target: "git".to_string(),
                            evidence: "denied".to_string(),
                        },
                    ),
                },
                AcceptanceResult::CommandFailed {
                    error: "exit 1".to_string(),
                    findings: vec!["boom".to_string()],
                    diagnostic: AcceptanceCommandDiagnostic::default(),
                },
                AcceptanceResult::RuntimeLimit {
                    limit: AcceptanceRuntimeLimit {
                        limit_secs: 1800,
                        cleanup_confirmed: true,
                        cleanup_diagnostics: String::new(),
                    },
                },
                AcceptanceResult::Cancelled,
            ];

            for result in excluded {
                assert_eq!(
                    classify_invalid_acceptance_result(&result),
                    None,
                    "{result:?} must not be an eligible invalid result"
                );
                let mut escalation = default_driver();
                let outcome = escalation.observe(&result, None);
                assert!(
                    !outcome.escalation_selected(),
                    "{result:?} must not select escalation: {outcome:?}"
                );
                assert_eq!(
                    escalation.take_command_mode(),
                    AcceptanceCommandMode::Normal
                );
            }
        }

        /// A command that never completed produced no reviewer output, so it
        /// neither consumes nor resets the sequence — and the alternate reviewer
        /// already selected still runs once the command recovers.
        #[test]
        fn non_completing_invocations_preserve_the_pending_selection() {
            for result in [
                AcceptanceResult::CommandFailed {
                    error: "exit 1".to_string(),
                    findings: Vec::new(),
                    diagnostic: AcceptanceCommandDiagnostic::default(),
                },
                AcceptanceResult::Cancelled,
                AcceptanceResult::RuntimeLimit {
                    limit: AcceptanceRuntimeLimit {
                        limit_secs: 1800,
                        cleanup_confirmed: true,
                        cleanup_diagnostics: String::new(),
                    },
                },
            ] {
                let mut escalation = default_driver();
                assert!(escalation
                    .observe(&missing_verdict(), None)
                    .escalation_selected());

                assert_eq!(
                    escalation.observe(&result, None),
                    AcceptanceEscalationOutcome::NotObserved,
                    "{result:?} must not be observed against the invalid-result sequence"
                );
                assert_eq!(escalation.consecutive_invalid(), 1);
                assert_eq!(escalation.uses_in_sequence(), 1);
                assert_eq!(
                    escalation.take_command_mode(),
                    AcceptanceCommandMode::Escalation,
                    "the pending alternate reviewer must survive an invocation that never ran"
                );
            }
        }

        // --- Command selection ---

        /// The selection is consumed exactly once, so the retry after the
        /// escalation retry is back on the normal command.
        #[test]
        fn the_command_mode_is_consumed_by_exactly_one_invocation() {
            let mut escalation = default_driver();
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal
            );

            assert!(escalation
                .observe(&missing_verdict(), None)
                .escalation_selected());
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Escalation
            );
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal,
                "one selection must not survive into a second invocation"
            );
        }

        /// Without the optional command, eligibility is still classified and
        /// counted, but the retry keeps using the normal reviewer.
        #[test]
        fn a_missing_escalation_command_preserves_normal_retry_behavior() {
            let mut escalation = driver(None, None);

            let outcome = escalation.observe(&missing_verdict(), None);
            assert_eq!(
                outcome,
                AcceptanceEscalationOutcome::Retained {
                    kind: InvalidAcceptanceResult::MissingVerdict,
                    consecutive_invalid: 1,
                    reason: EscalationDeclineReason::NoCommandConfigured,
                }
            );
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal
            );
        }

        // --- Threshold, cap, and reset ---

        /// A higher threshold keeps the earlier invalid results on the normal
        /// command and escalates only once the configured count is reached.
        #[test]
        fn escalation_waits_for_the_configured_threshold() {
            let mut escalation = driver(Some("deep-accept {prompt}"), Some((3, 1)));

            for expected in 1..3 {
                let outcome = escalation.observe(&missing_verdict(), None);
                assert_eq!(
                    outcome,
                    AcceptanceEscalationOutcome::Retained {
                        kind: InvalidAcceptanceResult::MissingVerdict,
                        consecutive_invalid: expected,
                        reason: EscalationDeclineReason::BelowThreshold {
                            after_invalid_results: 3,
                        },
                    }
                );
                assert_eq!(
                    escalation.take_command_mode(),
                    AcceptanceCommandMode::Normal
                );
            }

            assert!(escalation
                .observe(&missing_verdict(), None)
                .escalation_selected());
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Escalation
            );
        }

        /// The per-sequence cap bounds escalation: once it is spent the sequence
        /// keeps counting but every later retry is back on the normal reviewer.
        #[test]
        fn the_use_cap_bounds_one_invalid_result_sequence() {
            let mut escalation = default_driver();

            assert!(escalation
                .observe(&missing_verdict(), None)
                .escalation_selected());
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Escalation
            );

            let outcome = escalation.observe(&missing_verdict(), None);
            assert_eq!(
                outcome,
                AcceptanceEscalationOutcome::Retained {
                    kind: InvalidAcceptanceResult::MissingVerdict,
                    consecutive_invalid: 2,
                    reason: EscalationDeclineReason::UseCapExhausted {
                        max_uses_per_sequence: 1,
                    },
                }
            );
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal
            );
        }

        /// A larger cap permits exactly that many uses in one sequence.
        #[test]
        fn a_larger_cap_permits_exactly_that_many_uses() {
            let mut escalation = driver(Some("deep-accept {prompt}"), Some((1, 2)));

            for expected_use in 1..=2 {
                let outcome = escalation.observe(&bare_blocker(), None);
                assert!(outcome.escalation_selected(), "{outcome:?}");
                assert_eq!(escalation.uses_in_sequence(), expected_use);
                assert_eq!(
                    escalation.take_command_mode(),
                    AcceptanceCommandMode::Escalation
                );
            }

            assert!(!escalation
                .observe(&bare_blocker(), None)
                .escalation_selected());
        }

        /// Any completed non-invalid result ends the sequence, and a later
        /// invalid result starts a fresh one with a fresh use budget.
        #[test]
        fn a_non_invalid_result_resets_the_sequence() {
            for reset_result in [
                AcceptanceResult::Pass,
                AcceptanceResult::Continue,
                actionable_fail(),
            ] {
                let mut escalation = default_driver();
                assert!(escalation
                    .observe(&missing_verdict(), None)
                    .escalation_selected());
                let _ = escalation.take_command_mode();
                assert!(!escalation
                    .observe(&malformed_finding(), None)
                    .escalation_selected());

                assert_eq!(
                    escalation.observe(&reset_result, None),
                    AcceptanceEscalationOutcome::SequenceReset
                );
                assert_eq!(escalation.consecutive_invalid(), 0);
                assert_eq!(escalation.uses_in_sequence(), 0);

                assert!(
                    escalation
                        .observe(&bare_blocker(), None)
                        .escalation_selected(),
                    "a new sequence must get a fresh escalation budget after {reset_result:?}"
                );
            }
        }

        // --- Empty FAIL across its Apply round ---

        /// Below the threshold an empty FAIL keeps the existing generic
        /// FAIL-to-Apply fallback, and the invalid-result count survives the
        /// Apply round when that round changed nothing.
        #[test]
        fn empty_fail_below_threshold_keeps_its_sequence_across_the_apply_round() {
            let mut escalation = driver(Some("deep-accept {prompt}"), Some((2, 1)));

            let first = escalation.observe(&empty_fail(), Some("rev-a"));
            assert_eq!(
                first,
                AcceptanceEscalationOutcome::Retained {
                    kind: InvalidAcceptanceResult::EmptyFail,
                    consecutive_invalid: 1,
                    reason: EscalationDeclineReason::BelowThreshold {
                        after_invalid_results: 2,
                    },
                },
                "below threshold the empty FAIL follows the existing generic fallback"
            );
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal
            );

            // The Apply round produced no commit, so the same revision comes back.
            let second = escalation.observe(&empty_fail(), Some("rev-a"));
            assert!(
                second.escalation_selected(),
                "the retained count must let a later invalid result reach the threshold: {second:?}"
            );
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Escalation
            );
        }

        /// An Apply round that moved the revision is real repository progress,
        /// so the sequence starts over rather than accumulating across it.
        #[test]
        fn a_revision_change_resets_the_sequence() {
            let mut escalation = driver(Some("deep-accept {prompt}"), Some((2, 1)));

            assert!(!escalation
                .observe(&empty_fail(), Some("rev-a"))
                .escalation_selected());

            let after_apply = escalation.observe(&empty_fail(), Some("rev-b"));
            assert_eq!(
                after_apply,
                AcceptanceEscalationOutcome::Retained {
                    kind: InvalidAcceptanceResult::EmptyFail,
                    consecutive_invalid: 1,
                    reason: EscalationDeclineReason::BelowThreshold {
                        after_invalid_results: 2,
                    },
                },
                "a moved revision must start a fresh sequence"
            );
            assert_eq!(
                escalation.take_command_mode(),
                AcceptanceCommandMode::Normal
            );
        }

        // --- Empty-FAIL routing decision ---

        /// The one routing question an execution frontend asks is answered from
        /// the kind the driver already returned. Only a *selected* escalation of
        /// an empty FAIL replaces the generic FAIL-to-Apply repair; every other
        /// escalated class keeps its own existing routing and only changes which
        /// reviewer the already-permitted retry runs.
        #[test]
        fn only_a_selected_empty_fail_escalation_replaces_the_generic_repair() {
            let escalated = |kind| AcceptanceEscalationOutcome::Escalated {
                kind,
                consecutive_invalid: 1,
                use_index: 1,
                max_uses_per_sequence: 1,
            };

            assert!(
                escalates_empty_fail(&escalated(InvalidAcceptanceResult::EmptyFail)),
                "an escalated empty FAIL is routed as an acceptance-only alternate review"
            );

            for kind in [
                InvalidAcceptanceResult::MissingVerdict,
                InvalidAcceptanceResult::BareBlocker,
                InvalidAcceptanceResult::MalformedFinding,
            ] {
                assert!(
                    !escalates_empty_fail(&escalated(kind)),
                    "{kind:?} already owns an acceptance-only retry; its routing must not change"
                );
            }

            for outcome in [
                AcceptanceEscalationOutcome::NotObserved,
                AcceptanceEscalationOutcome::SequenceReset,
                AcceptanceEscalationOutcome::Retained {
                    kind: InvalidAcceptanceResult::EmptyFail,
                    consecutive_invalid: 1,
                    reason: EscalationDeclineReason::BelowThreshold {
                        after_invalid_results: 2,
                    },
                },
            ] {
                assert!(
                    !escalates_empty_fail(&outcome),
                    "{outcome:?} selected no alternate reviewer, so routing is unchanged"
                );
            }
        }

        /// The decision the parallel loop makes is the driver's own: a real
        /// observation that selects escalation for an empty FAIL reroutes, and
        /// the same observation below the threshold does not.
        #[test]
        fn the_routing_decision_reads_the_drivers_own_observation() {
            let mut escalation = driver(Some("deep-accept {prompt}"), Some((2, 1)));

            let below_threshold = escalation.observe(&empty_fail(), Some("rev-a"));
            assert!(
                !escalates_empty_fail(&below_threshold),
                "below threshold the empty FAIL keeps the generic FAIL-to-Apply repair"
            );

            let at_threshold = escalation.observe(&empty_fail(), Some("rev-a"));
            assert!(
                escalates_empty_fail(&at_threshold),
                "at the threshold the empty FAIL becomes an acceptance-only alternate review"
            );

            let mut protocol_class = driver(Some("deep-accept {prompt}"), Some((1, 1)));
            let escalated_missing_verdict =
                protocol_class.observe(&missing_verdict(), Some("rev-a"));
            assert!(escalated_missing_verdict.escalation_selected());
            assert!(
                !escalates_empty_fail(&escalated_missing_verdict),
                "a missing verdict escalates the reviewer, not the routing"
            );
        }

        // --- Non-persistence ---

        /// The driver is active-run memory. A fresh one built from the same
        /// configuration starts at zero, which is what makes a restart run
        /// ordinary Acceptance from workspace and Git evidence.
        #[test]
        fn a_fresh_driver_carries_no_escalation_state() {
            let config = config_with(Some("deep-accept {prompt}"), None);

            let mut first = AcceptanceEscalationDriver::from_config(&config);
            assert!(first
                .observe(&missing_verdict(), Some("rev-a"))
                .escalation_selected());
            assert_eq!(first.consecutive_invalid(), 1);
            assert_eq!(first.uses_in_sequence(), 1);

            let mut restarted = AcceptanceEscalationDriver::from_config(&config);
            assert_eq!(restarted.consecutive_invalid(), 0);
            assert_eq!(restarted.uses_in_sequence(), 0);
            assert_eq!(
                restarted.take_command_mode(),
                AcceptanceCommandMode::Normal,
                "a restarted run must begin with the ordinary acceptance command"
            );
        }

        // --- Diagnostics ---

        /// Both decisions are reportable without a second read, and the ordinary
        /// cases stay silent.
        #[test]
        fn only_the_two_decisions_produce_a_diagnostic() {
            assert!(AcceptanceEscalationOutcome::NotObserved
                .diagnostic()
                .is_none());
            assert!(AcceptanceEscalationOutcome::SequenceReset
                .diagnostic()
                .is_none());

            let mut escalation = default_driver();
            let escalated = escalation.observe(&malformed_finding(), None).diagnostic();
            let escalated = escalated.expect("an escalation decision must be reportable");
            assert!(escalated.contains("malformed-finding"), "{escalated}");
            assert!(
                escalated.contains("acceptance_escalation_command"),
                "{escalated}"
            );

            let retained = escalation.observe(&malformed_finding(), None).diagnostic();
            let retained = retained.expect("a declined escalation must be reportable");
            assert!(retained.contains("acceptance_command"), "{retained}");
            assert!(retained.contains("budget"), "{retained}");
        }

        /// The mode names the configuration key it resolves, so a diagnostic can
        /// never claim a command the runner did not run.
        #[test]
        fn the_command_mode_names_its_configuration_key() {
            assert_eq!(AcceptanceCommandMode::Normal.label(), "acceptance_command");
            assert_eq!(
                AcceptanceCommandMode::Escalation.label(),
                "acceptance_escalation_command"
            );
            assert!(!AcceptanceCommandMode::Normal.is_escalation());
            assert!(AcceptanceCommandMode::Escalation.is_escalation());
        }

        // --- Template selection ---

        /// The command mode selects the template and nothing else: both
        /// resolutions keep the same `{change_id}`/`{prompt}` contract.
        #[test]
        fn the_command_mode_resolves_exactly_one_reviewer_template() {
            let config = config_with(Some("deep-accept {change_id} {prompt}"), None);

            assert_eq!(
                acceptance_command_template(&config, AcceptanceCommandMode::Normal)
                    .expect("the normal reviewer is a required command"),
                "accept {change_id} {prompt}"
            );
            assert_eq!(
                acceptance_command_template(&config, AcceptanceCommandMode::Escalation)
                    .expect("the escalation reviewer is configured"),
                "deep-accept {change_id} {prompt}"
            );
        }

        /// Selecting escalation without a configured command means a caller
        /// bypassed the policy that owns the selection, so it fails loudly
        /// instead of quietly running the normal reviewer under the wrong name.
        #[test]
        fn escalation_without_a_configured_command_is_a_configuration_error() {
            let config = config_with(None, None);

            assert_eq!(
                acceptance_command_template(&config, AcceptanceCommandMode::Normal)
                    .expect("the normal reviewer is unaffected"),
                "accept {change_id} {prompt}"
            );
            let message = acceptance_command_template(&config, AcceptanceCommandMode::Escalation)
                .expect_err("an unconfigured alternate reviewer must not silently fall back")
                .to_string();
            assert!(
                message.contains("acceptance_escalation_command"),
                "{message}"
            );
        }

        /// The alternate reviewer gets trusted framing that it must produce one
        /// fresh canonical verdict; the normal reviewer gets nothing extra.
        #[test]
        fn only_an_escalation_invocation_carries_the_alternate_reviewer_framing() {
            assert!(
                crate::agent::build_acceptance_escalation_context(AcceptanceCommandMode::Normal)
                    .is_empty(),
                "an ordinary acceptance invocation must not be told it is an alternate review"
            );

            let context = crate::agent::build_acceptance_escalation_context(
                AcceptanceCommandMode::Escalation,
            );
            assert!(context.contains("<acceptance_escalation>"), "{context}");
            assert!(
                context.contains("alternate acceptance reviewer"),
                "{context}"
            );
            assert!(
                context.contains("one fresh canonical acceptance verdict"),
                "{context}"
            );
        }

        /// The three protocol contracts already own an Acceptance-only retry;
        /// an empty FAIL does not, which is why its alternate review is bounded
        /// by the use cap alone.
        #[test]
        fn only_empty_fail_lacks_a_protocol_retry_budget() {
            assert!(InvalidAcceptanceResult::MissingVerdict.has_protocol_retry_budget());
            assert!(InvalidAcceptanceResult::BareBlocker.has_protocol_retry_budget());
            assert!(InvalidAcceptanceResult::MalformedFinding.has_protocol_retry_budget());
            assert!(!InvalidAcceptanceResult::EmptyFail.has_protocol_retry_budget());
        }
    }
}