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
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
//! Tests for ParallelExecutor and related functionality.

use super::super::*;
use super::support::{
    create_test_config, create_test_config_with, init_git_repo, TestAssertionExt,
    TestWorkspaceManager,
};
use crate::agent::AgentRunner;
use crate::command_queue::CommandQueueConfig;
use crate::config::defaults::default_retry_patterns;
use crate::config::OrchestratorConfig;
use crate::events::ExecutionEvent;
use crate::orchestration::acceptance::MAX_ACCEPTANCE_RETRY_CYCLES;
use crate::orchestration::state::{OrchestratorState, ReducerCommand, WaitState};
use crate::parallel::dedup::DiagnosticDeduplicationStore;
use crate::parallel::dynamic_queue::ReanalysisReason;
use crate::parallel::executor::{
    execute_acceptance_in_workspace, execute_archive_finalization_in_workspace,
    execute_archive_in_workspace,
};
use crate::parallel::merge::MergeAttempt;
use crate::parallel::queue_state::ReanalysisDispatchContext;
use crate::vcs::git::commands::get_current_commit;
#[cfg(feature = "heavy-tests")]
use crate::vcs::GitWorkspaceManager;
#[cfg(feature = "heavy-tests")]
use crate::vcs::WorkspaceManager;
use crate::vcs::WorkspaceStatus;
use crate::vcs::{VcsBackend, Workspace, WorkspaceInfo};
use std::collections::{HashMap, HashSet};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tempfile::TempDir;
use tokio::process::Command;
use tokio::sync::{mpsc, Mutex, RwLock};
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;

const DEFAULT_STAGGER_DELAY_MS: u64 = 2000;
const DEFAULT_MAX_RETRIES: u32 = 2;
const DEFAULT_RETRY_DELAY_MS: u64 = 5000;
const DEFAULT_RETRY_IF_DURATION_UNDER_SECS: u64 = 5;

#[test]
#[should_panic(expected = "option missing: value was None")]
fn test_or_fail_option_reports_context() {
    let value: Option<u32> = None;
    let _ = value.or_fail("option missing");
}

#[test]
#[should_panic(expected = "io failed: boom")]
fn test_or_fail_result_reports_context_and_error() {
    let result: Result<(), &str> = Err("boom");
    result.or_fail("io failed");
}

#[test]
fn test_parallel_executor_creation() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let executor = ParallelExecutor::new(repo_root, config, None);

    assert_eq!(executor.max_conflict_retries, 3);
}

#[test]
fn test_parallel_executor_preserves_supplied_shared_stagger_state() {
    let shared_stagger_state = Arc::new(Mutex::new(None));
    let executor = ParallelExecutor::with_backend_and_queue_and_stagger(
        PathBuf::from("/tmp/test-repo"),
        create_test_config(),
        None,
        VcsBackend::Git,
        None,
        Some(shared_stagger_state.clone()),
    );

    assert!(Arc::ptr_eq(
        &executor.shared_stagger_state,
        &shared_stagger_state
    ));
    assert!(Arc::ptr_eq(
        &executor.ai_runner.shared_stagger_state(),
        &shared_stagger_state
    ));
}

async fn commit_workspace_change(
    workspace: &Workspace,
    filename: &str,
    contents: &str,
    message: &str,
) {
    std::fs::write(workspace.path.join(filename), contents).or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", message])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("unexpected error");
}

fn write_change_proposal(repo_root: &Path, change_id: &str, dependencies: &[&str]) {
    let change_dir = repo_root.join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create change proposal directory");
    let dependencies = dependencies
        .iter()
        .map(|dependency| format!("  - {dependency}\n"))
        .collect::<String>();
    std::fs::write(
        change_dir.join("proposal.md"),
        format!("---\ndependencies:\n{dependencies}---\n# {change_id}\n"),
    )
    .or_fail("write change proposal");
}

async fn commit_archive_to_base(repo_root: &Path, archive_leaf: &str, change_id: &str) {
    let archive_dir = repo_root
        .join("openspec/changes/archive")
        .join(archive_leaf);
    std::fs::create_dir_all(&archive_dir).or_fail("unexpected error");
    std::fs::write(
        archive_dir.join("proposal.md"),
        format!("# Archived {change_id}\n"),
    )
    .or_fail("unexpected error");
    // A real archive moves the change: leaving the active directory behind is
    // contradictory base evidence, not proof of completion.
    let active_dir = repo_root.join("openspec/changes").join(change_id);
    if active_dir.exists() {
        std::fs::remove_dir_all(&active_dir).or_fail("unexpected error");
    }
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", &format!("Archive {change_id}")])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
}
#[tokio::test]
async fn resolving_dependency_blocks_its_dependent_but_not_unrelated_dispatch() {
    let temp = TempDir::new().or_fail("create temp repo");
    init_git_repo(temp.path()).await;
    std::fs::create_dir_all(temp.path().join("openspec/changes/dependent"))
        .or_fail("create dependent change");
    std::fs::write(
        temp.path().join("openspec/changes/dependent/proposal.md"),
        "---\ndependencies:\n  - resolving\n---\n# Dependent\n",
    )
    .or_fail("write dependent proposal metadata");
    std::fs::write(
        temp.path().join("openspec/changes/dependent/tasks.md"),
        "## Implementation Tasks\n- [ ] apply\n",
    )
    .or_fail("write dependent tasks");
    std::fs::create_dir_all(temp.path().join("openspec/changes/unrelated"))
        .or_fail("create unrelated change");
    std::fs::write(
        temp.path().join("openspec/changes/unrelated/proposal.md"),
        "# Unrelated\n",
    )
    .or_fail("write unrelated proposal");
    std::fs::write(
        temp.path().join("openspec/changes/unrelated/tasks.md"),
        "## Implementation Tasks\n- [ ] apply\n",
    )
    .or_fail("write unrelated tasks");
    Command::new("git")
        .args(["add", "."])
        .current_dir(temp.path())
        .output()
        .await
        .or_fail("stage fixture changes");
    Command::new("git")
        .args(["commit", "-m", "Add dispatch fixtures"])
        .current_dir(temp.path())
        .output()
        .await
        .or_fail("commit fixture changes");

    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(
        temp.path().to_path_buf(),
        create_test_config_with(OrchestratorConfig {
            workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
            ..Default::default()
        }),
        Some(tx),
    );
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            "resolving".to_string(),
            "dependent".to_string(),
            "unrelated".to_string(),
        ],
        1,
    )));
    {
        let mut guard = shared.write().await;
        // Production start records queue intent for its targets before the
        // scheduler runs; ordinary dispatch reads that intent, not the local list.
        guard.apply_command(ReducerCommand::AddToQueue("dependent".to_string()));
        guard.apply_command(ReducerCommand::AddToQueue("unrelated".to_string()));
        guard.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "resolving".to_string(),
            command: "resolve".to_string(),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let analysis = crate::analyzer::AnalysisResult {
        order: vec!["dependent".to_string(), "unrelated".to_string()],
        dependencies: HashMap::new(),
        groups: None,
    };
    let selected = executor
        .select_changes_for_dispatch(&analysis, 2, &HashSet::new())
        .await;
    assert_eq!(
        selected,
        vec!["unrelated"],
        "resolve blocks only its dependent"
    );

    let mut queued = vec![
        crate::openspec::Change {
            dependencies: vec!["resolving".to_string()],
            ..make_test_change("dependent")
        },
        make_test_change("unrelated"),
    ];
    let mut in_flight = HashSet::new();
    let mut join_set = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        temp.path().to_path_buf(),
    );
    executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 2,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &dependent_ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("resolve-gated dispatch");
    while join_set.join_next().await.is_some() {}

    let mut saw_unrelated_apply = false;
    let mut saw_dependent_apply = false;
    while let Ok(Some(event)) =
        tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv()).await
    {
        match event {
            ExecutionEvent::ApplyStarted { change_id, .. } if change_id == "unrelated" => {
                saw_unrelated_apply = true
            }
            ExecutionEvent::ApplyStarted { change_id, .. } if change_id == "dependent" => {
                saw_dependent_apply = true
            }
            _ => {}
        }
    }
    assert!(
        saw_unrelated_apply,
        "unrelated change must retain parallel dispatch"
    );
    assert!(
        !saw_dependent_apply,
        "dependent must not emit ApplyStarted while its dependency resolves"
    );

    commit_archive_to_base(temp.path(), "2026-07-21-resolving", "resolving").await;
    shared
        .write()
        .await
        .apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "resolving".to_string(),
            revision: "merged".to_string(),
        });
    let selected = executor
        .select_changes_for_dispatch(&analysis, 2, &HashSet::new())
        .await;
    assert_eq!(selected, vec!["dependent", "unrelated"]);

    executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 2,
            iteration: 2,
            reanalysis_reason: ReanalysisReason::ResolveCompletion,
            analyzer: &dependent_ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("merged dependency dispatch");
    while join_set.join_next().await.is_some() {}
    let mut saw_dependent_after_merge = false;
    while let Ok(Some(event)) =
        tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv()).await
    {
        if matches!(
            event,
            ExecutionEvent::ApplyStarted { change_id, .. } if change_id == "dependent"
        ) {
            saw_dependent_after_merge = true;
        }
    }
    assert!(
        saw_dependent_after_merge,
        "dependent must emit ApplyStarted after merge evidence"
    );
}

#[tokio::test]
async fn resolving_dependency_diagnostic_dedupes_and_reemits_after_signature_change() {
    let temp = TempDir::new().or_fail("unexpected error");
    init_git_repo(temp.path()).await;
    let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        temp.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["resolving-a".to_string(), "dependent".to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        // Production start records queue intent for its targets before the
        // scheduler runs; ordinary dispatch reads that intent, not the local list.
        guard.apply_command(ReducerCommand::AddToQueue("dependent".to_string()));
        guard.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "resolving-a".to_string(),
            command: "resolve".to_string(),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());
    let resolving_analysis = crate::analyzer::AnalysisResult {
        order: vec!["dependent".to_string()],
        dependencies: HashMap::from([("dependent".to_string(), vec!["resolving-a".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    assert!(executor
        .select_changes_for_dispatch(&resolving_analysis, 1, &in_flight)
        .await
        .is_empty());
    assert!(executor
        .select_changes_for_dispatch(&resolving_analysis, 1, &in_flight)
        .await
        .is_empty());
    assert_eq!(
        drain_dependency_events(&mut event_rx, "dependent"),
        vec!["blocked:resolving-a".to_string()],
        "unchanged resolving blocker must emit one diagnostic event"
    );

    shared
        .write()
        .await
        .apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "resolving-a".to_string(),
            error: "conflict remains".to_string(),
        });
    assert!(executor
        .select_changes_for_dispatch(&resolving_analysis, 1, &in_flight)
        .await
        .is_empty());
    assert_eq!(
        drain_dependency_events(&mut event_rx, "dependent"),
        vec!["blocked:resolving-a".to_string()],
        "changed blocker signature must re-emit a diagnostic event"
    );
}

#[tokio::test]
async fn metadata_read_failure_blocks_dispatch_even_without_analyzer_dependencies() {
    for (change_id, proposal) in [
        ("missing-proposal", None),
        (
            "invalid-proposal",
            Some("---\ndependencies: [broken\n---\n# Invalid\n"),
        ),
    ] {
        let temp = TempDir::new().or_fail("unexpected error");
        init_git_repo(temp.path()).await;
        let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64);
        let mut executor = ParallelExecutor::new(
            temp.path().to_path_buf(),
            create_test_config(),
            Some(event_tx),
        );
        let proposal_dir = temp.path().join("openspec/changes").join(change_id);
        std::fs::create_dir_all(&proposal_dir).or_fail("create proposal fixture");
        if let Some(proposal) = proposal {
            std::fs::write(proposal_dir.join("proposal.md"), proposal)
                .or_fail("write invalid proposal fixture");
        }
        let analysis = crate::analyzer::AnalysisResult {
            order: vec![change_id.to_string()],
            dependencies: HashMap::new(),
            groups: None,
        };

        assert!(
            executor
                .select_changes_for_dispatch(&analysis, 1, &HashSet::new())
                .await
                .is_empty(),
            "{change_id} must not dispatch"
        );
        let mut saw_metadata_error = false;
        while let Ok(event) = event_rx.try_recv() {
            if let ExecutionEvent::Error { message } = event {
                saw_metadata_error |= message.contains("dependency metadata could not be read");
            }
        }
        assert!(
            saw_metadata_error,
            "{change_id} metadata failure must block dispatch visibly"
        );
    }
}

#[tokio::test]
async fn test_dependency_blocker_diagnostics_dedupe_and_reemit_on_signature_change() {
    let temp = TempDir::new().or_fail("unexpected error");
    write_change_proposal(temp.path(), "dependent", &["dep-a"]);
    let rejected_dir = temp.path().join("openspec/changes/dep-a");

    let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        temp.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let analysis = crate::analyzer::AnalysisResult {
        order: vec!["dependent".to_string()],
        dependencies: HashMap::from([("dependent".to_string(), vec!["dep-a".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let first = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;
    let second = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;

    assert!(first.is_empty());
    assert!(second.is_empty());
    let mut missing_errors = 0;
    while let Ok(event) = event_rx.try_recv() {
        if let ParallelEvent::Error { message } = event {
            if message.contains("missing dependency 'dep-a'") {
                missing_errors += 1;
            }
        }
    }
    assert_eq!(
        missing_errors, 1,
        "unchanged missing blocker should emit once"
    );

    std::fs::create_dir_all(&rejected_dir).or_fail("unexpected error");
    std::fs::write(rejected_dir.join("proposal.md"), "# Dep A\n").or_fail("unexpected error");
    std::fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED\n").or_fail("unexpected error");
    let third = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;
    assert!(third.is_empty());

    let mut rejected_errors = 0;
    while let Ok(event) = event_rx.try_recv() {
        if let ParallelEvent::Error { message } = event {
            if message.contains("rejected dependency 'dep-a'") {
                rejected_errors += 1;
            }
        }
    }
    assert_eq!(rejected_errors, 1, "changed blocker class should re-emit");
}

#[tokio::test]
async fn test_terminal_error_change_is_not_selected_until_explicit_retry() {
    let temp = TempDir::new().or_fail("unexpected error");
    let (event_tx, _event_rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        temp.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue("alpha".to_string()));
        guard.apply_execution_event(&crate::events::ExecutionEvent::ProcessingError {
            id: "alpha".to_string(),
            error: "boom".to_string(),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let analysis = crate::analyzer::AnalysisResult {
        order: vec!["alpha".to_string()],
        dependencies: HashMap::new(),
        groups: None,
    };
    let in_flight = HashSet::new();

    let blocked = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;
    assert!(blocked.is_empty());

    shared
        .write()
        .await
        .apply_command(ReducerCommand::RetryError("alpha".to_string()));
    let selected = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;
    assert_eq!(selected, vec!["alpha".to_string()]);
}

#[tokio::test]
async fn test_dependency_on_terminal_error_is_blocked_until_retry_and_success() {
    let temp = TempDir::new().or_fail("unexpected error");
    init_git_repo(temp.path()).await;
    write_change_proposal(temp.path(), "alpha", &[]);
    write_change_proposal(temp.path(), "beta", &["alpha"]);
    let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        temp.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string(), "beta".to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue("alpha".to_string()));
        guard.apply_command(ReducerCommand::AddToQueue("beta".to_string()));
        guard.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "alpha".to_string(),
            error: "boom".to_string(),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let analysis = crate::analyzer::AnalysisResult {
        order: vec!["alpha".to_string(), "beta".to_string()],
        dependencies: HashMap::from([("beta".to_string(), vec!["alpha".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let blocked = executor
        .select_changes_for_dispatch(&analysis, 2, &in_flight)
        .await;
    assert!(blocked.is_empty());

    let mut saw_error_dependency_block = false;
    while let Ok(event) = event_rx.try_recv() {
        if let ParallelEvent::Error { message } = event {
            if message.contains("blocked by errored dependency 'alpha'") {
                saw_error_dependency_block = true;
            }
        }
    }
    assert!(
        saw_error_dependency_block,
        "errored dependency should emit a diagnostic"
    );

    shared
        .write()
        .await
        .apply_command(ReducerCommand::RetryError("alpha".to_string()));
    let retry_selected = executor
        .select_changes_for_dispatch(&analysis, 2, &in_flight)
        .await;
    assert_eq!(retry_selected, vec!["alpha".to_string()]);

    commit_archive_to_base(temp.path(), "2026-05-12-alpha", "alpha").await;
    shared
        .write()
        .await
        .apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "merged".to_string(),
        });

    let after_success_analysis = crate::analyzer::AnalysisResult {
        order: vec!["beta".to_string()],
        dependencies: HashMap::from([("beta".to_string(), vec!["alpha".to_string()])]),
        groups: None,
    };
    let after_success = executor
        .select_changes_for_dispatch(&after_success_analysis, 2, &in_flight)
        .await;
    assert_eq!(after_success, vec!["beta".to_string()]);
}

#[tokio::test]
async fn test_dependency_blocker_archived_unblocks_dispatch_after_base_merge() {
    let temp = TempDir::new().or_fail("unexpected error");
    init_git_repo(temp.path()).await;
    write_change_proposal(temp.path(), "dependent", &["dep-a"]);
    let rejected_dir = temp.path().join("openspec/changes/dep-a");
    std::fs::create_dir_all(&rejected_dir).or_fail("unexpected error");
    std::fs::write(rejected_dir.join("proposal.md"), "# Dep A\n").or_fail("unexpected error");
    std::fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED\n").or_fail("unexpected error");

    let (event_tx, _event_rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        temp.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let analysis = crate::analyzer::AnalysisResult {
        order: vec!["dependent".to_string()],
        dependencies: HashMap::from([("dependent".to_string(), vec!["dep-a".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let blocked = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;
    assert!(blocked.is_empty());

    std::fs::remove_file(rejected_dir.join("REJECTED.md")).or_fail("unexpected error");
    commit_archive_to_base(temp.path(), "2026-05-09-dep-a", "dep-a").await;

    let selected = executor
        .select_changes_for_dispatch(&analysis, 1, &in_flight)
        .await;
    assert_eq!(selected, vec!["dependent".to_string()]);
    assert!(executor.force_recreate_worktree.contains("dependent"));
}

#[tokio::test]
async fn test_queue_reconciliation_skips_archived_dirty_candidate_when_post_archive_merge_active() {
    let temp = TempDir::new().or_fail("unexpected error");
    init_git_repo(temp.path()).await;

    let workspace_path = temp.path().join("worktrees/ws-gamma");
    std::fs::create_dir_all(&workspace_path).or_fail("unexpected error");
    let worktree_changes_dir = workspace_path.join("openspec/changes");
    std::fs::create_dir_all(worktree_changes_dir.join("archive/2026-05-10-gamma"))
        .or_fail("unexpected error");
    std::fs::write(
        worktree_changes_dir.join("archive/2026-05-10-gamma/proposal.md"),
        "# Gamma\n",
    )
    .or_fail("unexpected error");

    let merge_calls = Arc::new(AtomicUsize::new(0));
    let manager = TestWorkspaceManager::new(merge_calls)
        .with_existing_workspace("gamma", workspace_path.clone());
    let mut executor = ParallelExecutor::new(temp.path().to_path_buf(), create_test_config(), None);
    executor.workspace_manager = Box::new(manager);
    // Explicit queue intent, so the post-archive-merge gate is what stops the
    // candidate rather than the absence of ordinary intent.
    let shared = Arc::new(tokio::sync::RwLock::new(
        crate::orchestration::state::OrchestratorState::new(vec!["gamma".to_string()], 0),
    ));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("gamma".to_string()));
    executor.set_shared_orchestrator_state(shared);

    let _active_merge_guard =
        crate::parallel::merge::ActivePostArchiveMergeGuard::force_register_for_test("gamma");
    let mut queued = Vec::new();
    let in_flight = HashSet::new();

    let outcome = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
        .await;

    assert_eq!(outcome.total_added(), 0);
    assert!(queued.is_empty());
}

#[test]
fn test_skip_reason_for_merge_deferred_dependency() {
    let merge_calls = Arc::new(AtomicUsize::new(0));
    let manager = TestWorkspaceManager::new(merge_calls);
    let mut change_dependencies = HashMap::new();
    change_dependencies.insert("change-b".to_string(), vec!["change-a".to_string()]);
    let mut resolve_wait_changes = HashSet::new();
    resolve_wait_changes.insert("change-a".to_string());

    // Create test AI runner
    let shared_stagger_state = Arc::new(Mutex::new(None));
    let config = create_test_config();
    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };
    let run_command_scope = crate::ai_command_runner::RunCommandScope::new();
    let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    ai_runner.set_run_command_scope(run_command_scope.clone());

    let executor = ParallelExecutor {
        workspace_manager: Box::new(manager),
        config,
        apply_command: String::new(),
        archive_command: String::new(),
        event_tx: None,
        max_conflict_retries: 1,
        repo_root: PathBuf::from("/tmp/test-repo"),
        no_resume: false,
        explicit_retry: false,
        failed_tracker: FailedChangeTracker::new(),
        change_dependencies,
        resolve_wait_changes,
        reject_wait_changes: HashSet::new(),
        merge_wait_changes: HashSet::new(),
        dependency_blocker_fingerprints: HashMap::new(),
        force_recreate_worktree: HashSet::new(),
        hooks: None,
        cancel_token: None,
        last_queue_change_at: Arc::new(Mutex::new(None)),
        last_available_slots: None,
        analyzer_capacity_suppressed: false,
        pending_retry_bypass: HashSet::new(),
        dynamic_queue: None,
        ai_runner,
        run_command_scope,
        shared_stagger_state,
        apply_history: Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        archive_history: Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        acceptance_history: Arc::new(Mutex::new(crate::history::AcceptanceHistory::new())),
        acceptance_tail_injected: Arc::new(Mutex::new(std::collections::HashMap::new())),
        apply_budget: crate::execution::apply::ApplyBudget::new(),
        lifecycle_slots: crate::parallel::lifecycle_slots::LifecycleSlots::new(4),
        manual_resolve_count: None,
        auto_resolve_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pending_merge_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        scheduler_lifetime: SchedulerLifetime::Finite,
        graceful_stop: None,
        persistent_idle_latched: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        persistent_idle_baseline: Arc::new(std::sync::Mutex::new(None)),
        post_archive_action: super::super::PostArchiveAction::MergeToBase,
        shared_orchestrator_state: None,
        last_dispatched_resolve_wait_changes: HashSet::new(),
        last_dispatched_reject_wait_changes: HashSet::new(),
        resolve_wait_retry_triggered: false,
        last_resolve_wait_base_dirty: None,
        diagnostic_dedup: DiagnosticDeduplicationStore::new(),
        last_completed_analysis_input: None,
        next_analysis_signature_probe_at: None,
        analysis_retry_throttle: None,
        analysis_input_probe: None,
        upstream: None,
        explicit_target_plan: None,
        change_failures_this_run: HashSet::new(),
        run_fatal_abort: None,
        merge_result_channel_override: None,
        run_command_cleanup_budget_override: None,
    };

    // MergeWait dependencies are NOT skip reasons; they are handled as blocked/queued status
    // via dependency resolution checks (is_dependency_resolved). Only failed dependencies
    // are skip reasons.
    assert!(executor.skip_reason_for_change("change-b").is_none());
    assert!(executor.skip_reason_for_change("change-c").is_none());
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_resolve_merge_aborts_when_base_dirty() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    let repo_dir = tempfile::TempDir::new().or_fail("create temp repo");
    let worktree_dir = tempfile::TempDir::new().or_fail("create worktree base");
    let repo_root = repo_dir.path();
    init_git_repo(repo_root).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(worktree_dir.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let mut manager = GitWorkspaceManager::new(
        worktree_dir.path().to_path_buf(),
        repo_root.to_path_buf(),
        1,
        config.clone(),
    );
    let workspace = manager
        .create_workspace("change-a", None)
        .await
        .or_fail("create workspace");
    commit_workspace_change(&workspace, "change-a.txt", "A", "Apply: change-a").await;

    std::fs::write(repo_root.join("dirty.txt"), "dirty").or_fail("dirty base");

    let result = resolve_deferred_merge(repo_root.to_path_buf(), config, "change-a").await;
    assert!(result.is_err(), "dirty base must abort deferred merge");

    let merge_log = Command::new("git")
        .args(["log", "--merges", "--format=%s"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("read merge log");
    assert!(!String::from_utf8_lossy(&merge_log.stdout).contains("Merge change: change-a"));
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_conflictless_path_skips_resolve_started_event() {
    use tokio::sync::mpsc;

    let temp_dir = tempfile::TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let base_dir = repo_root.join("worktrees");

    init_git_repo(repo_root).await;

    let config = create_test_config_with(OrchestratorConfig {
        resolve_command: Some("sh -c 'echo should-not-run-resolve'".to_string()),
        ..Default::default()
    });
    let mut manager =
        GitWorkspaceManager::new(base_dir.clone(), repo_root.to_path_buf(), 1, config.clone());

    let workspace_a = manager
        .create_workspace("change-a", None)
        .await
        .or_fail("unexpected error");
    commit_workspace_change(&workspace_a, "change-a.txt", "A", "Apply: change-a").await;

    // Prepare the same state as archived sequential merge handoff:
    // `git merge --no-ff --no-commit <worktree>` succeeded on main,
    // MERGE_HEAD exists, and there are no unresolved conflicts.
    Command::new("git")
        .args(["checkout", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["merge", "--no-ff", "--no-commit", &workspace_a.name])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    let (event_tx, mut event_rx) = mpsc::channel(64);

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };
    let run_command_scope = crate::ai_command_runner::RunCommandScope::new();
    let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    ai_runner.set_run_command_scope(run_command_scope.clone());

    let executor = ParallelExecutor {
        workspace_manager: Box::new(manager),
        config,
        apply_command: String::new(),
        archive_command: String::new(),
        event_tx: Some(event_tx),
        max_conflict_retries: 2,
        repo_root: repo_root.to_path_buf(),
        no_resume: false,
        explicit_retry: false,
        failed_tracker: FailedChangeTracker::new(),
        change_dependencies: HashMap::new(),
        resolve_wait_changes: HashSet::new(),
        reject_wait_changes: HashSet::new(),
        merge_wait_changes: HashSet::new(),
        dependency_blocker_fingerprints: HashMap::new(),
        force_recreate_worktree: HashSet::new(),
        hooks: None,
        cancel_token: None,
        last_queue_change_at: Arc::new(Mutex::new(None)),
        last_available_slots: None,
        analyzer_capacity_suppressed: false,
        pending_retry_bypass: HashSet::new(),
        dynamic_queue: None,
        ai_runner,
        run_command_scope,
        apply_history: Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        archive_history: Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        acceptance_history: Arc::new(Mutex::new(crate::history::AcceptanceHistory::new())),
        acceptance_tail_injected: Arc::new(Mutex::new(std::collections::HashMap::new())),
        apply_budget: crate::execution::apply::ApplyBudget::new(),
        lifecycle_slots: crate::parallel::lifecycle_slots::LifecycleSlots::new(4),
        shared_stagger_state,
        manual_resolve_count: None,
        auto_resolve_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pending_merge_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        scheduler_lifetime: SchedulerLifetime::Finite,
        graceful_stop: None,
        persistent_idle_latched: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        persistent_idle_baseline: Arc::new(std::sync::Mutex::new(None)),
        post_archive_action: super::super::PostArchiveAction::MergeToBase,
        shared_orchestrator_state: None,
        last_dispatched_resolve_wait_changes: HashSet::new(),
        last_dispatched_reject_wait_changes: HashSet::new(),
        resolve_wait_retry_triggered: false,
        last_resolve_wait_base_dirty: None,
        diagnostic_dedup: DiagnosticDeduplicationStore::new(),
        last_completed_analysis_input: None,
        next_analysis_signature_probe_at: None,
        analysis_retry_throttle: None,
        analysis_input_probe: None,
        upstream: None,
        explicit_target_plan: None,
        change_failures_this_run: HashSet::new(),
        run_fatal_abort: None,
        merge_result_channel_override: None,
        run_command_cleanup_budget_override: None,
    };

    let items = crate::parallel::resolve_state::SequentialMergeItem::batch(
        std::slice::from_ref(&workspace_a.name),
        &["change-a".to_string()],
        std::slice::from_ref(&workspace_a.path),
    )
    .or_fail("well-formed sequential merge batch");

    executor
        .merge_and_resolve_with(&items, |_revs, _details| async move { Ok(()) })
        .await
        .or_fail("unexpected error");

    let mut saw_resolve_started = false;
    let mut saw_resolve_completed = false;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            ParallelEvent::ResolveStarted { .. } => saw_resolve_started = true,
            ParallelEvent::ResolveCompleted { change_id, .. } if change_id == "change-a" => {
                saw_resolve_completed = true
            }
            _ => {}
        }
    }

    assert!(!saw_resolve_started);
    assert!(saw_resolve_completed);
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_conflict_path_emits_resolve_started_event() {
    use tokio::sync::mpsc;

    let temp_dir = tempfile::TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let base_dir = repo_root.join("worktrees");

    init_git_repo(repo_root).await;

    let config = create_test_config_with(OrchestratorConfig {
        resolve_command: Some("sh merge-resolver.sh".to_string()),
        ..Default::default()
    });
    let mut manager =
        GitWorkspaceManager::new(base_dir.clone(), repo_root.to_path_buf(), 1, config.clone());

    // main側で先に変更を入れて、ワークツリー側と衝突を作る
    std::fs::write(repo_root.join("conflict.txt"), "main").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Main conflict seed"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    let workspace_a = manager
        .create_workspace("change-a", None)
        .await
        .or_fail("unexpected error");
    std::fs::write(workspace_a.path.join("conflict.txt"), "worktree").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");

    let resolver_script = repo_root.join("merge-resolver.sh");
    let script_contents = format!(
        "#!/bin/sh\nset -e\nROOT=\"$(pwd)\"\n\
            cd \"{}\"\n\
            git checkout {}\n\
            if ! git merge --no-ff -m 'Pre-sync base into change-a' main; then\n\
              if git rev-parse -q --verify MERGE_HEAD >/dev/null 2>&1; then\n\
                git checkout --ours conflict.txt\n\
                git add -A\n\
                git commit -m 'Pre-sync base into change-a'\n\
              else\n\
                exit 1\n\
              fi\n\
            fi\n\
            cd \"$ROOT\"\n\
            git checkout main\n\
            git merge --no-ff -m 'Merge change: change-a' {}\n",
        workspace_a.path.to_string_lossy(),
        workspace_a.name,
        workspace_a.name
    );
    std::fs::write(&resolver_script, script_contents).or_fail("unexpected error");

    let (event_tx, mut event_rx) = mpsc::channel(64);

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };
    let run_command_scope = crate::ai_command_runner::RunCommandScope::new();
    let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    ai_runner.set_run_command_scope(run_command_scope.clone());

    let executor = ParallelExecutor {
        workspace_manager: Box::new(manager),
        config,
        apply_command: String::new(),
        archive_command: String::new(),
        event_tx: Some(event_tx),
        max_conflict_retries: 2,
        repo_root: repo_root.to_path_buf(),
        no_resume: false,
        explicit_retry: false,
        failed_tracker: FailedChangeTracker::new(),
        change_dependencies: HashMap::new(),
        resolve_wait_changes: HashSet::new(),
        reject_wait_changes: HashSet::new(),
        merge_wait_changes: HashSet::new(),
        dependency_blocker_fingerprints: HashMap::new(),
        force_recreate_worktree: HashSet::new(),
        hooks: None,
        cancel_token: None,
        last_queue_change_at: Arc::new(Mutex::new(None)),
        last_available_slots: None,
        analyzer_capacity_suppressed: false,
        pending_retry_bypass: HashSet::new(),
        dynamic_queue: None,
        ai_runner,
        run_command_scope,
        apply_history: Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        archive_history: Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        acceptance_history: Arc::new(Mutex::new(crate::history::AcceptanceHistory::new())),
        acceptance_tail_injected: Arc::new(Mutex::new(std::collections::HashMap::new())),
        apply_budget: crate::execution::apply::ApplyBudget::new(),
        lifecycle_slots: crate::parallel::lifecycle_slots::LifecycleSlots::new(4),
        shared_stagger_state,
        manual_resolve_count: None,
        auto_resolve_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pending_merge_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        scheduler_lifetime: SchedulerLifetime::Finite,
        graceful_stop: None,
        persistent_idle_latched: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        persistent_idle_baseline: Arc::new(std::sync::Mutex::new(None)),
        post_archive_action: super::super::PostArchiveAction::MergeToBase,
        shared_orchestrator_state: None,
        last_dispatched_resolve_wait_changes: HashSet::new(),
        last_dispatched_reject_wait_changes: HashSet::new(),
        resolve_wait_retry_triggered: false,
        last_resolve_wait_base_dirty: None,
        diagnostic_dedup: DiagnosticDeduplicationStore::new(),
        last_completed_analysis_input: None,
        next_analysis_signature_probe_at: None,
        analysis_retry_throttle: None,
        analysis_input_probe: None,
        upstream: None,
        explicit_target_plan: None,
        change_failures_this_run: HashSet::new(),
        run_fatal_abort: None,
        merge_result_channel_override: None,
        run_command_cleanup_budget_override: None,
    };

    let items = crate::parallel::resolve_state::SequentialMergeItem::batch(
        std::slice::from_ref(&workspace_a.name),
        &["change-a".to_string()],
        std::slice::from_ref(&workspace_a.path),
    )
    .or_fail("well-formed sequential merge batch");

    executor
        .merge_and_resolve_with(&items, |_revs, _details| async move { Ok(()) })
        .await
        .or_fail("unexpected error");

    let mut saw_resolve_started = false;
    let mut saw_resolve_completed = false;
    let mut resolve_started_command: Option<String> = None;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            ParallelEvent::ResolveStarted { change_id, command } if change_id == "change-a" => {
                saw_resolve_started = true;
                resolve_started_command = Some(command);
            }
            ParallelEvent::ResolveCompleted { change_id, .. } if change_id == "change-a" => {
                saw_resolve_completed = true
            }
            _ => {}
        }
    }

    assert!(saw_resolve_started);
    assert!(saw_resolve_completed);
    let command = resolve_started_command.expect("resolve started command must exist");
    assert!(command.contains("merge-resolver.sh"));
    assert!(!command.contains("(unknown)"));
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_retries_when_merge_commit_missing() {
    let temp_dir = tempfile::TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let base_dir = repo_root.join("worktrees");

    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(repo_root.join("README.md"), "base").or_fail("unexpected error");

    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["commit", "-m", "Base"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        resolve_command: Some("sh merge-resolver.sh".to_string()),
        ..Default::default()
    });
    let mut manager =
        GitWorkspaceManager::new(base_dir.clone(), repo_root.to_path_buf(), 2, config.clone());

    let workspace_a = manager
        .create_workspace("change-a", None)
        .await
        .or_fail("unexpected error");
    let workspace_b = manager
        .create_workspace("change-b", None)
        .await
        .or_fail("unexpected error");

    std::fs::write(workspace_a.path.join("change-a.txt"), "A").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(workspace_b.path.join("change-b.txt"), "B").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_b.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-b"])
        .current_dir(&workspace_b.path)
        .output()
        .await
        .or_fail("unexpected error");

    let resolver_script = repo_root.join("merge-resolver.sh");
    let script_contents = format!(
        "#!/bin/sh\nset -e\nROOT=\"$(pwd)\"\n\
            if [ -f .git/merge-missing-marker ]; then\n\
              cd \"{}\"\n\
              git checkout {}\n\
              git merge --no-ff -m 'Pre-sync base into change-b' main\n\
              cd \"$ROOT\"\n\
              git checkout main\n\
              git merge --no-ff -m 'Merge change: change-b' {}\n\
              exit 0\n\
            fi\n\
            cd \"{}\"\n\
            git checkout {}\n\
            git merge --no-ff -m 'Pre-sync base into change-a' main\n\
            cd \"$ROOT\"\n\
            git checkout main\n\
            git merge --no-ff -m 'Merge change: change-a' {}\n\
            touch .git/merge-missing-marker\n",
        workspace_b.path.to_string_lossy(),
        workspace_b.name,
        workspace_b.name,
        workspace_a.path.to_string_lossy(),
        workspace_a.name,
        workspace_a.name
    );
    std::fs::write(&resolver_script, script_contents).or_fail("unexpected error");

    // Create test AI runner

    let shared_stagger_state = Arc::new(Mutex::new(None));

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,

        max_retries: DEFAULT_MAX_RETRIES,

        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,

        retry_error_patterns: default_retry_patterns(),

        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let run_command_scope = crate::ai_command_runner::RunCommandScope::new();
    let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    ai_runner.set_run_command_scope(run_command_scope.clone());

    let executor = ParallelExecutor {
        workspace_manager: Box::new(manager),
        config,
        apply_command: String::new(),
        archive_command: String::new(),
        event_tx: None,
        max_conflict_retries: 2,
        repo_root: repo_root.to_path_buf(),
        no_resume: false,
        explicit_retry: false,
        failed_tracker: FailedChangeTracker::new(),
        change_dependencies: HashMap::new(),
        resolve_wait_changes: HashSet::new(),
        reject_wait_changes: HashSet::new(),
        merge_wait_changes: HashSet::new(),
        dependency_blocker_fingerprints: HashMap::new(),
        force_recreate_worktree: HashSet::new(),
        hooks: None,
        cancel_token: None,
        last_queue_change_at: Arc::new(Mutex::new(None)),
        last_available_slots: None,
        analyzer_capacity_suppressed: false,
        pending_retry_bypass: HashSet::new(),
        dynamic_queue: None,
        ai_runner,
        run_command_scope,
        apply_history: Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        archive_history: Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        acceptance_history: Arc::new(Mutex::new(crate::history::AcceptanceHistory::new())),
        acceptance_tail_injected: Arc::new(Mutex::new(std::collections::HashMap::new())),
        apply_budget: crate::execution::apply::ApplyBudget::new(),
        lifecycle_slots: crate::parallel::lifecycle_slots::LifecycleSlots::new(4),
        shared_stagger_state,
        manual_resolve_count: None,
        auto_resolve_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pending_merge_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        scheduler_lifetime: SchedulerLifetime::Finite,
        graceful_stop: None,
        persistent_idle_latched: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        persistent_idle_baseline: Arc::new(std::sync::Mutex::new(None)),
        post_archive_action: super::super::PostArchiveAction::MergeToBase,
        shared_orchestrator_state: None,
        last_dispatched_resolve_wait_changes: HashSet::new(),
        last_dispatched_reject_wait_changes: HashSet::new(),
        resolve_wait_retry_triggered: false,
        last_resolve_wait_base_dirty: None,
        diagnostic_dedup: DiagnosticDeduplicationStore::new(),
        last_completed_analysis_input: None,
        next_analysis_signature_probe_at: None,
        analysis_retry_throttle: None,
        analysis_input_probe: None,
        upstream: None,
        explicit_target_plan: None,
        change_failures_this_run: HashSet::new(),
        run_fatal_abort: None,
        merge_result_channel_override: None,
        run_command_cleanup_budget_override: None,
    };

    let items = crate::parallel::resolve_state::SequentialMergeItem::batch(
        &[workspace_a.name.clone(), workspace_b.name.clone()],
        &["change-a".to_string(), "change-b".to_string()],
        &[workspace_a.path.clone(), workspace_b.path.clone()],
    )
    .or_fail("well-formed sequential merge batch");

    executor
        .merge_and_resolve_with(&items, |_revs, _details| async move { Ok(()) })
        .await
        .or_fail("unexpected error");

    let merge_log = Command::new("git")
        .args(["log", "--merges", "--format=%s"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    let merge_messages = String::from_utf8_lossy(&merge_log.stdout);
    assert!(merge_messages.contains("Merge change: change-a"));
    assert!(merge_messages.contains("Merge change: change-b"));
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_resolves_conflict_with_resolve_command() {
    let temp_dir = tempfile::TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let base_dir = repo_root.join("worktrees");

    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(repo_root.join("conflict.txt"), "base").or_fail("unexpected error");

    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["commit", "-m", "Base"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        resolve_command: Some("sh merge-resolver.sh".to_string()),
        ..Default::default()
    });
    let mut manager =
        GitWorkspaceManager::new(base_dir.clone(), repo_root.to_path_buf(), 2, config.clone());

    let workspace_a = manager
        .create_workspace("change-a", None)
        .await
        .or_fail("unexpected error");
    let workspace_b = manager
        .create_workspace("change-b", None)
        .await
        .or_fail("unexpected error");

    std::fs::write(workspace_a.path.join("conflict.txt"), "A").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(workspace_b.path.join("conflict.txt"), "B").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_b.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-b"])
        .current_dir(&workspace_b.path)
        .output()
        .await
        .or_fail("unexpected error");

    let resolver_script = repo_root.join("merge-resolver.sh");
    let script_contents = format!(
        "#!/bin/sh\nset -e\nROOT=\"$(pwd)\"\n\
            cd \"{}\"\n\
            git checkout {}\n\
            git merge --no-ff -m 'Pre-sync base into change-a' main\n\
            cd \"$ROOT\"\n\
            git checkout main\n\
            git merge --no-ff -m 'Merge change: change-a' {}\n\
            cd \"{}\"\n\
            git checkout {}\n\
            if ! git merge --no-ff -m 'Pre-sync base into change-b' main; then\n\
              if git rev-parse -q --verify MERGE_HEAD >/dev/null 2>&1; then\n\
                git checkout --ours conflict.txt\n\
                git add -A\n\
                git commit -m 'Pre-sync base into change-b'\n\
              else\n\
                exit 1\n\
              fi\n\
            fi\n\
            cd \"$ROOT\"\n\
            git checkout main\n\
            git merge --no-ff -m 'Merge change: change-b' {}\n",
        workspace_a.path.to_string_lossy(),
        workspace_a.name,
        workspace_a.name,
        workspace_b.path.to_string_lossy(),
        workspace_b.name,
        workspace_b.name
    );
    std::fs::write(&resolver_script, script_contents).or_fail("unexpected error");

    // Create test AI runner

    let shared_stagger_state = Arc::new(Mutex::new(None));

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,

        max_retries: DEFAULT_MAX_RETRIES,

        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,

        retry_error_patterns: default_retry_patterns(),

        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let run_command_scope = crate::ai_command_runner::RunCommandScope::new();
    let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    ai_runner.set_run_command_scope(run_command_scope.clone());

    let executor = ParallelExecutor {
        workspace_manager: Box::new(manager),
        config,
        apply_command: String::new(),
        archive_command: String::new(),
        event_tx: None,
        max_conflict_retries: 2,
        repo_root: repo_root.to_path_buf(),
        no_resume: false,
        explicit_retry: false,
        failed_tracker: FailedChangeTracker::new(),
        change_dependencies: HashMap::new(),
        resolve_wait_changes: HashSet::new(),
        reject_wait_changes: HashSet::new(),
        merge_wait_changes: HashSet::new(),
        dependency_blocker_fingerprints: HashMap::new(),
        force_recreate_worktree: HashSet::new(),
        hooks: None,
        cancel_token: None,
        last_queue_change_at: Arc::new(Mutex::new(None)),
        last_available_slots: None,
        analyzer_capacity_suppressed: false,
        pending_retry_bypass: HashSet::new(),
        dynamic_queue: None,
        ai_runner,
        run_command_scope,
        apply_history: Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        archive_history: Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        acceptance_history: Arc::new(Mutex::new(crate::history::AcceptanceHistory::new())),
        acceptance_tail_injected: Arc::new(Mutex::new(std::collections::HashMap::new())),
        apply_budget: crate::execution::apply::ApplyBudget::new(),
        lifecycle_slots: crate::parallel::lifecycle_slots::LifecycleSlots::new(4),
        shared_stagger_state,
        manual_resolve_count: None,
        auto_resolve_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pending_merge_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        scheduler_lifetime: SchedulerLifetime::Finite,
        graceful_stop: None,
        persistent_idle_latched: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        persistent_idle_baseline: Arc::new(std::sync::Mutex::new(None)),
        post_archive_action: super::super::PostArchiveAction::MergeToBase,
        shared_orchestrator_state: None,
        last_dispatched_resolve_wait_changes: HashSet::new(),
        last_dispatched_reject_wait_changes: HashSet::new(),
        resolve_wait_retry_triggered: false,
        last_resolve_wait_base_dirty: None,
        diagnostic_dedup: DiagnosticDeduplicationStore::new(),
        last_completed_analysis_input: None,
        next_analysis_signature_probe_at: None,
        analysis_retry_throttle: None,
        analysis_input_probe: None,
        upstream: None,
        explicit_target_plan: None,
        change_failures_this_run: HashSet::new(),
        run_fatal_abort: None,
        merge_result_channel_override: None,
        run_command_cleanup_budget_override: None,
    };

    let items = crate::parallel::resolve_state::SequentialMergeItem::batch(
        &[workspace_a.name.clone(), workspace_b.name.clone()],
        &["change-a".to_string(), "change-b".to_string()],
        &[workspace_a.path.clone(), workspace_b.path.clone()],
    )
    .or_fail("well-formed sequential merge batch");

    executor
        .merge_and_resolve_with(&items, |_revs, _details| async move { Ok(()) })
        .await
        .or_fail("unexpected error");

    let merged_contents =
        std::fs::read_to_string(repo_root.join("conflict.txt")).or_fail("unexpected error");
    assert!(merged_contents.contains('B'));
}

#[cfg(feature = "heavy-tests")]
#[cfg(unix)]
#[tokio::test]
async fn test_merge_retries_after_pre_commit_changes() {
    let temp_dir = tempfile::TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let base_dir = repo_root.join("worktrees");

    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(repo_root.join("hooked.txt"), "base").or_fail("unexpected error");

    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    Command::new("git")
        .args(["commit", "-m", "Base"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        resolve_command: Some("sh merge-resolver.sh".to_string()),
        ..Default::default()
    });
    let mut manager =
        GitWorkspaceManager::new(base_dir.clone(), repo_root.to_path_buf(), 1, config.clone());

    let workspace_a = manager
        .create_workspace("change-a", None)
        .await
        .or_fail("unexpected error");

    std::fs::write(repo_root.join("main.txt"), "main").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Main update"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(workspace_a.path.join("change-a.txt"), "A").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(&workspace_a.path)
        .output()
        .await
        .or_fail("unexpected error");

    let hooks_dir = repo_root.join(".git/hooks");
    let hook_path = hooks_dir.join("pre-commit");
    let hook_contents = "#!/bin/sh\n\
        set -e\n\
        COMMON_DIR=$(git rev-parse --git-common-dir)\n\
        MARKER=\"$COMMON_DIR/hooks/pre-commit-ran\"\n\
        if [ ! -f \"$MARKER\" ]; then\n\
          echo 'hooked' >> hooked.txt\n\
          git add hooked.txt\n\
          touch \"$MARKER\"\n\
          exit 1\n\
        fi\n\
        exit 0\n";
    std::fs::write(&hook_path, hook_contents).or_fail("unexpected error");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&hook_path)
            .or_fail("unexpected error")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&hook_path, perms).or_fail("unexpected error");
    }

    let resolver_script = repo_root.join("merge-resolver.sh");
    let script_contents = format!(
        "#!/bin/sh\nset -e\nROOT=\"$(pwd)\"\n\
            cd \"{}\"\n\
            git checkout {}\n\
            git merge --no-ff --no-commit main\n\
            if ! git commit -m 'Pre-sync base into change-a'; then\n\
              git add -A\n\
              git commit -m 'Pre-sync base into change-a'\n\
            fi\n\
            cd \"$ROOT\"\n\
            git checkout main\n\
            git merge --no-ff --no-commit {}\n\
            if ! git commit -m 'Merge change: change-a'; then\n\
              git add -A\n\
              git commit -m 'Merge change: change-a'\n\
            fi\n",
        workspace_a.path.to_string_lossy(),
        workspace_a.name,
        workspace_a.name
    );
    std::fs::write(&resolver_script, script_contents).or_fail("unexpected error");

    // Create test AI runner

    let shared_stagger_state = Arc::new(Mutex::new(None));

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,

        max_retries: DEFAULT_MAX_RETRIES,

        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,

        retry_error_patterns: default_retry_patterns(),

        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let run_command_scope = crate::ai_command_runner::RunCommandScope::new();
    let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    ai_runner.set_run_command_scope(run_command_scope.clone());

    let executor = ParallelExecutor {
        workspace_manager: Box::new(manager),
        config,
        apply_command: String::new(),
        archive_command: String::new(),
        event_tx: None,
        max_conflict_retries: 2,
        repo_root: repo_root.to_path_buf(),
        no_resume: false,
        explicit_retry: false,
        failed_tracker: FailedChangeTracker::new(),
        change_dependencies: HashMap::new(),
        resolve_wait_changes: HashSet::new(),
        reject_wait_changes: HashSet::new(),
        merge_wait_changes: HashSet::new(),
        dependency_blocker_fingerprints: HashMap::new(),
        force_recreate_worktree: HashSet::new(),
        hooks: None,
        cancel_token: None,
        last_queue_change_at: Arc::new(Mutex::new(None)),
        last_available_slots: None,
        analyzer_capacity_suppressed: false,
        pending_retry_bypass: HashSet::new(),
        dynamic_queue: None,
        ai_runner,
        run_command_scope,
        apply_history: Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        archive_history: Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        acceptance_history: Arc::new(Mutex::new(crate::history::AcceptanceHistory::new())),
        acceptance_tail_injected: Arc::new(Mutex::new(std::collections::HashMap::new())),
        apply_budget: crate::execution::apply::ApplyBudget::new(),
        lifecycle_slots: crate::parallel::lifecycle_slots::LifecycleSlots::new(4),
        shared_stagger_state,
        manual_resolve_count: None,
        auto_resolve_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        pending_merge_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        scheduler_lifetime: SchedulerLifetime::Finite,
        graceful_stop: None,
        persistent_idle_latched: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        persistent_idle_baseline: Arc::new(std::sync::Mutex::new(None)),
        post_archive_action: super::super::PostArchiveAction::MergeToBase,
        shared_orchestrator_state: None,
        last_dispatched_resolve_wait_changes: HashSet::new(),
        last_dispatched_reject_wait_changes: HashSet::new(),
        resolve_wait_retry_triggered: false,
        last_resolve_wait_base_dirty: None,
        diagnostic_dedup: DiagnosticDeduplicationStore::new(),
        last_completed_analysis_input: None,
        next_analysis_signature_probe_at: None,
        analysis_retry_throttle: None,
        analysis_input_probe: None,
        upstream: None,
        explicit_target_plan: None,
        change_failures_this_run: HashSet::new(),
        run_fatal_abort: None,
        merge_result_channel_override: None,
        run_command_cleanup_budget_override: None,
    };

    let items = crate::parallel::resolve_state::SequentialMergeItem::batch(
        std::slice::from_ref(&workspace_a.name),
        &["change-a".to_string()],
        std::slice::from_ref(&workspace_a.path),
    )
    .or_fail("well-formed sequential merge batch");

    executor
        .merge_and_resolve_with(&items, |_revs, _details| async move { Ok(()) })
        .await
        .or_fail("unexpected error");

    let hook_contents =
        std::fs::read_to_string(repo_root.join("hooked.txt")).or_fail("unexpected error");
    assert!(hook_contents.contains("hooked"));
}

#[tokio::test]
async fn test_execute_acceptance_in_workspace_emits_gate_specific_failure_log_context() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    // Create a workspace commit so acceptance diff context has a real delta target.
    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let change_id = "change-a";
    let tasks_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    let acceptance_output = "ACCEPTANCE: FAIL\n\nFINDINGS:\n- archive-readiness gate failed: cargo clippy -- -D warnings (src/lib.rs:42)\n- secondary finding\n";
    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(format!(
            "printf '{}'",
            acceptance_output.replace('\n', "\\n")
        )),
        archive_command: Some(
            "sh -c 'mkdir -p openspec/changes/archive && mv openspec/changes/change-a openspec/changes/archive/change-a && echo archive-ran > archive-ran.txt'"
                .to_string(),
        ),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        change_id,
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    match result {
        crate::orchestration::AcceptanceResult::Fail { findings } => {
            assert_eq!(findings.len(), 2);
            assert!(
                findings
                    .iter()
                    .any(|f| f.contains("archive-readiness gate failed")),
                "expected archive-readiness finding in acceptance output"
            );
        }
        other => panic!("expected acceptance fail result, got {:?}", other),
    }

    let archive_result = execute_archive_in_workspace(
        change_id,
        repo_root.path(),
        acceptance_config
            .get_archive_command()
            .or_fail("unexpected error"),
        &acceptance_config,
        None,
        VcsBackend::Git,
        None,
        None,
        None,
        &ai_runner,
        &Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        &Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        &shared_stagger_state,
    )
    .await;

    let archive_commit = archive_result.or_fail("archive should run even after acceptance failure");
    assert!(
        !archive_commit.trim().is_empty(),
        "archive should return a merge commit hash when workspace-local routing allows archive"
    );

    assert!(
        repo_root.path().join("archive-ran.txt").exists(),
        "archive command should execute based on workspace-local routing"
    );
}

#[tokio::test]
async fn test_acceptance_fail_records_follow_up_tasks() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let change_id = "change-a";
    let tasks_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(
            "sh -c 'echo ACCEPTANCE: FAIL; echo; echo FINDINGS:; echo - missing regression test; echo - add repo coverage; echo - external non-mockable prerequisite unavailable'"
                .to_string(),
        ),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, iteration) = execute_acceptance_in_workspace(
        change_id,
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    match result {
        crate::orchestration::AcceptanceResult::Fail { findings } => {
            assert_eq!(findings.len(), 3);
        }
        other => panic!("expected acceptance fail, got {:?}", other),
    }

    assert_eq!(
        agent
            .get_acceptance_follow_up(change_id)
            .or_fail("acceptance follow-up should be recorded")
            .1,
        ["missing regression test", "add repo coverage"]
    );

    crate::task_parser::replace_acceptance_follow_up_from_latest_fail(
        &crate::task_file::TaskFile::in_entry(
            &tasks_dir,
            crate::task_file::TaskFileFormat::Markdown,
        ),
        iteration,
        &[
            "missing regression test".to_string().into(),
            "add repo coverage".to_string().into(),
        ],
    )
    .or_fail("unexpected error");

    let updated_tasks =
        std::fs::read_to_string(tasks_dir.join("tasks.md")).or_fail("unexpected error");
    assert!(updated_tasks.contains("## Current Acceptance Follow-up"));
    assert!(updated_tasks.contains("- attempt: 1"));
    assert!(updated_tasks.contains("- [ ] missing regression test"));
    assert!(updated_tasks.contains("- [ ] add repo coverage"));

    let progress = crate::task_parser::parse_file(&tasks_dir.join("tasks.md"), Some(change_id))
        .or_fail("unexpected error");
    assert_eq!(progress.completed, 1);
    assert_eq!(progress.total, 3);
}

// --- Reviewer command selection in the live parallel path ---

const NORMAL_REVIEWER_PROMPT_FILE: &str = "normal-reviewer-prompt.txt";
const ESCALATION_REVIEWER_PROMPT_FILE: &str = "escalation-reviewer-prompt.txt";

/// Two reviewer templates that are distinguishable from outside the process:
/// each writes the prompt it actually received into its own marker file and
/// emits its own verdict. "Which command ran" is then answered by the workspace
/// rather than by re-reading the selection logic under test.
fn distinguishable_reviewer_config() -> OrchestratorConfig {
    create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(format!(
            "printf '%s' {{prompt}} > {NORMAL_REVIEWER_PROMPT_FILE}; echo 'ACCEPTANCE: FAIL'; \
             echo; echo 'FINDINGS:'; echo '- normal reviewer ran'"
        )),
        acceptance_escalation_command: Some(format!(
            "printf '%s' {{prompt}} > {ESCALATION_REVIEWER_PROMPT_FILE}; echo 'ACCEPTANCE: PASS'"
        )),
        ..Default::default()
    })
}

/// Run exactly one acceptance invocation in `workspace_path` under the given
/// reviewer command mode, through the same executor entry point the parallel
/// dispatch loop calls.
async fn run_acceptance_with_command_mode(
    workspace_path: &Path,
    config: &OrchestratorConfig,
    command_mode: crate::orchestration::acceptance::AcceptanceCommandMode,
) -> crate::orchestration::AcceptanceResult {
    let change_id = "change-a";
    let tasks_dir = workspace_path.join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let ai_runner = AiCommandRunner::new(queue_config, Arc::new(Mutex::new(None)));
    let mut agent = AgentRunner::new(config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        change_id,
        workspace_path,
        &mut agent,
        None,
        None,
        &ai_runner,
        config,
        &acceptance_tail_injected,
        &acceptance_history,
        None,
        None,
        command_mode,
    )
    .await
    .or_fail("acceptance invocation should complete");

    result
}

/// The live parallel acceptance path honours an escalation selection: it runs
/// `acceptance_escalation_command`, not `acceptance_command`, and the
/// alternate-reviewer framing reaches that invocation's prompt.
#[tokio::test]
async fn acceptance_escalation_mode_runs_the_escalation_command_with_its_framing() {
    let workspace = TempDir::new().or_fail("unexpected error");
    let config = distinguishable_reviewer_config();

    let result = run_acceptance_with_command_mode(
        workspace.path(),
        &config,
        crate::orchestration::acceptance::AcceptanceCommandMode::Escalation,
    )
    .await;

    assert!(
        matches!(result, crate::orchestration::AcceptanceResult::Pass),
        "the escalation reviewer's own verdict must be the one parsed, got {result:?}"
    );
    assert!(
        !workspace.path().join(NORMAL_REVIEWER_PROMPT_FILE).exists(),
        "an escalation invocation must not run acceptance_command"
    );

    let prompt = std::fs::read_to_string(workspace.path().join(ESCALATION_REVIEWER_PROMPT_FILE))
        .or_fail("acceptance_escalation_command should have run and captured its prompt");
    assert!(
        prompt.contains("<acceptance_escalation>")
            && prompt.contains("</acceptance_escalation>")
            && prompt.contains("You are an alternate acceptance reviewer."),
        "the alternate-reviewer framing must reach the escalation invocation: {prompt}"
    );
}

/// The counterpart: an ordinary invocation runs `acceptance_command` and never
/// carries the alternate-reviewer framing, so the framing cannot leak into a
/// normal review.
#[tokio::test]
async fn acceptance_normal_mode_runs_the_normal_command_without_escalation_framing() {
    let workspace = TempDir::new().or_fail("unexpected error");
    let config = distinguishable_reviewer_config();

    let result = run_acceptance_with_command_mode(
        workspace.path(),
        &config,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await;

    match result {
        crate::orchestration::AcceptanceResult::Fail { findings } => assert_eq!(
            crate::acceptance::finding_texts(&findings),
            ["normal reviewer ran"],
            "the normal reviewer's own verdict must be the one parsed"
        ),
        other => panic!("expected the normal reviewer's FAIL verdict, got {other:?}"),
    }
    assert!(
        !workspace
            .path()
            .join(ESCALATION_REVIEWER_PROMPT_FILE)
            .exists(),
        "an ordinary invocation must not run acceptance_escalation_command"
    );

    let prompt = std::fs::read_to_string(workspace.path().join(NORMAL_REVIEWER_PROMPT_FILE))
        .or_fail("acceptance_command should have run and captured its prompt");
    assert!(
        !prompt.contains("acceptance_escalation")
            && !prompt.contains("You are an alternate acceptance reviewer."),
        "the alternate-reviewer framing must be absent from a normal invocation: {prompt}"
    );
}

/// Two independent dispatches route acceptance follow-up persistence and PASS
/// cleanup through the shared task-parser recovery path. This asserts the two
/// call sequences produce byte-identical files, so recovery, warning, and
/// cleanup behavior cannot diverge between workspaces.
#[test]
fn repeated_follow_up_recovery_produces_identical_files() {
    const DRIFTED: &str = concat!(
        "## Implementation Tasks\n",
        "- [x] done\n",
        "\n",
        "## Current Acceptance Follow-up\n",
        "- attempt: 1\n",
        "- [x] earlier finding\n",
        "### Reviewer notes\n",
        "Free-form evidence with - [ ] checkbox text.\n",
    );
    let change_id = "parity-change";
    let findings = ["latest finding".to_string()];

    let seed = |root: &Path| {
        let change_dir = root.join("openspec/changes").join(change_id);
        std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
        std::fs::write(change_dir.join("tasks.md"), DRIFTED).or_fail("unexpected error");
    };

    let first_root = TempDir::new().or_fail("unexpected error");
    let second_root = TempDir::new().or_fail("unexpected error");
    seed(first_root.path());
    seed(second_root.path());

    let mut rendered = Vec::new();
    for root in [first_root.path(), second_root.path()] {
        // FAIL persistence: identical resolver + shared recovery entry point.
        let tasks_path =
            crate::task_parser::resolve_acceptance_follow_up_tasks_path(change_id, root)
                .or_fail("follow-up path resolves");
        let recovery = crate::task_parser::replace_acceptance_follow_up_from_latest_fail(
            &tasks_path,
            2,
            &crate::acceptance::legacy_findings(findings.clone()),
        )
        .or_fail("recovery succeeds instead of terminating");
        assert_eq!(recovery.recovered_blocks, 1);
        assert!(recovery.warning().is_some());

        let after_fail = std::fs::read_to_string(&tasks_path).or_fail("unexpected error");
        assert!(after_fail.contains("## Recovered Acceptance Notes"));
        assert!(after_fail.contains("- [ ] latest finding"));
        assert_eq!(
            crate::task_parser::parse_content(&after_fail, None),
            crate::task_parser::TaskProgress::with_counts(1, 2)
        );

        // PASS cleanup: recovered notes survive, runtime section does not.
        let cleanup_path = crate::task_parser::resolve_acceptance_follow_up_tasks_path_for_cleanup(
            change_id, root,
        )
        .or_fail("cleanup path resolves")
        .or_fail("cleanup path exists");
        crate::task_parser::clear_acceptance_follow_up(&cleanup_path).or_fail("cleanup succeeds");

        let after_pass = std::fs::read_to_string(&cleanup_path).or_fail("unexpected error");
        assert!(!after_pass.contains("Acceptance Follow-up"));
        assert!(after_pass.contains("## Recovered Acceptance Notes"));
        rendered.push(after_pass);
    }

    assert_eq!(rendered[0], rendered[1]);
}

#[tokio::test]
async fn test_acceptance_history_records_end_revision_when_head_changes() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let change_id = "change-a";
    let tasks_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo acceptance-history-marker >> feature.rs; git add feature.rs; git commit -m acceptance-history-rev >/dev/null 2>&1; echo ACCEPTANCE: PASS'".to_string()),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        change_id,
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    match result {
        crate::orchestration::AcceptanceResult::Pass => {}
        other => panic!("expected acceptance pass, got {:?}", other),
    }

    let end_revision = get_current_commit(repo_root.path())
        .await
        .or_fail("unexpected error");

    let recorded_revision = acceptance_history
        .lock()
        .await
        .last_commit_hash(change_id)
        .or_fail("acceptance history should store commit hash");
    assert_eq!(
        recorded_revision, end_revision,
        "acceptance history commit_hash should track end-of-acceptance HEAD"
    );
}

#[tokio::test]
async fn test_acceptance_diff_base_uses_last_acceptance_end_revision() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let change_id = "change-a";
    let tasks_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo acceptance-drift-marker >> feature.rs; git add feature.rs; git commit -m acceptance-drift-rev >/dev/null 2>&1; echo ACCEPTANCE: PASS'".to_string()),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        change_id,
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    match result {
        crate::orchestration::AcceptanceResult::Pass => {}
        other => panic!("expected acceptance pass, got {:?}", other),
    }

    std::fs::write(
        repo_root.path().join("post_acceptance_only.rs"),
        "pub fn only_after() {}\n",
    )
    .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "post_acceptance_only.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Post acceptance fix"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let base_commit = acceptance_history
        .lock()
        .await
        .last_commit_hash(change_id)
        .or_fail("acceptance history should provide last commit hash");
    let current_commit = get_current_commit(repo_root.path())
        .await
        .or_fail("unexpected error");

    let changed_files = crate::vcs::git::commands::get_changed_files(
        repo_root.path(),
        Some(&base_commit),
        &current_commit,
    )
    .await
    .or_fail("expected changed files from last acceptance revision");

    assert!(
        changed_files.iter().any(|f| f == "post_acceptance_only.rs"),
        "diff from last acceptance revision should include files changed after acceptance"
    );
    assert!(
        !changed_files.iter().any(|f| f == "feature.rs"),
        "diff from last acceptance revision should exclude files changed during acceptance itself"
    );
}

#[tokio::test]
async fn test_archive_guard_allows_archive_after_acceptance_head_change_pass() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let change_id = "change-a";
    let tasks_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo post-pass-change >> feature.rs; git add feature.rs; git commit -m acceptance-pass-rev >/dev/null 2>&1; echo ACCEPTANCE: PASS'".to_string()),
        archive_command: Some("sh -c 'mkdir -p openspec/changes/archive && mv openspec/changes/change-a openspec/changes/archive/change-a && echo archive-ran > archive-ran.txt'".to_string()),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        change_id,
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    match result {
        crate::orchestration::AcceptanceResult::Pass => {}
        other => panic!("expected acceptance pass, got {:?}", other),
    }

    execute_archive_in_workspace(
        change_id,
        repo_root.path(),
        acceptance_config
            .get_archive_command()
            .or_fail("unexpected error"),
        &acceptance_config,
        None,
        VcsBackend::Git,
        None,
        None,
        None,
        &ai_runner,
        &Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        &Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        &shared_stagger_state,
    )
    .await
    .or_fail("archive should pass when acceptance history records the final revision for handoff");

    assert!(
        repo_root.path().join("archive-ran.txt").exists(),
        "archive command should execute after acceptance pass with head change"
    );
}

#[tokio::test]
async fn test_dynamic_queue_injection() {
    use crate::tui::queue::DynamicQueue;
    use std::sync::Arc;
    use tokio::sync::mpsc;

    // Create a dynamic queue and add a change ID
    let queue = Arc::new(DynamicQueue::new());
    queue.push("test-change-2".to_string()).await;

    // Verify the queue has one item
    assert_eq!(queue.len().await, 1);

    // Create a simple parallel executor with the queue
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (tx, _rx) = mpsc::channel(10);
    let mut executor = ParallelExecutor::new(repo_root, config, Some(tx));
    executor.set_dynamic_queue(queue.clone());

    // The queue reference should be set
    assert!(executor.dynamic_queue.is_some());

    // After this point, the execute_with_reanalysis method would poll the queue
    // and inject the change into the execution. This is tested via integration tests.
}

#[tokio::test]
async fn test_should_reanalyze_bypasses_debounce_on_slot_recovery() {
    use std::time::Instant;
    use tokio::sync::mpsc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root, config, Some(tx));

    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(Instant::now());
    }

    assert!(
        executor.should_reanalyze(true).await,
        "explicit scheduler triggers should bypass debounce"
    );
    assert!(
        !executor.should_reanalyze(false).await,
        "regular queue edits should still respect debounce"
    );
}

#[tokio::test]
async fn test_queue_notification_with_fresh_debounce_starts_analysis_after_initial_iteration() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use std::time::Instant;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(Instant::now());
    }

    let mut queued = vec![make_test_change("fresh-queue-notification")];
    let mut in_flight = HashSet::new();
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 2,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("queue notification reanalysis should not fail");

    assert!(!should_break);
    assert_eq!(iteration, 3, "dispatch should advance after analysis");
    assert!(queued.is_empty());
    assert_eq!(in_flight.len(), 1);

    let mut saw_analysis_started = false;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::AnalysisStarted { attempt_id, .. } = event {
            saw_analysis_started = attempt_id.contains("iteration=2;trigger=queue;");
        }
    }
    assert!(
        saw_analysis_started,
        "fresh queue debounce must not suppress explicit queue notification analysis"
    );

    while join_set.join_next().await.is_some() {}
}

fn make_test_change(id: &str) -> crate::openspec::Change {
    crate::openspec::Change {
        id: id.to_string(),
        completed_tasks: 0,
        total_tasks: 1,
        last_modified: "now".to_string(),
        dependencies: Vec::new(),
        metadata: crate::openspec::ProposalMetadata::default(),
    }
}

#[tokio::test]
async fn capacity_zero_dispatch_diagnostic_guard_suppresses_identical_keys_and_emits_changed_keys()
{
    let (tx, mut rx) = mpsc::channel(8);
    let mut executor = ParallelExecutor::new(
        PathBuf::from("/tmp/cflx-capacity-zero-dedup-unit"),
        create_test_config(),
        Some(tx),
    );
    let queued = vec![make_test_change("change-a")];
    let in_flight = HashSet::from(["active-apply".to_string()]);
    let order = vec!["change-a".to_string()];

    executor
        .emit_capacity_zero_dispatch_diagnostic_once(&queued, &in_flight, 1, &order)
        .await;
    executor
        .emit_capacity_zero_dispatch_diagnostic_once(&queued, &in_flight, 1, &order)
        .await;

    let changed_order = vec!["change-b".to_string()];
    executor
        .emit_capacity_zero_dispatch_diagnostic_once(&queued, &in_flight, 1, &changed_order)
        .await;
    let changed_parallelism = 2;
    executor
        .emit_capacity_zero_dispatch_diagnostic_once(
            &queued,
            &in_flight,
            changed_parallelism,
            &order,
        )
        .await;

    drop(executor);

    let mut diagnostics = Vec::new();
    while let Some(event) = rx.recv().await {
        if let ExecutionEvent::Log(entry) = event {
            if entry
                .message
                .contains("dispatch_capacity_zero_after_analysis")
            {
                diagnostics.push(entry.message);
            }
        }
    }

    assert_eq!(
        diagnostics.len(),
        3,
        "initial signature plus two changed signatures should emit exactly three diagnostics; saw {diagnostics:?}"
    );
    assert!(
        diagnostics
            .iter()
            .any(|message| message.contains("max_parallelism=2")),
        "changed max_parallelism should emit a fresh diagnostic; saw {diagnostics:?}"
    );
}

fn dependent_ready_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies: HashMap::from([("dependent".to_string(), vec!["resolving".to_string()])]),
            groups: None,
        }
        .into()
    })
}

fn ready_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies: HashMap::new(),
            groups: None,
        }
        .into()
    })
}

fn blocked_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    let dependencies = changes
        .iter()
        .map(|change| (change.id.clone(), vec!["unresolved-dependency".to_string()]))
        .collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies,
            groups: None,
        }
        .into()
    })
}

fn declared_dependency_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    let dependencies = changes
        .iter()
        .map(|change| (change.id.clone(), change.dependencies.clone()))
        .collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies,
            groups: None,
        }
        .into()
    })
}

fn selective_dependency_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    let dependencies = changes
        .iter()
        .map(|change| {
            if change.id == "change-b" {
                (change.id.clone(), vec!["unresolved-dependency".to_string()])
            } else {
                (change.id.clone(), Vec::new())
            }
        })
        .collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies,
            groups: None,
        }
        .into()
    })
}

#[tokio::test]
async fn test_blocked_only_classifier_distinguishes_scheduler_work_classes() {
    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    let mut dependency_blocked = make_test_change("dependency-blocked");
    dependency_blocked.dependencies = vec!["missing-dependency".to_string()];
    let queued = vec![
        make_test_change("dispatchable"),
        make_test_change("manual-merge"),
        make_test_change("resolve-wait"),
        make_test_change("terminal-error"),
        dependency_blocked,
    ];
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            "dispatchable".to_string(),
            "manual-merge".to_string(),
            "resolve-wait".to_string(),
            "terminal-error".to_string(),
            "dependency-blocked".to_string(),
            "candidate-missing".to_string(),
        ],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue("candidate-missing".to_string()));
        // Ordinary candidates carry the queue intent an explicit start records
        // for them; the lane and terminal fixtures below are classified by their
        // own reducer-owned state.
        guard.apply_command(ReducerCommand::AddToQueue("dispatchable".to_string()));
        guard.apply_command(ReducerCommand::AddToQueue("dependency-blocked".to_string()));
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "manual-merge".to_string(),
            reason: "manual merge required".to_string(),
            auto_resumable: false,
        });
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "resolve-wait".to_string(),
            reason: "dirty base".to_string(),
            auto_resumable: false,
        });
        guard.apply_command(ReducerCommand::ResolveMerge("resolve-wait".to_string()));
        guard.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "terminal-error".to_string(),
            error: "boom".to_string(),
        });
    }

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.set_shared_orchestrator_state(shared);
    let classification = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;

    assert_eq!(
        classification.class_for("dispatchable"),
        Some(crate::parallel::queue_state::QueuedWorkClass::DispatchableApply)
    );
    assert_eq!(
        classification.class_for("manual-merge"),
        Some(crate::parallel::queue_state::QueuedWorkClass::ManualMergeWait)
    );
    assert_eq!(
        classification.class_for("resolve-wait"),
        Some(crate::parallel::queue_state::QueuedWorkClass::SchedulerLaneWait)
    );
    assert_eq!(
        classification.class_for("terminal-error"),
        Some(crate::parallel::queue_state::QueuedWorkClass::TerminalErrorRetryRequired)
    );
    assert_eq!(
        classification.class_for("dependency-blocked"),
        Some(crate::parallel::queue_state::QueuedWorkClass::DependencyBlocked)
    );
    assert_eq!(
        classification.class_for("candidate-missing"),
        Some(crate::parallel::queue_state::QueuedWorkClass::CandidateUnavailable)
    );
}

/// Queue reconciliation must keep an actively retried missing-verdict change as
/// in-progress acceptance work and only defer it as
/// `terminal_error_retry_required` once the protocol budget is exhausted.
#[tokio::test]
async fn queue_reconciliation_defers_missing_verdict_only_after_retry_exhaustion() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;

    let change_id = "missing-verdict-queue";
    let queued = vec![make_test_change(change_id)];
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
        guard.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: change_id.to_string(),
            command: "apply".to_string(),
        });
    }

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.set_shared_orchestrator_state(shared.clone());

    // While protocol-retry budget remains, no terminal error is reported, so
    // the change stays ordinary acceptance work.
    let during_retry = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;
    assert_ne!(
        during_retry.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::TerminalErrorRetryRequired),
        "an actively retried missing verdict must not be deferred as a terminal error"
    );
    assert!(during_retry.terminal_error_retry_required.is_empty());

    // Exhaustion is the first point at which the runtime reports a terminal error.
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: change_id.to_string(),
            error: crate::orchestration::acceptance::missing_verdict_exhausted_error(
                3,
                2,
                &["Monitoring verification".to_string()],
            ),
        });
    }

    let after_exhaustion = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;
    assert_eq!(
        after_exhaustion.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::TerminalErrorRetryRequired),
        "an exhausted missing verdict must reach the existing terminal-error deferral"
    );
}

#[tokio::test]
async fn test_blocked_only_resolve_wait_present() {
    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    let active_alpha = repo_dir.path().join("openspec/changes/alpha");
    std::fs::create_dir_all(&active_alpha).or_fail("create active alpha change dir");
    std::fs::write(active_alpha.join("proposal.md"), "# Alpha\n")
        .or_fail("write active alpha proposal");

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.resolve_wait_changes.insert("alpha".to_string());

    let mut beta = make_test_change("beta");
    beta.dependencies = vec!["alpha".to_string()];
    let queued = vec![beta];
    let in_flight = HashSet::new();

    assert!(
        executor
            .classify_queued_work(&queued, &in_flight)
            .await
            .is_blocked_only(),
        "fixture must still be blocked-only at the queue-classification layer"
    );
    assert!(
        !executor
            .is_blocked_only_scheduler_state(&queued, &in_flight)
            .await,
        "local resolve_wait entries must keep the scheduler alive until resolve dispatch or completion"
    );

    executor.resolve_wait_changes.clear();
    executor.reject_wait_changes.insert("alpha".to_string());
    assert!(
        !executor
            .is_blocked_only_scheduler_state(&queued, &in_flight)
            .await,
        "local reject_wait entries must also prevent blocked-only drain"
    );
}

#[tokio::test]
async fn test_blocked_only_reanalysis_skips_analyzer_for_merge_wait_and_terminal_error() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["manual-merge".to_string(), "terminal-error".to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "manual-merge".to_string(),
            reason: "manual merge required".to_string(),
            auto_resumable: false,
        });
        guard.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "terminal-error".to_string(),
            error: "boom".to_string(),
        });
    }

    let analyzer_calls = Arc::new(AtomicUsize::new(0));
    static BLOCKED_ONLY_ANALYZER_CALLS: std::sync::OnceLock<Arc<AtomicUsize>> =
        std::sync::OnceLock::new();
    let _ = BLOCKED_ONLY_ANALYZER_CALLS.set(analyzer_calls.clone());
    fn should_not_call_analysis_result<'a>(
        changes: &'a [crate::openspec::Change],
        _in_flight: &'a [String],
        _iteration: u32,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
    > {
        if let Some(calls) = BLOCKED_ONLY_ANALYZER_CALLS.get() {
            calls.fetch_add(1, Ordering::SeqCst);
        }
        let order: Vec<String> = changes.iter().map(|change| change.id.clone()).collect();
        Box::pin(async move {
            crate::analyzer::AnalysisResult {
                order,
                dependencies: HashMap::new(),
                groups: None,
            }
            .into()
        })
    }

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.set_shared_orchestrator_state(shared);
    let mut queued = vec![
        make_test_change("manual-merge"),
        make_test_change("terminal-error"),
    ];
    let mut in_flight = HashSet::new();
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &should_not_call_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(!should_break);
    assert_eq!(iteration, 1);
    assert_eq!(analyzer_calls.load(Ordering::SeqCst), 0);
    assert!(in_flight.is_empty());
    assert_eq!(queued.len(), 2);
    assert!(
        executor
            .is_blocked_only_scheduler_state(&queued, &in_flight)
            .await
    );
}

#[tokio::test]
async fn test_resolve_wait_completion_unblocks_dependents() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::{MergeResult, MergeResultOrigin, MergeTaskOutcome, WorkspaceResult};
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let alpha_dir = repo_dir.path().join("openspec/changes/alpha");
    std::fs::create_dir_all(&alpha_dir).or_fail("unexpected error");
    std::fs::write(alpha_dir.join("proposal.md"), "# Alpha\n").or_fail("unexpected error");
    let beta_dir = repo_dir.path().join("openspec/changes/beta");
    std::fs::create_dir_all(&beta_dir).or_fail("create beta change");
    std::fs::write(
        beta_dir.join("proposal.md"),
        "---\ndependencies:\n  - alpha\n---\n# Beta\n",
    )
    .or_fail("write beta proposal");
    std::fs::write(
        beta_dir.join("tasks.md"),
        "## Implementation Tasks\n- [ ] apply\n",
    )
    .or_fail("write beta tasks");
    Command::new("git")
        .args(["add", "."])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("stage fixture changes");
    Command::new("git")
        .args(["commit", "-m", "Add dependency fixtures"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("commit fixture changes");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.resolve_wait_changes.insert("alpha".to_string());

    let mut beta = make_test_change("beta");
    beta.dependencies = vec!["alpha".to_string()];
    let mut queued = vec![beta];
    let mut in_flight = HashSet::new();
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );

    assert!(
        !executor
            .should_exit_when_idle(true, &queued, &in_flight, None)
            .await,
        "finite scheduler must not exit while a dependency blocker is waiting on resolve_wait completion"
    );
    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &beta_depends_on_alpha_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("blocked pre-completion reanalysis should not fail");
    assert!(!should_break);
    assert_eq!(
        iteration, 1,
        "blocked-only beta must not dispatch before alpha resolves"
    );
    assert!(in_flight.is_empty());
    assert_eq!(queued.len(), 1);

    std::fs::remove_dir_all(&alpha_dir).or_fail("unexpected error");
    commit_archive_to_base(repo_dir.path(), "2026-05-13-alpha", "alpha").await;
    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    assert!(
        executor
            .handle_merge_result(MergeResult {
                change_id: "alpha".to_string(),
                workspace_name: "ws-alpha".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome: MergeTaskOutcome::Merged,
            })
            .await
            .is_merged(),
        "merged resolve_wait result should be treated as a successful base-lane completion"
    );
    assert!(
        executor.resolve_wait_changes.is_empty(),
        "merged resolve_wait result should clear local resolve_wait state"
    );

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration,
            reanalysis_reason: ReanalysisReason::ResolveCompletion,
            analyzer: &beta_depends_on_alpha_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("post-completion reanalysis should dispatch unblocked beta");

    assert!(!should_break);
    assert_eq!(
        iteration, 2,
        "dispatching beta should advance the scheduler iteration"
    );
    assert!(
        queued.is_empty(),
        "unblocked dependent should leave the queue"
    );
    assert!(
        in_flight.contains("beta"),
        "dependent beta should dispatch after alpha resolve_wait completion is merged"
    );

    while join_set.join_next().await.is_some() {}

    let mut saw_apply_started = false;
    while let Ok(Some(event)) =
        tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv()).await
    {
        if matches!(
            event,
            ExecutionEvent::ApplyStarted { change_id, .. } if change_id == "beta"
        ) {
            saw_apply_started = true;
        }
    }
    assert!(
        saw_apply_started,
        "dependent must emit ApplyStarted only after merged resolve completion"
    );
}

#[tokio::test]
async fn test_analyze_failure_diagnostic_dedupes_by_signature() {
    let (tx, mut rx) = tokio::sync::mpsc::channel(16);
    let mut executor = ParallelExecutor::new(
        PathBuf::from("/tmp/test-repo"),
        create_test_config(),
        Some(tx),
    );
    let queued = vec![make_test_change("alpha")];
    let in_flight = HashSet::new();

    executor
        .emit_analysis_failure_diagnostic_once(&queued, &in_flight, "InstanceRef not provided")
        .await;
    executor
        .emit_analysis_failure_diagnostic_once(&queued, &in_flight, "InstanceRef not provided")
        .await;
    executor
        .emit_analysis_failure_diagnostic_once(&queued, &in_flight, "different failure")
        .await;

    let mut error_count = 0;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::Error { message } = event {
            if message.contains("Dependency analysis failed") {
                error_count += 1;
            }
        }
    }
    assert_eq!(
        error_count, 2,
        "stable analysis failure signature should emit once"
    );
}

fn single_queued_route_depends_on_policy_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
            groups: None,
        }
        .into()
    })
}

fn beta_depends_on_alpha_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    _in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies: HashMap::from([("beta".to_string(), vec!["alpha".to_string()])]),
            groups: None,
        }
        .into()
    })
}

fn dependency_on_inflight_analysis_result<'a>(
    changes: &'a [crate::openspec::Change],
    in_flight: &'a [String],
    _iteration: u32,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
> {
    let order = changes.iter().map(|change| change.id.clone()).collect();
    let dependency = in_flight
        .first()
        .cloned()
        .unwrap_or_else(|| "policy".to_string());
    let dependencies = changes
        .iter()
        .map(|change| {
            if change.id == "route" {
                (change.id.clone(), vec![dependency.clone()])
            } else {
                (change.id.clone(), Vec::new())
            }
        })
        .collect();
    Box::pin(async move {
        crate::analyzer::AnalysisResult {
            order,
            dependencies,
            groups: None,
        }
        .into()
    })
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_apply_time_rejected_handoff_enters_rejecting_review_and_emits_change_rejected() {
    use crate::events::ExecutionEvent;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let change_id = "change-rejected";
    let change_dir = repo_dir
        .path()
        .join("openspec")
        .join("changes")
        .join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
    std::fs::write(
        change_dir.join("proposal.md"),
        "---\nchange_type: implementation\n---\n# Change\n",
    )
    .or_fail("unexpected error");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [ ] implement rejected flow\n",
    )
    .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Add change files"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some(
            "sh -c 'mkdir -p openspec/changes/{change_id}; printf "
                .to_string()
                + "\"# REJECTED\\n\\n- change_id: {change_id}\\n- reason: regression\\n\" > openspec/changes/{change_id}/REJECTED.md'",
        ),
        acceptance_command: Some("sh -c 'echo REJECTION_REVIEW: CONFIRM'".to_string()),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(128);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("unexpected error");

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("unexpected error");

    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    assert!(
        result.error.is_none(),
        "unexpected error: {:?}",
        result.error
    );
    assert!(
        result.rejected.is_some(),
        "rejected reason should be set after apply-time rejecting confirm"
    );
    assert!(
        result
            .rejected
            .as_deref()
            .unwrap_or_default()
            .contains("Rejecting review confirmed rejection"),
        "unexpected rejected reason: {:?}",
        result.rejected
    );

    let mut saw_rejecting_status = false;
    let mut saw_change_rejected = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::WorkspaceStatusUpdated {
                change_id: id,
                status,
                ..
            } if id == change_id && status == WorkspaceStatus::Rejecting => {
                saw_rejecting_status = true;
            }
            ExecutionEvent::ChangeRejected { change_id: id, .. } if id == change_id => {
                saw_change_rejected = true;
            }
            _ => {}
        }
    }

    assert!(
        saw_rejecting_status,
        "apply-time rejected handoff must emit WorkspaceStatus::Rejecting"
    );
    assert!(
        saw_change_rejected,
        "confirmed rejecting review must emit ChangeRejected"
    );
}

#[tokio::test]
async fn dynamic_queue_ingestion_skips_final_terminal_merged_change() {
    use crate::tui::queue::DynamicQueue;

    let queue = Arc::new(DynamicQueue::new());
    queue.push("alpha".to_string()).await;

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        1,
    )));
    shared
        .write()
        .await
        .apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "rev".to_string(),
        });

    let mut executor =
        ParallelExecutor::new(PathBuf::from("/tmp/test-repo"), create_test_config(), None);
    executor.set_dynamic_queue(queue);
    executor.set_shared_orchestrator_state(shared);

    let mut queued = Vec::new();
    let in_flight = HashSet::new();
    let mut reason = crate::parallel::dynamic_queue::ReanalysisReason::Initial;

    let changed = executor
        .check_dynamic_queue_and_add_changes(&mut queued, &in_flight, &mut reason)
        .await;

    assert!(!changed);
    assert!(queued.is_empty());
    assert_eq!(
        reason,
        crate::parallel::dynamic_queue::ReanalysisReason::Initial
    );
}

#[tokio::test]
async fn final_terminal_dispatch_preflight_skips_before_workspace_execution() {
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        1,
    )));
    shared
        .write()
        .await
        .apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "rev".to_string(),
        });

    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(tx),
    );
    executor.set_shared_orchestrator_state(shared);
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            "alpha".to_string(),
            "base".to_string(),
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch should skip cleanly");

    assert!(in_flight.is_empty());
    assert!(join_set.join_next().await.is_none());
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::ArchiveStarted { ref change_id, .. }
            | ExecutionEvent::ApplyStarted { ref change_id, .. }
            | ExecutionEvent::AcceptanceStarted { ref change_id, .. }
                if change_id == "alpha" =>
            {
                panic!("final terminal dispatch must not emit execution event: {event:?}");
            }
            _ => {}
        }
    }
}

#[tokio::test]
async fn test_dependency_blocked_event_is_emitted_even_when_slots_are_full() {
    use crate::events::ExecutionEvent;
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("change-a"), make_test_change("change-b")];
    let mut in_flight = HashSet::new();

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &selective_dependency_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(!should_break);
    assert_eq!(iteration, 2);
    assert_eq!(in_flight.len(), 1, "ready change should consume the slot");

    let mut saw_blocked_event = false;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::DependencyBlocked {
            change_id,
            dependency_ids,
        } = event
        {
            if change_id == "change-b" {
                assert_eq!(dependency_ids, vec!["unresolved-dependency".to_string()]);
                saw_blocked_event = true;
            }
        }
    }

    assert!(
        saw_blocked_event,
        "dependency-blocked event must be emitted even if available slots are already consumed"
    );

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_single_queued_active_not_queued_dependency_blocks_dispatch_selection() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "route", &["policy"]);
    let policy_dir = repo_dir.path().join("openspec/changes/policy");
    std::fs::create_dir_all(&policy_dir).or_fail("unexpected error");
    std::fs::write(policy_dir.join("proposal.md"), "# Policy\n").or_fail("unexpected error");

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert!(
        selected.is_empty(),
        "route must not dispatch while policy is active but not queued"
    );
    let dependency_events = drain_dependency_events(&mut rx, "route");
    assert_eq!(dependency_events, vec!["blocked:policy".to_string()]);
}

#[tokio::test]
async fn test_single_queued_archived_dependency_waits_until_merged() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "route", &["policy"]);
    let archived_dir = repo_dir
        .path()
        .join("openspec/changes/archive/2026-05-13-policy");
    std::fs::create_dir_all(&archived_dir).or_fail("unexpected error");
    std::fs::write(archived_dir.join("proposal.md"), "# Policy\n").or_fail("unexpected error");

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert!(
        selected.is_empty(),
        "archived dependency must wait for base-branch merge evidence"
    );
    assert_eq!(
        drain_dependency_events(&mut rx, "route"),
        vec!["blocked:policy".to_string()],
        "archived-but-not-merged dependency should emit one dependency-blocked event"
    );
}

#[tokio::test]
async fn test_single_queued_archived_dependency_can_dispatch_after_merge() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "route", &["policy"]);
    commit_archive_to_base(repo_dir.path(), "2026-05-13-policy", "policy").await;

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert_eq!(selected, vec!["route".to_string()]);
    assert!(
        drain_dependency_events(&mut rx, "route").is_empty(),
        "merged archived dependency should be satisfied without dependency-blocked events"
    );
}

#[tokio::test]
async fn test_archived_dependency_uses_effective_integration_base_after_startup() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "route", &["policy"]);

    let archived_dir = repo_dir
        .path()
        .join("openspec/changes/archive/2026-05-13-policy");
    std::fs::create_dir_all(&archived_dir).or_fail("unexpected error");
    std::fs::write(archived_dir.join("proposal.md"), "# Archived policy\n")
        .or_fail("unexpected error");

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let initially_blocked = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;
    assert!(
        initially_blocked.is_empty(),
        "archived-but-not-merged dependency should capture startup branch and remain blocked"
    );
    assert_eq!(
        drain_dependency_events(&mut rx, "route"),
        vec!["blocked:policy".to_string()]
    );

    let startup_branch_has_archive =
        crate::execution::state::is_merged_to_base("policy", repo_dir.path(), "main")
            .await
            .or_fail("unexpected error");
    assert!(
        !startup_branch_has_archive,
        "test fixture must prove the original startup branch lacks the archive merge before integration advances"
    );

    Command::new("git")
        .args(["checkout", "-b", "integration"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Archive policy on integration"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("unexpected error");

    let integration_has_archive =
        crate::execution::state::is_merged_to_base("policy", repo_dir.path(), "integration")
            .await
            .or_fail("unexpected error");
    assert!(
        integration_has_archive,
        "test fixture must prove the effective integration base contains the archive merge"
    );

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert_eq!(
        selected,
        vec!["route".to_string()],
        "archived dependency merged into the effective integration base should unblock dispatch even when startup branch is unchanged"
    );
    assert_eq!(
        drain_dependency_events(&mut rx, "route"),
        vec!["resolved".to_string()],
        "effective-base merge should resolve the previous archived dependency blocker"
    );

    let main_has_archive =
        crate::execution::state::is_merged_to_base("policy", repo_dir.path(), "main")
            .await
            .or_fail("unexpected error");
    assert!(
        !main_has_archive,
        "test fixture must prove the original startup branch still lacks the archive merge"
    );
}

#[tokio::test]
async fn dependency_resolving_dependents_wait_until_merged() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "change-b", &["change-a"]);
    write_change_proposal(repo_dir.path(), "change-c", &["change-a"]);
    let archived_dir = repo_dir
        .path()
        .join("openspec/changes/archive/2026-05-13-change-a");
    std::fs::create_dir_all(&archived_dir).or_fail("unexpected error");
    std::fs::write(archived_dir.join("proposal.md"), "# Change A\n").or_fail("unexpected error");

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["change-b".to_string(), "change-c".to_string()],
        dependencies: HashMap::from([
            ("change-b".to_string(), vec!["change-a".to_string()]),
            ("change-c".to_string(), vec!["change-a".to_string()]),
        ]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 2, &in_flight)
        .await;

    assert!(
        selected.is_empty(),
        "B/C dependents must not dispatch while A is archived locally but not merged to base"
    );
    let mut blocked_events = Vec::new();
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::DependencyBlocked {
            change_id,
            dependency_ids,
        } = event
        {
            blocked_events.push(format!("{change_id}:{}", dependency_ids.join(",")));
        }
    }
    blocked_events.sort();
    assert_eq!(
        blocked_events,
        vec![
            "change-b:change-a".to_string(),
            "change-c:change-a".to_string(),
        ]
    );
}

#[tokio::test]
async fn test_single_queued_dependency_block_classes_fail_closed() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    for dep_id in ["ghost", "rejected-policy", "inflight-policy"] {
        write_change_proposal(repo_dir.path(), &format!("route-{dep_id}"), &[dep_id]);
    }
    let rejected_dir = repo_dir.path().join("openspec/changes/rejected-policy");
    std::fs::create_dir_all(&rejected_dir).or_fail("unexpected error");
    std::fs::write(rejected_dir.join("proposal.md"), "# Rejected Policy\n")
        .or_fail("unexpected error");
    std::fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED\n").or_fail("unexpected error");

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let in_flight = HashSet::from(["inflight-policy".to_string()]);

    for dep_id in ["ghost", "rejected-policy", "inflight-policy"] {
        let analysis_result = crate::analyzer::AnalysisResult {
            order: vec![format!("route-{dep_id}")],
            dependencies: HashMap::from([(format!("route-{dep_id}"), vec![dep_id.to_string()])]),
            groups: None,
        };
        let selected = executor
            .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
            .await;
        assert!(
            selected.is_empty(),
            "dependency {dep_id} must fail closed before dispatch"
        );
    }

    let mut blocked_events = Vec::new();
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::DependencyBlocked {
            change_id,
            dependency_ids,
        } = event
        {
            blocked_events.push(format!("{change_id}:{}", dependency_ids.join(",")));
        }
    }
    blocked_events.sort();
    assert_eq!(
        blocked_events,
        vec![
            "route-ghost:ghost".to_string(),
            "route-inflight-policy:inflight-policy".to_string(),
            "route-rejected-policy:rejected-policy".to_string(),
        ]
    );
}

#[tokio::test]
async fn test_single_queued_active_dependency_does_not_emit_apply_started() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "route", &["policy"]);
    let policy_dir = repo_dir.path().join("openspec/changes/policy");
    std::fs::create_dir_all(&policy_dir).or_fail("unexpected error");
    std::fs::write(policy_dir.join("proposal.md"), "# Policy\n").or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("route")];
    let mut in_flight = HashSet::new();

    let (_should_break, _iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &single_queued_route_depends_on_policy_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(
        !in_flight.contains("route"),
        "route must not enter in-flight while policy is active but not queued"
    );

    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::ApplyStarted { change_id, .. } if change_id == "route" => {
                panic!("route must not emit ApplyStarted before policy resolves")
            }
            ExecutionEvent::ProcessingStarted(change_id) if change_id == "route" => {
                panic!("route must not emit ProcessingStarted before policy resolves")
            }
            _ => {}
        }
    }
}

#[tokio::test]
async fn test_inflight_dependency_blocks_dispatch_until_resolved() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("route")];
    let mut in_flight = HashSet::from(["policy".to_string()]);

    let (_should_break, _iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 2,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &dependency_on_inflight_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(
        !in_flight.contains("route"),
        "route must not dispatch while policy is in-flight and unmerged"
    );

    let mut saw_blocked = false;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::DependencyBlocked {
            change_id,
            dependency_ids,
        } = event
        {
            if change_id == "route" && dependency_ids == vec!["policy".to_string()] {
                saw_blocked = true;
            }
        }
    }
    assert!(
        saw_blocked,
        "in-flight dependency should emit DependencyBlocked"
    );
}

#[tokio::test]
async fn test_dependency_blocked_event_emits_once_for_unchanged_snapshot() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["ghost".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let first_selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;
    let second_selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert!(first_selected.is_empty());
    assert!(second_selected.is_empty());
    let blocked_events = drain_dependency_events(&mut rx, "route");
    assert_eq!(
        blocked_events,
        vec!["blocked:ghost".to_string()],
        "unchanged blocker fingerprint should emit one DependencyBlocked event"
    );
}

#[tokio::test]
async fn test_changed_dependency_blocker_snapshot_emits_again() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let in_flight = HashSet::new();
    let missing_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["ghost".to_string()])]),
        groups: None,
    };
    let queued_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string(), "policy".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
        groups: None,
    };

    let missing_selected = executor
        .select_changes_for_dispatch(&missing_analysis, 1, &in_flight)
        .await;
    let queued_selected = executor
        .select_changes_for_dispatch(&queued_analysis, 1, &in_flight)
        .await;

    assert!(missing_selected.is_empty());
    assert_eq!(queued_selected, vec!["policy".to_string()]);
    let blocked_events = drain_dependency_events(&mut rx, "route");
    assert_eq!(
        blocked_events,
        vec!["blocked:ghost".to_string(), "blocked:policy".to_string()],
        "changed blocker fingerprint should emit another DependencyBlocked event"
    );
}

#[tokio::test]
async fn test_dependency_resolved_emits_once_and_blocked_again_can_emit() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let in_flight = HashSet::new();
    let blocked_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["ghost".to_string()])]),
        groups: None,
    };
    let ready_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::new(),
        groups: None,
    };

    let first_blocked = executor
        .select_changes_for_dispatch(&blocked_analysis, 1, &in_flight)
        .await;
    let first_ready = executor
        .select_changes_for_dispatch(&ready_analysis, 1, &in_flight)
        .await;
    let second_ready = executor
        .select_changes_for_dispatch(&ready_analysis, 1, &in_flight)
        .await;
    let second_blocked = executor
        .select_changes_for_dispatch(&blocked_analysis, 1, &in_flight)
        .await;

    assert!(first_blocked.is_empty());
    assert_eq!(first_ready, vec!["route".to_string()]);
    assert_eq!(second_ready, vec!["route".to_string()]);
    assert!(second_blocked.is_empty());
    let dependency_events = drain_dependency_events(&mut rx, "route");
    assert_eq!(
        dependency_events,
        vec![
            "blocked:ghost".to_string(),
            "resolved".to_string(),
            "blocked:ghost".to_string(),
        ],
        "resolved transition should emit once and a later blocked transition should emit again"
    );
}

#[tokio::test]
async fn test_dependency_suppression_state_does_not_change_dispatch_selection() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, _rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let in_flight = HashSet::new();
    let blocked_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string(), "policy".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["policy".to_string()])]),
        groups: None,
    };

    let before = executor
        .select_changes_for_dispatch(&blocked_analysis, 2, &in_flight)
        .await;
    assert_eq!(before, vec!["policy".to_string()]);
    assert!(
        executor
            .dependency_blocker_fingerprints
            .contains_key("route"),
        "diagnostic fingerprint should be stored only after deriving blockers"
    );

    let after = executor
        .select_changes_for_dispatch(&blocked_analysis, 2, &in_flight)
        .await;
    assert_eq!(
        after,
        vec!["policy".to_string()],
        "in-memory diagnostic suppression must not alter dispatch selection"
    );
}

fn drain_dependency_events(
    rx: &mut tokio::sync::mpsc::Receiver<ExecutionEvent>,
    target_change_id: &str,
) -> Vec<String> {
    let mut events = Vec::new();
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::DependencyBlocked {
                change_id,
                dependency_ids,
            } if change_id == target_change_id => {
                events.push(format!("blocked:{}", dependency_ids.join(",")));
            }
            ExecutionEvent::DependencyResolved { change_id } if change_id == target_change_id => {
                events.push("resolved".to_string());
            }
            _ => {}
        }
    }
    events
}

/// The regression: a suppressed duplicate diagnostic must not be able to leave
/// the reducer describing an unresolved dependency wait as plain `queued`.
///
/// Integration scope — a real Git repository, the real scheduler classification
/// path, and the real reducer — because the defect lived in the seam between
/// the edge-triggered event and the state projection, which no in-memory double
/// can reproduce.
#[tokio::test]
async fn dependency_blocker_projection_rebuild_survives_deduplicated_diagnostics() {
    use crate::orchestration::state::{OrchestratorState, ReducerCommand};

    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
        vec!["route".to_string()],
        0,
    )));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("route".to_string()));
    executor.set_shared_orchestrator_state(shared.clone());

    let blocked_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["ghost".to_string()])]),
        groups: None,
    };
    let ready_analysis = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::new(),
        groups: None,
    };
    let in_flight = HashSet::new();

    // ── First classification: blocked, projected, announced once ────────────
    assert!(executor
        .select_changes_for_dispatch(&blocked_analysis, 1, &in_flight)
        .await
        .is_empty());
    {
        let guard = shared.read().await;
        assert_eq!(guard.display_status("route"), "blocked");
        let blocker = guard.blocker_view("route").expect("structured blocker");
        assert_eq!(
            blocker.kind,
            crate::orchestration::state::BlockerKind::Dependency
        );
        assert_eq!(blocker.dependencies, vec!["ghost".to_string()]);
    }

    // ── Unchanged fingerprint: still no second diagnostic, still blocked ────
    assert!(executor
        .select_changes_for_dispatch(&blocked_analysis, 1, &in_flight)
        .await
        .is_empty());
    assert_eq!(
        shared.read().await.display_status("route"),
        "blocked",
        "a suppressed duplicate diagnostic must not withdraw the current blocker"
    );

    // ── Projection replaced mid-wait, fingerprints untouched ────────────────
    //
    // A refresh, a reducer rebuild, or any loss of the projection while the
    // dependency is still unresolved. Nothing about the blocker changed, so the
    // deduplication store will emit nothing; the reconciliation path is the
    // only thing that can restore the wait.
    {
        let mut guard = shared.write().await;
        *guard = OrchestratorState::new(vec!["route".to_string()], 0);
        guard.apply_command(ReducerCommand::AddToQueue("route".to_string()));
        assert_eq!(guard.display_status("route"), "queued");
    }
    assert!(executor
        .select_changes_for_dispatch(&blocked_analysis, 1, &in_flight)
        .await
        .is_empty());
    {
        let guard = shared.read().await;
        assert_eq!(
            guard.display_status("route"),
            "blocked",
            "a rebuilt projection must be restored from classification, not from a changed fingerprint"
        );
        assert_eq!(
            guard.blocker_view("route").expect("blocker").dependencies,
            vec!["ghost".to_string()]
        );
    }

    // Three coherent classifications, one operator diagnostic: deduplication is
    // preserved exactly, and it is no longer current-state authority.
    assert_eq!(
        drain_dependency_events(&mut rx, "route"),
        vec!["blocked:ghost".to_string()],
        "an unchanged blocker fingerprint stays a single announced transition"
    );

    // ── Resolution: the wait is withdrawn and dispatch resumes ──────────────
    assert_eq!(
        executor
            .select_changes_for_dispatch(&ready_analysis, 1, &in_flight)
            .await,
        vec!["route".to_string()],
        "dispatch selection is unchanged by the projection work"
    );
    {
        let guard = shared.read().await;
        assert_eq!(
            guard.display_status("route"),
            "queued",
            "the retained queue intent decides the display once evidence resolves"
        );
        assert!(guard.blocker_view("route").is_none());
    }
}

#[tokio::test]
async fn test_archived_dependency_is_blocked_without_rejection_until_merged() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "route", &["contracts"]);
    let archived_dir = repo_dir
        .path()
        .join("openspec")
        .join("changes")
        .join("archive")
        .join("2026-04-29-contracts");
    std::fs::create_dir_all(&archived_dir).or_fail("unexpected error");
    std::fs::write(archived_dir.join("proposal.md"), "# Archived").or_fail("unexpected error");

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["contracts".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert!(selected.is_empty());
    let dependency_events = drain_dependency_events(&mut rx, "route");
    assert_eq!(dependency_events, vec!["blocked:contracts".to_string()]);
    while let Ok(event) = rx.try_recv() {
        assert!(
            !matches!(event, ExecutionEvent::ChangeRejected { .. }),
            "archived dependency must not emit ChangeRejected"
        );
    }
}

#[tokio::test]
async fn test_missing_dependency_fails_closed_without_dispatch() {
    let repo_dir = tempfile::TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let analysis_result = crate::analyzer::AnalysisResult {
        order: vec!["route".to_string()],
        dependencies: HashMap::from([("route".to_string(), vec!["ghost".to_string()])]),
        groups: None,
    };
    let in_flight = HashSet::new();

    let selected = executor
        .select_changes_for_dispatch(&analysis_result, 1, &in_flight)
        .await;

    assert!(selected.is_empty(), "missing dependency must not dispatch");
    let mut saw_missing_diagnostic = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::Error { message } if message.contains("missing dependency 'ghost'") => {
                saw_missing_diagnostic = true;
            }
            ExecutionEvent::ChangeRejected { .. } => {
                panic!("missing dependency should fail closed without ChangeRejected")
            }
            _ => {}
        }
    }
    assert!(
        saw_missing_diagnostic,
        "missing dependency diagnostic should be emitted"
    );
}

#[tokio::test]
async fn test_slot_release_reanalyzes_and_dispatches_queued_follow_up_changes() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    // The resolving change holds the lifecycle slot it was admitted with; that
    // membership, not a phase counter, is what admission is computed from.
    executor
        .lifecycle_slots
        .occupy_now(
            "resolving-change",
            crate::parallel::lifecycle_slots::SlotPhase::Merge,
        )
        .await;

    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(std::time::Instant::now());
    }

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![
        make_test_change("follow-up-a"),
        make_test_change("follow-up-b"),
    ];
    let mut in_flight = HashSet::new();

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 2,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(
        !should_break,
        "scheduler should keep running while resolve holds the slot"
    );
    assert_eq!(
        iteration, 2,
        "no dispatch should happen while available slots are zero"
    );
    assert_eq!(
        queued.len(),
        2,
        "queued follow-up changes should remain queued"
    );
    assert!(
        in_flight.is_empty(),
        "nothing should dispatch before the slot is released"
    );

    // The resolve settles, releasing the slot its change owned.
    executor.lifecycle_slots.release("resolving-change");

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(
        !should_break,
        "scheduler should continue after dispatching resumed queued work"
    );
    assert_eq!(
        iteration, 3,
        "dispatch should advance the scheduler iteration"
    );
    assert_eq!(
        queued.len(),
        1,
        "one follow-up change should dispatch immediately after slot recovery"
    );
    assert_eq!(
        in_flight.len(),
        1,
        "slot recovery should move a queued follow-up change into flight"
    );

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_resolve_wait_does_not_block_queue_reanalysis_dispatch() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    executor
        .resolve_wait_changes
        .insert("still-resolving".to_string());

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("queued-during-resolve-wait")];
    let mut in_flight = HashSet::new();

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(!should_break);
    assert_eq!(iteration, 2);
    assert!(queued.is_empty());
    assert_eq!(in_flight.len(), 1);

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_resolving_with_free_slot_still_dispatches_queued_change() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    // gamma has scheduler-visible retry intent, while alpha is already consuming one slot.
    executor
        .resolve_wait_changes
        .insert("gamma-merge-wait".to_string());

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("beta-queued")];
    let mut in_flight = HashSet::from(["alpha-resolving".to_string()]);

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 2,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(!should_break);
    assert_eq!(iteration, 2, "free slot should advance scheduler iteration");
    assert!(queued.is_empty(), "queued change should be dispatched");
    assert_eq!(
        in_flight.len(),
        2,
        "queued change should dispatch even when another change is resolving"
    );
    assert!(
        in_flight.contains("beta-queued"),
        "beta must become in-flight when slot is available"
    );

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_dispatch_zero_reanalysis_is_retried_on_next_loop() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("queued-after-zero-dispatch")];
    let mut in_flight = HashSet::new();

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::QueueNotification,
            analyzer: &blocked_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(!should_break);
    assert_eq!(iteration, 1, "dispatch 0件では iteration は進まない");
    assert_eq!(queued.len(), 1, "dispatchできない change はキューに残る");
    assert!(in_flight.is_empty());

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration,
            reanalysis_reason: ReanalysisReason::ResolveCompletion,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(!should_break);
    assert_eq!(
        iteration, 2,
        "次ループ再評価で dispatch され iteration が進む"
    );
    assert!(queued.is_empty(), "再評価後にキューが消化される");
    assert_eq!(in_flight.len(), 1, "再評価後に change が in-flight になる");

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_resolve_completion_reanalysis_bypasses_debounce_and_dispatches_work() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(std::time::Instant::now());
    }

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("follow-up-after-resolve")];
    let mut in_flight = HashSet::new();

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 2,
            reanalysis_reason: ReanalysisReason::ResolveCompletion,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(
        !should_break,
        "resolve completion should resume the scheduler instead of terminating it"
    );
    assert_eq!(
        iteration, 3,
        "resolve completion should immediately trigger a dispatch iteration"
    );
    assert!(
        queued.is_empty(),
        "resolve completion should dispatch queued work without waiting for debounce"
    );
    assert_eq!(
        in_flight.len(),
        1,
        "queued work should become in-flight after resolve completion"
    );

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_repair_candidate_reanalysis_bypasses_debounce_and_dispatches_work() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::parallel::WorkspaceResult;
    use crate::vcs::VcsBackend;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    let workspace_base = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(std::time::Instant::now());
    }

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut queued = vec![make_test_change("repair-after-archive")];
    let mut in_flight = HashSet::new();

    let (should_break, iteration) = executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            max_parallelism: 1,
            iteration: 2,
            reanalysis_reason: ReanalysisReason::RepairCandidate,
            analyzer: &ready_analysis_result,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("unexpected error");

    assert!(
        !should_break,
        "repair candidate should resume the scheduler instead of terminating it"
    );
    assert_eq!(
        iteration, 3,
        "repair candidate should immediately trigger a dispatch iteration"
    );
    assert!(
        queued.is_empty(),
        "repair candidate should dispatch queued work without waiting for queue debounce"
    );
    assert_eq!(
        in_flight.len(),
        1,
        "repair candidate should become in-flight after repair-triggered analysis"
    );

    while join_set.join_next().await.is_some() {}
}

#[tokio::test]
async fn test_rejected_workspace_completion_retries_deferred_merges() {
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor
        .resolve_wait_changes
        .insert("blocked-change".to_string());

    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);
    let mut in_flight = HashSet::new();
    in_flight.insert("blocked-change".to_string());

    executor
        .handle_workspace_completion(
            WorkspaceResult {
                change_id: "blocked-change".to_string(),
                workspace_name: "ws-blocked-change".to_string(),
                final_revision: None,
                error: None,
                rejected: Some("confirmed rejection".to_string()),
            },
            1,
            &mut in_flight,
            &merge_result_tx,
        )
        .await;

    assert!(
        executor.resolve_wait_changes.is_empty(),
        "rejecting completion must trigger deferred-merge retry and clear orphaned resolve-wait entries"
    );
}

#[tokio::test]
async fn test_rejection_review_failure_retries_deferred_merges() {
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor
        .resolve_wait_changes
        .insert("blocked-change".to_string());

    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);
    let mut in_flight = HashSet::new();
    in_flight.insert("blocked-change".to_string());

    executor
        .handle_workspace_completion(
            WorkspaceResult {
                change_id: "blocked-change".to_string(),
                workspace_name: "ws-blocked-change".to_string(),
                final_revision: None,
                error: Some("rejecting review failed".to_string()),
                rejected: None,
            },
            1,
            &mut in_flight,
            &merge_result_tx,
        )
        .await;

    assert!(
        executor.resolve_wait_changes.is_empty(),
        "rejecting failure must trigger deferred-merge retry and clear orphaned resolve-wait entries"
    );
}

#[tokio::test]
async fn test_handle_merge_result_keeps_pending_counter_non_negative() {
    use crate::parallel::{MergeResult, MergeResultOrigin, MergeTaskOutcome};
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    executor.pending_merge_count.store(2, Ordering::Relaxed);
    assert_eq!(
        executor
            .handle_merge_result(MergeResult {
                change_id: "change-ok".to_string(),
                workspace_name: "ws-change-ok".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: MergeTaskOutcome::Merged,
            })
            .await,
        MergeResultDisposition::Merged
    );
    assert_eq!(executor.pending_merge_count.load(Ordering::Relaxed), 1);

    assert_eq!(
        executor
            .handle_merge_result(MergeResult {
                change_id: "change-err".to_string(),
                workspace_name: "ws-change-err".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: MergeTaskOutcome::run_fatal("merge failed"),
            })
            .await,
        MergeResultDisposition::AbortRun
    );
    assert_eq!(executor.pending_merge_count.load(Ordering::Relaxed), 0);
}

#[tokio::test]
async fn fix_scheduler_premature_exit_decrements_pending_merge_counter_on_merge_completion() {
    use crate::parallel::{MergeResult, MergeResultOrigin, MergeTaskOutcome};
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);

    let disposition = executor
        .handle_merge_result(MergeResult {
            change_id: "change-ok".to_string(),
            workspace_name: "ws-change-ok".to_string(),
            origin: MergeResultOrigin::PostArchiveMerge,
            outcome: MergeTaskOutcome::Merged,
        })
        .await;

    assert!(
        disposition.is_merged(),
        "actual merged background outcomes must trigger success-only scheduler follow-up"
    );
    assert_eq!(
        executor.pending_merge_count.load(Ordering::Relaxed),
        0,
        "scheduler must clear pending merge counter after merge result is handled"
    );
}

#[tokio::test]
async fn test_handle_merge_result_deferred_is_not_successful_completion() {
    use crate::parallel::{MergeResult, MergeResultOrigin, MergeTaskOutcome};
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    executor.resolve_wait_changes.insert("beta".to_string());

    let disposition = executor
        .handle_merge_result(MergeResult {
            change_id: "alpha".to_string(),
            workspace_name: "ws-alpha".to_string(),
            origin: MergeResultOrigin::PostArchiveMerge,
            outcome: MergeTaskOutcome::deferred("archive verification incomplete", false),
        })
        .await;

    assert_eq!(
        disposition,
        MergeResultDisposition::Deferred,
        "deferred background merge outcomes must not be reported as completed merges"
    );
    assert!(
        !executor.had_change_failures(),
        "a deferral is pending work, not a change failure"
    );
    assert_eq!(executor.pending_merge_count.load(Ordering::Relaxed), 0);
    assert!(
        executor.resolve_wait_changes.contains("beta"),
        "deferred merge result handling must not run success-only retry_deferred_base_lane_waiters"
    );
}

/// Only a run-fatal outcome may reach the single global-Error owner, and when it
/// does it must ask for an abort rather than a decorated continuation.
#[tokio::test]
async fn run_fatal_merge_result_emits_one_global_error_and_requests_abort() {
    use crate::parallel::{MergeResult, MergeResultOrigin, MergeTaskOutcome};
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);

    let disposition = executor
        .handle_merge_result(MergeResult {
            change_id: "alpha".to_string(),
            workspace_name: "ws-alpha".to_string(),
            origin: MergeResultOrigin::PostArchiveMerge,
            outcome: MergeTaskOutcome::run_fatal("merge failed hard"),
        })
        .await;

    assert_eq!(disposition, MergeResultDisposition::AbortRun);
    let event = rx.try_recv().or_fail("expected merge failure event");
    match event {
        ExecutionEvent::Error { message } => {
            assert!(message.contains("alpha"), "missing change id: {message}");
            assert!(
                message.contains("ws-alpha"),
                "missing workspace name: {message}"
            );
            assert!(
                message.contains("merge failed hard"),
                "missing error: {message}"
            );
        }
        other => panic!("expected error event, got {other:?}"),
    }

    // A second fatal result arriving during the bounded drain must not add a
    // second global Error: the run is already aborting.
    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    assert_eq!(
        executor
            .handle_merge_result(MergeResult {
                change_id: "beta".to_string(),
                workspace_name: "ws-beta".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: MergeTaskOutcome::run_fatal("second fatal outcome"),
            })
            .await,
        MergeResultDisposition::AbortRun
    );
    assert!(
        rx.try_recv().is_err(),
        "an aborting run emits exactly one global Error"
    );
}

/// The regression this change exists for: bounded post-archive resolve
/// exhaustion is change-local, so the queue wrapper must not wrap it in a global
/// Error, and the run must keep going.
#[tokio::test]
async fn resolve_exhausted_merge_result_continues_without_a_global_error() {
    use crate::parallel::{
        MergeResult, MergeResultOrigin, MergeTaskOutcome, ResolveFailureClassification,
    };
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));

    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);

    let disposition = executor
        .handle_merge_result(MergeResult {
            change_id: "alpha".to_string(),
            workspace_name: "ws-alpha".to_string(),
            origin: MergeResultOrigin::PostArchiveMerge,
            outcome: MergeTaskOutcome::resolve_exhausted(
                "alpha",
                3,
                ResolveFailureClassification::UnresolvedConflict,
                "conflicts remain",
            ),
        })
        .await;

    assert_eq!(disposition, MergeResultDisposition::ContinueWithErrors);
    assert_eq!(executor.pending_merge_count.load(Ordering::Relaxed), 0);
    assert!(
        executor.had_change_failures(),
        "a change-local failure must be remembered for truthful terminal reporting"
    );
    assert!(
        executor.run_fatal_abort.is_none(),
        "an exhausted resolve must never request a run abort"
    );
    assert!(
        rx.try_recv().is_err(),
        "the queue wrapper must not emit a global Error for an already-classified change failure"
    );
}

/// Publication and hook failures keep their own typed owners across the shared
/// boundary; the queue must neither duplicate nor escalate them.
#[tokio::test]
async fn already_reported_merge_results_are_never_promoted_to_global_errors() {
    use crate::parallel::{
        AlreadyReportedFailureKind, MergeResult, MergeResultOrigin, MergeTaskOutcome,
    };
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    for kind in [
        AlreadyReportedFailureKind::Push,
        AlreadyReportedFailureKind::Hook,
        AlreadyReportedFailureKind::RejectionReview,
    ] {
        let config = create_test_config();
        let (tx, mut rx) = mpsc::channel(32);
        let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
        executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);

        let disposition = executor
            .handle_merge_result(MergeResult {
                change_id: "alpha".to_string(),
                workspace_name: "ws-alpha".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: MergeTaskOutcome::already_reported(
                    "alpha",
                    kind,
                    "already reported by its typed owner",
                ),
            })
            .await;

        assert_eq!(
            disposition,
            MergeResultDisposition::ContinueWithErrors,
            "{:?} must continue the run",
            kind
        );
        assert!(
            executor.run_fatal_abort.is_none(),
            "{:?} must not fall through to a run-fatal abort",
            kind
        );
        assert!(
            rx.try_recv().is_err(),
            "{:?} already emitted its lifecycle event; a duplicate global Error is forbidden",
            kind
        );
    }
}

/// Ownership release is independent of severity: every outcome returns the
/// pending counter, and every non-merged spawned-retry outcome returns the lane.
#[tokio::test]
async fn every_outcome_releases_pending_accounting_regardless_of_severity() {
    use crate::parallel::{
        AlreadyReportedFailureKind, MergeResult, MergeResultOrigin, MergeTaskOutcome,
        ResolveFailureClassification,
    };
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let outcomes = [
        MergeTaskOutcome::Merged,
        MergeTaskOutcome::deferred("base lane busy", true),
        MergeTaskOutcome::deferred("needs operator action", false),
        MergeTaskOutcome::resolve_exhausted(
            "alpha",
            3,
            ResolveFailureClassification::RetriesExhausted,
            "budget exhausted",
        ),
        MergeTaskOutcome::already_reported(
            "alpha",
            AlreadyReportedFailureKind::Push,
            "push already reported",
        ),
        MergeTaskOutcome::run_fatal("base identity lost"),
    ];

    for outcome in outcomes {
        let config = create_test_config();
        let (tx, _rx) = mpsc::channel(32);
        let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
        executor.pending_merge_count.store(1, Ordering::Relaxed);

        let expected = outcome.disposition();
        let disposition = executor
            .handle_merge_result(MergeResult {
                change_id: "alpha".to_string(),
                workspace_name: "ws-alpha".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: outcome.clone(),
            })
            .await;

        assert_eq!(
            disposition, expected,
            "disposition drifted for {:?}",
            outcome
        );
        assert_eq!(
            executor.pending_merge_count.load(Ordering::Relaxed),
            0,
            "pending accounting must be released for {:?}",
            outcome
        );
    }
}

#[tokio::test]
async fn test_scheduler_lifetime_controls_idle_exit_behavior() {
    use tempfile::TempDir;

    let repo_dir = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let mut finite_executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), config.clone(), None);

    let queued = Vec::new();
    let in_flight = HashSet::new();
    assert!(
        finite_executor
            .should_exit_when_idle(true, &queued, &in_flight, None)
            .await,
        "finite scheduler must exit when all work is drained"
    );

    finite_executor.set_persistent_lifetime();
    assert!(
        !finite_executor
            .should_exit_when_idle(true, &queued, &in_flight, None)
            .await,
        "persistent scheduler must remain alive while idle"
    );

    assert!(
        !finite_executor
            .should_exit_when_idle(false, &queued, &in_flight, None)
            .await,
        "scheduler must not exit when active join tasks remain"
    );
}

#[tokio::test]
async fn test_persistent_idle_wait_detection_requires_fully_drained_state() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    let queued = Vec::new();
    let in_flight = HashSet::new();
    assert!(
        !executor
            .should_enter_persistent_idle_wait(true, &queued, &in_flight, None)
            .await,
        "finite scheduler must not enter persistent idle wait"
    );

    executor.set_persistent_lifetime();
    assert!(
        executor
            .should_enter_persistent_idle_wait(true, &queued, &in_flight, None)
            .await,
        "persistent scheduler should enter event-driven idle wait only when fully drained"
    );
    assert!(
        !executor
            .should_enter_persistent_idle_wait(false, &queued, &in_flight, None)
            .await,
        "active join tasks must keep the scheduler on the normal event path"
    );
    let queued_work = vec![make_test_change("queued-work")];
    assert!(
        !executor
            .should_enter_persistent_idle_wait(true, &queued_work, &in_flight, None)
            .await,
        "dispatchable queued work must keep debounce/reanalysis behavior active"
    );
    let in_flight_work = HashSet::from(["in-flight-work".to_string()]);
    assert!(
        !executor
            .should_enter_persistent_idle_wait(true, &queued, &in_flight_work, None)
            .await,
        "in-flight work must keep completion handling active"
    );

    executor
        .resolve_wait_changes
        .insert("needs-resolve".to_string());
    assert!(
        executor
            .should_enter_persistent_idle_wait(true, &queued, &in_flight, None)
            .await,
        "stable ResolveWait-only work should use event-driven persistent idle wait"
    );
}

/// Verification `persistent-idle-ready-regressions`: the scheduler announces a
/// persistent-idle park once per episode and stays alive across it.
///
/// Unit-scoped: the admission predicate, the latch, and the event channel are
/// all in-memory, and the drained/waiting-only inputs are held constant so the
/// only thing under test is the edge.
#[tokio::test]
async fn persistent_idle_event_is_edge_triggered() {
    let (tx, mut rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(
        PathBuf::from("/tmp/test-repo"),
        create_test_config(),
        Some(tx),
    );
    executor.set_persistent_lifetime();

    let queued: Vec<crate::openspec::Change> = Vec::new();
    let in_flight = HashSet::new();

    let idle_events = |rx: &mut mpsc::Receiver<ExecutionEvent>| {
        let mut count = 0;
        while let Ok(event) = rx.try_recv() {
            if matches!(event, ExecutionEvent::PersistentSchedulerIdle) {
                count += 1;
            }
        }
        count
    };

    // A fully drained persistent scheduler parks and announces it exactly once.
    assert!(
        executor
            .admit_persistent_idle_wait(true, &queued, &in_flight, None)
            .await,
        "a fully drained persistent scheduler must park"
    );
    assert_eq!(idle_events(&mut rx), 1, "the first park is the idle edge");
    assert!(
        executor.persistent_idle_is_latched(),
        "the episode stays open while the scheduler is parked"
    );

    // Repeated evaluation of the same state, and a wake that admits nothing,
    // both reach the same park and announce nothing further.
    for _ in 0..3 {
        assert!(
            executor
                .admit_persistent_idle_wait(true, &queued, &in_flight, None)
                .await,
            "the scheduler is still alive and still parking"
        );
    }
    assert_eq!(
        idle_events(&mut rx),
        0,
        "repeated evaluation and no-op wakes must not re-announce idle"
    );

    // A blocked/waiting-only episode is the same episode: still nothing
    // executing, so it must not produce a second edge either.
    executor
        .resolve_wait_changes
        .insert("needs-resolve".to_string());
    assert!(
        executor
            .admit_persistent_idle_wait(true, &queued, &in_flight, None)
            .await,
        "a resolve-wait-only persistent scheduler must park"
    );
    assert_eq!(idle_events(&mut rx), 0, "the episode is still open");

    // Admitted work rearms the edge; the next park announces again.
    executor.rearm_persistent_idle();
    assert!(
        !executor.persistent_idle_is_latched(),
        "admitted work must close the episode"
    );
    assert!(
        executor
            .admit_persistent_idle_wait(true, &queued, &in_flight, None)
            .await
    );
    assert_eq!(
        idle_events(&mut rx),
        1,
        "the park after admitted work is a new idle edge"
    );

    // A finite scheduler never parks, so it never announces.
    let (finite_tx, mut finite_rx) = mpsc::channel(4);
    let finite = ParallelExecutor::new(
        PathBuf::from("/tmp/test-repo"),
        create_test_config(),
        Some(finite_tx),
    );
    assert!(
        !finite
            .admit_persistent_idle_wait(true, &queued, &in_flight, None)
            .await,
        "a finite scheduler terminates instead of parking"
    );
    assert_eq!(idle_events(&mut finite_rx), 0);
}

/// The two boundaries that rearm the edge are the two where admitted work
/// really begins, and neither is a wake.
#[tokio::test]
async fn persistent_idle_latch_survives_until_admitted_work() {
    let executor =
        ParallelExecutor::new(PathBuf::from("/tmp/test-repo"), create_test_config(), None);

    assert!(
        executor.latch_persistent_idle(),
        "the first latch of an episode is the edge"
    );
    assert!(
        !executor.latch_persistent_idle(),
        "a second latch in the same episode is not an edge"
    );

    executor.rearm_persistent_idle();
    assert!(
        executor.latch_persistent_idle(),
        "a rearmed latch reports the next edge"
    );
}

/// Verification `idle-start-running-regressions`: the idle edge rearms from a
/// coherent *level* observation of committed intent, and from nothing else.
///
/// This is the other half of immediate Running. The accepted Start projects the
/// run episode from its own outcome; if the scheduler could not then rearm, an
/// analysis that admits nothing would leave every frontend claiming a run with
/// no event left that could close it. Rearming from the reduction *outcome*
/// instead would lose exactly that edge whenever a concurrent enqueue had
/// already queued the same row, so what is asserted here is the level read.
///
/// Unit-scoped: the latch, the baseline, and the event channel are in-memory,
/// and each reducer view is an owned snapshot. No reducer lock, no repository,
/// no process, and no wall-clock threshold is involved — the ordering of edges
/// is the entire evidence.
#[tokio::test]
async fn idle_start_running_rearms_the_idle_edge_from_observed_intent() {
    use crate::parallel::work_snapshot::ReducerWorkSnapshot;

    let (tx, mut rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(
        PathBuf::from("/tmp/test-repo"),
        create_test_config(),
        Some(tx),
    );
    executor.set_persistent_lifetime();

    let queued: Vec<crate::openspec::Change> = Vec::new();
    let in_flight = HashSet::new();

    let idle_events = |rx: &mut mpsc::Receiver<ExecutionEvent>| {
        let mut count = 0;
        while let Ok(event) = rx.try_recv() {
            if matches!(event, ExecutionEvent::PersistentSchedulerIdle) {
                count += 1;
            }
        }
        count
    };

    /// One coherent reducer view carrying exactly this queue intent.
    fn view(queued_ids: &[&str]) -> ReducerWorkSnapshot {
        let mut state =
            OrchestratorState::new(vec!["change-a".to_string(), "change-b".to_string()], 10);
        for id in queued_ids {
            state.apply_command(ReducerCommand::AddToQueue((*id).to_string()));
        }
        ReducerWorkSnapshot::from_state(&state)
    }

    // The scheduler parks with nothing queued: the episode opens on an empty
    // baseline.
    assert!(
        executor
            .admit_persistent_idle_wait(true, &queued, &in_flight, Some(&view(&[])))
            .await
    );
    assert_eq!(idle_events(&mut rx), 1, "the first park is the idle edge");

    // A generic wake re-observes the very same level. Nothing arrived, so the
    // episode stays open and the frontends stay Ready.
    executor.rearm_persistent_idle_from_observed_intent(&view(&[]), false);
    assert!(
        executor.persistent_idle_is_latched(),
        "a wake that observes no new intent must not rearm"
    );

    // An abandoned reducer acquisition has observed nothing at all. Reading it
    // as "new intent" would rearm on a lost read; reading it as "no intent" is
    // the only truthful answer.
    executor.rearm_persistent_idle_from_observed_intent(&ReducerWorkSnapshot::incomplete(), false);
    assert!(
        executor.persistent_idle_is_latched(),
        "an incomplete view is not an observation"
    );

    // The accepted Start's committed queue intent, seen as a level.
    executor.rearm_persistent_idle_from_observed_intent(&view(&["change-a"]), false);
    assert!(
        !executor.persistent_idle_is_latched(),
        "committed queue intent the episode never parked on rearms the edge"
    );

    // Analysis admits nothing and the scheduler parks again: because the edge
    // was rearmed, this park is a *new* transition, which is what returns the
    // frontends to Ready.
    assert!(
        executor
            .admit_persistent_idle_wait(true, &queued, &in_flight, Some(&view(&["change-a"])))
            .await
    );
    assert_eq!(
        idle_events(&mut rx),
        1,
        "the no-work park after an accepted Start is a fresh idle edge"
    );

    // That row is now part of the baseline. A blocked-only episode being woken
    // re-observes its own rows, and must not flicker Ready/Running because of
    // them.
    executor.rearm_persistent_idle_from_observed_intent(&view(&["change-a"]), false);
    assert!(
        executor.persistent_idle_is_latched(),
        "intent the episode already parked on is not new intent"
    );

    // An accepted explicit-retry hold consumed by this pass is committed
    // operator intent that admits no queued row of its own.
    executor.rearm_persistent_idle_from_observed_intent(&view(&["change-a"]), true);
    assert!(
        !executor.persistent_idle_is_latched(),
        "a consumed explicit-retry edge rearms on its own"
    );

    // With no episode open there is no edge to rearm, so an ordinary running
    // scheduler's passes are inert here however much intent they observe.
    executor.rearm_persistent_idle_from_observed_intent(&view(&["change-a", "change-b"]), false);
    assert!(!executor.persistent_idle_is_latched());
    assert_eq!(
        idle_events(&mut rx),
        0,
        "rearming publishes nothing; only a park does"
    );
}

#[tokio::test]
async fn test_persistent_idle_wait_does_not_poll_worktree_reconciliation_without_wake() {
    use crate::tui::queue::DynamicQueue;
    use tokio::sync::mpsc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let queue = Arc::new(DynamicQueue::new());
    let scan_calls = Arc::new(AtomicUsize::new(0));
    let mut executor = ParallelExecutor::new(repo_root, config, None);
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(scan_calls.clone()));
    executor.set_persistent_lifetime();
    executor.set_dynamic_queue(queue);
    let (_merge_result_tx, mut merge_result_rx) = mpsc::channel(1);
    let mut reason = crate::parallel::dynamic_queue::ReanalysisReason::Initial;

    let wait = executor.wait_for_persistent_idle_wake(&mut reason, &mut merge_result_rx);
    tokio::pin!(wait);

    tokio::select! {
        _ = &mut wait => panic!("persistent idle wait should not complete without a wake event"),
        _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
    }

    assert_eq!(
        scan_calls.load(Ordering::SeqCst),
        0,
        "event-driven persistent idle wait must not poll worktree reconciliation"
    );
}

#[tokio::test]
async fn test_persistent_idle_wait_wakes_on_queue_push_and_notify_scheduler() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::tui::queue::DynamicQueue;
    use tokio::sync::mpsc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let queue = Arc::new(DynamicQueue::new());
    let mut executor = ParallelExecutor::new(repo_root, config, None);
    executor.set_persistent_lifetime();
    executor.set_dynamic_queue(queue.clone());
    let (_merge_result_tx, mut merge_result_rx) = mpsc::channel(1);

    let mut reason = ReanalysisReason::Initial;
    {
        let wait = executor.wait_for_persistent_idle_wake(&mut reason, &mut merge_result_rx);
        tokio::pin!(wait);

        tokio::select! {
            _ = &mut wait => panic!("persistent idle wait should not complete before a wake event"),
            _ = tokio::time::sleep(std::time::Duration::from_millis(20)) => {}
        }

        assert!(queue.push("queued-change".to_string()).await);
        tokio::time::timeout(std::time::Duration::from_secs(1), &mut wait)
            .await
            .or_fail("queue push should wake persistent idle wait");
    }
    assert_eq!(reason.to_string(), "queue");

    let mut reason = ReanalysisReason::Initial;
    {
        let wait = executor.wait_for_persistent_idle_wake(&mut reason, &mut merge_result_rx);
        tokio::pin!(wait);

        tokio::select! {
            _ = &mut wait => panic!("persistent idle wait should not complete before scheduler notification"),
            _ = tokio::time::sleep(std::time::Duration::from_millis(20)) => {}
        }

        queue.notify_scheduler();
        tokio::time::timeout(std::time::Duration::from_secs(1), &mut wait)
            .await
            .or_fail("notify_scheduler should wake persistent idle wait");
    }
    assert_eq!(reason.to_string(), "queue");
}

#[tokio::test]
async fn test_idle_queue_addition_marks_reanalysis_and_enqueues_change() {
    use crate::parallel::dynamic_queue::ReanalysisReason;
    use crate::tui::queue::DynamicQueue;

    let config = create_test_config();
    let mut executor = ParallelExecutor::new(PathBuf::from("."), config, None);
    executor.set_persistent_lifetime();

    let all_changes = crate::openspec::list_changes_native().unwrap_or_default();
    if all_changes.is_empty() {
        return;
    }

    let preferred_change_id = "refactor-git-sync-log-boilerplate";
    let change_id = all_changes
        .iter()
        .find(|change| change.id == preferred_change_id)
        .map(|change| change.id.clone())
        .or_else(|| all_changes.first().map(|change| change.id.clone()))
        .or_fail("expected at least one change");

    // Production order: an accepted queue addition records reducer intent
    // before the wake-up hint is published, and ingestion validates against that
    // intent rather than the catalog.
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.clone()],
        1,
    )));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue(change_id.clone()));
    executor.set_shared_orchestrator_state(shared);

    let dynamic_queue = Arc::new(DynamicQueue::new());
    dynamic_queue.push(change_id.to_string()).await;
    executor.set_dynamic_queue(dynamic_queue);

    let mut queued = Vec::new();
    let in_flight = HashSet::new();
    let mut reason = ReanalysisReason::Initial;

    let queue_changed = executor
        .check_dynamic_queue_and_add_changes(&mut queued, &in_flight, &mut reason)
        .await;

    assert!(
        queue_changed,
        "dynamic queue additions should trigger reanalysis"
    );
    assert_eq!(reason.to_string(), "queue");
    assert_eq!(queued.len(), 1);
    assert_eq!(queued[0].id, change_id);
}

#[tokio::test]
async fn test_debounce_with_queue_changes() {
    use std::time::{Duration, Instant};
    use tokio::sync::mpsc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root, config, Some(tx));

    // First check: no queue changes, should reanalyze
    assert!(executor.should_reanalyze(false).await);

    // Simulate a queue change
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(Instant::now());
    }

    // Immediate check: should NOT reanalyze (debounce active)
    assert!(!executor.should_reanalyze(false).await);

    // Simulate debounce period expiry without wall-clock waiting.
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(Instant::now() - Duration::from_secs(11));
    }

    // After simulated debounce expiry: should reanalyze
    assert!(executor.should_reanalyze(false).await);
}

#[tokio::test]
async fn test_queue_notification_triggers_reanalysis() {
    use crate::tui::queue::DynamicQueue;
    use std::sync::Arc;
    use std::time::Duration;

    // Create a dynamic queue
    let queue = Arc::new(DynamicQueue::new());

    // Spawn a task that waits for notification
    let queue_clone = queue.clone();
    let handle = tokio::spawn(async move {
        let notified = queue_clone.notified();

        // Wait for notification with timeout
        tokio::select! {
            _ = notified => {
                // Notification received
                Ok(())
            }
            _ = tokio::time::sleep(Duration::from_secs(2)) => {
                // Timeout - notification not received
                Err("Timeout waiting for notification")
            }
        }
    });

    // Give the task time to start waiting
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Push to queue (should trigger notification)
    queue.push("test-change".to_string()).await;

    // Verify the notification was received
    let result = handle.await.or_fail("unexpected error");
    assert!(
        result.is_ok(),
        "Queue notification should have been received"
    );
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_attempt_merge_defers_when_change_not_archived() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create openspec/changes/test-change directory (simulating incomplete archive)
    let change_dir = repo_root.join("openspec/changes/test-change");
    fs::create_dir_all(&change_dir).or_fail("unexpected error");
    fs::write(change_dir.join("spec.md"), "# Test").or_fail("unexpected error");

    // Commit the change directory to ensure working tree is clean
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Add test change (not archived)"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create executor
    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    let revisions = vec!["test-workspace".to_string()];
    let change_ids = vec!["test-change".to_string()];

    // Attempt merge should be deferred because change directory exists
    let archive_paths = vec![repo_root.to_path_buf()];
    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Deferred(deferred)) => {
            assert!(!deferred.auto_resumable);
            assert!(
                deferred.reason.contains("Archive incomplete"),
                "Expected deferred reason to mention archive incomplete, got: {}",
                deferred.reason
            );
            assert!(
                deferred.reason.contains("test-change"),
                "Expected reason to include change ID, got: {}",
                deferred.reason
            );
        }
        Ok(MergeAttempt::Merged { .. }) => {
            panic!("Merge should have been deferred when change directory exists");
        }
        Err(e) => {
            panic!("Expected MergeDeferred, got error: {}", e);
        }
    }
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_attempt_merge_succeeds_when_change_archived() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create archive directory but NOT openspec/changes/test-change (proper archive)
    let archive_dir = repo_root.join("openspec/changes/archive/test-change");
    fs::create_dir_all(&archive_dir).or_fail("unexpected error");
    fs::write(archive_dir.join("spec.md"), "# Archived").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Archive: test-change"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create worktree for the change (outside the main repo to avoid dirty working tree)
    let workspace_base = TempDir::new().or_fail("unexpected error");
    let workspace_path = workspace_base.path().join("ws-test-change");

    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            "ws-test-change",
            workspace_path.to_str().or_fail("unexpected error"),
            "HEAD",
        ])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create executor
    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    let revisions = vec!["ws-test-change".to_string()];
    let change_ids = vec!["test-change".to_string()];

    // Attempt merge should succeed because change is properly archived
    let archive_paths = vec![workspace_path.clone()];
    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Merged { .. }) => {
            // Success - merge was allowed
        }
        Ok(MergeAttempt::Deferred(deferred)) => {
            panic!(
                "Merge should have succeeded when change is archived, got deferred: {}",
                deferred.reason
            );
        }
        Err(e) => {
            // This is also acceptable - merge may fail for other reasons (e.g., merge conflicts)
            // but it should not be deferred due to archive verification
            println!("Merge failed with error (acceptable): {}", e);
        }
    }
}

/// Test that the has_resolve_wait helper correctly tracks ResolveWait state.
#[tokio::test]
async fn test_scheduler_syncs_manual_resolve_wait_from_shared_state() {
    use std::sync::Arc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
    }

    executor.shared_orchestrator_state = Some(shared.clone());
    executor.resolve_wait_changes.clear();

    executor.sync_resolve_wait_from_shared_state().await;

    assert!(
        executor.resolve_wait_changes.contains("change-a"),
        "scheduler must mirror reducer-owned ResolveWait intent before idle/drained checks"
    );

    let queued = Vec::new();
    let in_flight = HashSet::new();
    let should_exit = executor
        .should_exit_when_idle(true, &queued, &in_flight, None)
        .await;
    assert!(
        !should_exit,
        "finite scheduler must remain alive while reducer-visible ResolveWait work can unblock queued dependents"
    );
}

#[tokio::test]
async fn handle_merge_result_releases_resolve_wait_retry_lane_on_auto_deferred() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);
    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("change-a".to_string(), WaitState::ResolveWait))
        );
        assert!(guard.is_base_mutating_lane_occupied());
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "change-a".to_string(),
                workspace_name: "ws-change-a".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome: MergeTaskOutcome::deferred("Merge lane busy", true),
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(disposition, MergeResultDisposition::Deferred);
    let guard = shared.read().await;
    assert!(!guard.is_base_mutating_lane_occupied());
    assert_eq!(
        guard.resolve_wait_change_ids(),
        vec!["change-a".to_string()]
    );
    assert!(guard.global_invariants_hold());
}

#[tokio::test]
async fn handle_merge_result_releases_reject_wait_retry_lane_and_suppresses_duplicate_error() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (event_tx, mut event_rx) = mpsc::channel(8);
    let mut executor = ParallelExecutor::new(repo_root, config, Some(event_tx));
    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["lane".to_string(), "reject-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::ChangeArchived("lane".to_string()));
        guard.mark_reject_wait("reject-a");
        guard.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "lane".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("reject-a".to_string(), WaitState::RejectWait))
        );
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "reject-a".to_string(),
                workspace_name: "ws-reject-a".to_string(),
                origin: MergeResultOrigin::RejectWaitRetry,
                outcome: MergeTaskOutcome::already_reported(
                    "reject-a",
                    crate::parallel::AlreadyReportedFailureKind::RejectionReview,
                    "specific rejection review failure already emitted",
                ),
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(disposition, MergeResultDisposition::ContinueWithErrors);
    let guard = shared.read().await;
    assert!(!guard.is_base_mutating_lane_occupied());
    assert_eq!(guard.reject_wait_change_ids(), vec!["reject-a".to_string()]);
    assert!(guard.global_invariants_hold());
    assert!(
        event_rx.try_recv().is_err(),
        "retry-origin errors must not emit duplicate generic ParallelEvent::Error"
    );
}

#[tokio::test]
async fn handle_merge_result_suppresses_resolve_retry_generic_error() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (event_tx, mut event_rx) = mpsc::channel(8);
    let mut executor = ParallelExecutor::new(repo_root, config, Some(event_tx));
    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);

    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "resolve-a".to_string(),
                workspace_name: "ws-resolve-a".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome: MergeTaskOutcome::resolve_exhausted(
                    "resolve-a",
                    3,
                    crate::parallel::ResolveFailureClassification::UnresolvedConflict,
                    "ResolveFailed already emitted by retry body",
                ),
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(disposition, MergeResultDisposition::ContinueWithErrors);
    assert_eq!(executor.pending_merge_count.load(Ordering::Relaxed), 0);
    assert!(
        event_rx.try_recv().is_err(),
        "ResolveWait retry errors must not emit duplicate generic ParallelEvent::Error"
    );
}

#[tokio::test]
async fn resolve_retry_workspace_lookup_failure_is_operator_visible() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    let (event_tx, mut event_rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0))));
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["missing-ws".to_string(), "next-ws".to_string()],
        0,
    )));
    {
        let mut guard = shared.write().await;
        for change_id in ["missing-ws", "next-ws"] {
            guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
                change_id: change_id.to_string(),
                reason: "manual conflict".to_string(),
                auto_resumable: false,
            });
            guard.apply_command(ReducerCommand::ResolveMerge(change_id.to_string()));
        }
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("missing-ws".to_string(), WaitState::ResolveWait))
        );
        assert!(guard.is_base_mutating_lane_occupied());
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor
        .resolve_wait_changes
        .insert("missing-ws".to_string());

    let outcome = executor
        .retry_deferred_merges_for(vec!["missing-ws".to_string()], None)
        .await;

    assert_eq!(outcome, MergeTaskOutcome::Merged);
    let mut saw_workspace_warning = false;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            ExecutionEvent::Log(entry) => {
                if entry
                    .message
                    .contains("No workspace found for ResolveWait retry 'missing-ws'")
                {
                    saw_workspace_warning = true;
                }
            }
            ExecutionEvent::Error { message } => panic!(
                "clearing stale retry intent is not a run-fatal outcome, got global Error: {message}"
            ),
            _ => {}
        }
    }
    assert!(
        saw_workspace_warning,
        "missing-workspace retry path must stay operator-visible as a warning"
    );
    {
        let guard = shared.read().await;
        assert!(!guard.is_base_mutating_lane_occupied());
        assert!(!guard
            .resolve_wait_change_ids()
            .contains(&"missing-ws".to_string()));
        assert!(!guard
            .reject_wait_change_ids()
            .contains(&"missing-ws".to_string()));
        // Base integration was never proven, so releasing the consumed
        // reservation must leave a retryable row, not an idle one.
        assert_eq!(guard.display_status("missing-ws"), "merge wait");
        assert!(guard.global_invariants_hold());
    }
    assert_eq!(
        shared
            .write()
            .await
            .promote_next_base_mutating_lane_waiter(),
        Some(("next-ws".to_string(), WaitState::ResolveWait))
    );
}

/// Reducer state for a change that entered `ResolveWait` through an explicit
/// manual `M` retry and was then promoted onto the base-mutating lane.
///
/// `ReducerCommand::ResolveMerge` is what leaves `QueueIntent::NotQueued` behind
/// the wait, so this is the exact shape whose stale settlement used to surface
/// `not queued`.
async fn promoted_manual_resolve_retry_state(change_id: &str) -> Arc<RwLock<OrchestratorState>> {
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        0,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: change_id.to_string(),
            reason: "manual conflict".to_string(),
            auto_resumable: false,
        });
        guard.apply_command(ReducerCommand::ResolveMerge(change_id.to_string()));
        assert_eq!(guard.display_status(change_id), "resolve pending");
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some((change_id.to_string(), WaitState::ResolveWait))
        );
    }
    shared
}

async fn git_porcelain_status(repo_root: &Path) -> String {
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("read git status");
    String::from_utf8_lossy(&output.stdout).to_string()
}

async fn git_stash_list(repo_root: &Path) -> String {
    let output = Command::new("git")
        .args(["stash", "list"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("read git stash list");
    String::from_utf8_lossy(&output.stdout).to_string()
}

#[tokio::test]
async fn stale_deferred_merge_retry_with_proven_base_integration_settles_merged() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "alpha", &[]);
    commit_archive_to_base(repo_dir.path(), "2026-05-13-alpha", "alpha").await;
    assert!(
        crate::execution::state::is_merged_to_base("alpha", repo_dir.path(), "main")
            .await
            .or_fail("read base integration evidence"),
        "fixture must prove base-branch tree integration before the retry runs"
    );

    let (event_tx, _event_rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let merge_calls = Arc::new(AtomicUsize::new(0));
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(merge_calls.clone()));
    let shared = promoted_manual_resolve_retry_state("alpha").await;
    executor.set_shared_orchestrator_state(shared.clone());
    executor.resolve_wait_changes.insert("alpha".to_string());

    let outcome = executor
        .retry_deferred_merges_for(vec!["alpha".to_string()], None)
        .await;

    assert_eq!(outcome, MergeTaskOutcome::Merged);
    {
        let guard = shared.read().await;
        assert_eq!(
            guard.display_status("alpha"),
            "merged",
            "repository-proven base integration is a terminal result, not idle bookkeeping"
        );
        assert!(guard.resolve_wait_change_ids().is_empty());
        assert!(
            !guard.is_base_mutating_lane_occupied(),
            "base-lane ownership is released once the reducer state agrees"
        );
        assert!(guard.global_invariants_hold());
    }
    assert!(executor.resolve_wait_changes.is_empty());
    assert!(!executor.merge_wait_changes.contains("alpha"));
    assert_eq!(
        merge_calls.load(Ordering::SeqCst),
        0,
        "a stale retry must not attempt another merge"
    );
}

#[tokio::test]
async fn stale_deferred_merge_retry_preserves_dirty_repository_content() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "alpha", &[]);
    commit_archive_to_base(repo_dir.path(), "2026-05-13-alpha", "alpha").await;

    // Unrelated operator work: a tracked modification, a staged addition, and a
    // non-ignored untracked file.
    let tracked = repo_dir.path().join("README.md");
    let staged = repo_dir.path().join("staged.txt");
    let untracked = repo_dir.path().join("untracked.txt");
    std::fs::write(
        &tracked,
        "operator edit
",
    )
    .or_fail("write tracked modification");
    std::fs::write(
        &staged,
        "staged work
",
    )
    .or_fail("write staged file");
    Command::new("git")
        .args(["add", "staged.txt"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("stage operator file");
    std::fs::write(
        &untracked,
        "untracked work
",
    )
    .or_fail("write untracked file");

    let status_before = git_porcelain_status(repo_dir.path()).await;
    let head_before = get_current_commit(repo_dir.path())
        .await
        .or_fail("read HEAD before settlement");
    assert!(
        !status_before.trim().is_empty(),
        "fixture must be dirty before settlement"
    );

    let (event_tx, _event_rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0))));
    let shared = promoted_manual_resolve_retry_state("alpha").await;
    executor.set_shared_orchestrator_state(shared.clone());
    executor.resolve_wait_changes.insert("alpha".to_string());

    let outcome = executor
        .retry_deferred_merges_for(vec!["alpha".to_string()], None)
        .await;

    assert_eq!(outcome, MergeTaskOutcome::Merged);
    assert_eq!(
        shared.read().await.display_status("alpha"),
        "merged",
        "dirty content is a guard, not a reason to withhold the proven terminal result"
    );

    assert_eq!(
        git_porcelain_status(repo_dir.path()).await,
        status_before,
        "settlement must not stage, commit, stash, reset, or discard operator content"
    );
    assert_eq!(
        get_current_commit(repo_dir.path())
            .await
            .or_fail("read HEAD after settlement"),
        head_before,
        "settlement must not create a commit"
    );
    assert!(
        git_stash_list(repo_dir.path()).await.trim().is_empty(),
        "settlement must not stash operator content"
    );
    assert_eq!(
        std::fs::read_to_string(&tracked).or_fail("read tracked file"),
        "operator edit\n"
    );
    assert_eq!(
        std::fs::read_to_string(&staged).or_fail("read staged file"),
        "staged work\n"
    );
    assert_eq!(
        std::fs::read_to_string(&untracked).or_fail("read untracked file"),
        "untracked work\n"
    );
}

#[tokio::test]
async fn stale_deferred_merge_retry_with_unreadable_evidence_remains_merge_wait() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "alpha", &[]);
    commit_archive_to_base(repo_dir.path(), "2026-05-13-alpha", "alpha").await;

    let (event_tx, mut event_rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let merge_calls = Arc::new(AtomicUsize::new(0));
    // Base identity cannot be resolved, so the archive evidence above can never
    // be compared against a base tree. The retry still runs and finds no
    // workspace, which is where settlement happens on unproven evidence.
    executor.workspace_manager =
        Box::new(TestWorkspaceManager::new(merge_calls.clone()).with_failing_original_branch());
    let shared = promoted_manual_resolve_retry_state("alpha").await;
    executor.set_shared_orchestrator_state(shared.clone());
    executor.resolve_wait_changes.insert("alpha".to_string());

    let outcome = executor
        .retry_deferred_merges_for(vec!["alpha".to_string()], None)
        .await;

    assert_eq!(outcome, MergeTaskOutcome::Merged);
    {
        let guard = shared.read().await;
        let status = guard.display_status("alpha");
        assert_eq!(
            status, "merge wait",
            "unreadable evidence must fail closed to an explicitly retryable state"
        );
        assert_ne!(status, "merged");
        assert_ne!(status, "not queued");
        assert!(guard.resolve_wait_change_ids().is_empty());
        assert!(!guard.is_base_mutating_lane_occupied());
        assert!(guard.global_invariants_hold());
    }
    assert!(executor.resolve_wait_changes.is_empty());
    assert!(executor.merge_wait_changes.contains("alpha"));
    assert_eq!(
        merge_calls.load(Ordering::SeqCst),
        0,
        "evidence that could not be read must not authorize a merge attempt"
    );

    let mut saw_retry_dispatch = false;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            ExecutionEvent::Log(entry) => {
                if entry
                    .message
                    .contains("ResolveWait retry dispatch started for 'alpha'")
                {
                    saw_retry_dispatch = true;
                }
            }
            ExecutionEvent::Error { message } => {
                panic!("unreadable evidence is recoverable, got global Error: {message}")
            }
            _ => {}
        }
    }
    assert!(
        saw_retry_dispatch,
        "unreadable evidence must not silently swallow the operator's retry"
    );

    // The operator can still retry explicitly once the repository is corrected.
    assert!(matches!(
        shared
            .write()
            .await
            .apply_command(ReducerCommand::ResolveMerge("alpha".to_string())),
        crate::orchestration::state::ReduceOutcome::Changed(_)
    ));
    assert_eq!(
        shared.read().await.display_status("alpha"),
        "resolve pending"
    );
}

#[tokio::test]
async fn stale_deferred_merge_retry_with_stale_workspace_path_remains_merge_wait() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "alpha", &[]);
    assert!(
        !crate::execution::state::is_merged_to_base("alpha", repo_dir.path(), "main")
            .await
            .or_fail("read base integration evidence"),
        "fixture must prove base integration is absent before the retry runs"
    );

    let (event_tx, _event_rx) = mpsc::channel(32);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    let merge_calls = Arc::new(AtomicUsize::new(0));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(merge_calls.clone())
            .with_existing_workspace("alpha", repo_dir.path().join("deleted-worktree")),
    );
    let shared = promoted_manual_resolve_retry_state("alpha").await;
    executor.set_shared_orchestrator_state(shared.clone());
    executor.resolve_wait_changes.insert("alpha".to_string());

    let outcome = executor
        .retry_deferred_merges_for(vec!["alpha".to_string()], None)
        .await;

    assert_eq!(outcome, MergeTaskOutcome::Merged);
    {
        let guard = shared.read().await;
        let status = guard.display_status("alpha");
        assert_eq!(
            status, "merge wait",
            "a stale workspace path proves nothing about base integration"
        );
        assert_ne!(status, "merged");
        assert_ne!(status, "not queued");
        assert!(guard.resolve_wait_change_ids().is_empty());
        assert!(!guard.is_base_mutating_lane_occupied());
        assert!(guard.global_invariants_hold());
    }
    assert!(executor.resolve_wait_changes.is_empty());
    assert!(executor.merge_wait_changes.contains("alpha"));
    assert_eq!(
        merge_calls.load(Ordering::SeqCst),
        0,
        "a stale workspace path must not authorize a merge attempt"
    );
}

#[tokio::test]
async fn reject_retry_workspace_lookup_failure_is_operator_visible() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    let (event_tx, mut event_rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(event_tx),
    );
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0))));
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            "lane".to_string(),
            "missing-reject-ws".to_string(),
            "next-reject-ws".to_string(),
        ],
        0,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::ChangeArchived("lane".to_string()));
        guard.mark_reject_wait("missing-reject-ws");
        guard.mark_reject_wait("next-reject-ws");
        guard.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "lane".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("missing-reject-ws".to_string(), WaitState::RejectWait))
        );
        assert!(guard.is_base_mutating_lane_occupied());
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let outcome = executor
        .retry_deferred_rejection_review_for("missing-reject-ws".to_string())
        .await;

    assert_eq!(outcome, MergeTaskOutcome::Merged);
    let mut saw_workspace_warning = false;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            ExecutionEvent::Log(entry) => {
                if entry
                    .message
                    .contains("No workspace found for RejectWait retry 'missing-reject-ws'")
                {
                    saw_workspace_warning = true;
                }
            }
            ExecutionEvent::Error { message } => panic!(
                "clearing stale reject-wait intent is not a run-fatal outcome, got global Error: {message}"
            ),
            _ => {}
        }
    }
    assert!(
        saw_workspace_warning,
        "missing RejectWait workspace path must stay operator-visible as a warning"
    );
    {
        let guard = shared.read().await;
        assert!(!guard.is_base_mutating_lane_occupied());
        assert!(!guard
            .resolve_wait_change_ids()
            .contains(&"missing-reject-ws".to_string()));
        assert!(!guard
            .reject_wait_change_ids()
            .contains(&"missing-reject-ws".to_string()));
        assert!(guard.global_invariants_hold());
    }
    assert_eq!(
        shared
            .write()
            .await
            .promote_next_base_mutating_lane_waiter(),
        Some(("next-reject-ws".to_string(), WaitState::RejectWait))
    );
}

#[tokio::test]
async fn resolve_give_up_promotes_next_waiter_without_user_action() {
    // This test spawns a retry that uses the process-global merge lock.
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0))));
    let (merge_result_tx, mut merge_result_rx) = mpsc::channel(8);
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["first".to_string(), "second".to_string()],
        0,
    )));
    {
        let mut guard = shared.write().await;
        for change_id in ["first", "second"] {
            guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
                change_id: change_id.to_string(),
                reason: "manual conflict".to_string(),
                auto_resumable: false,
            });
            guard.apply_command(ReducerCommand::ResolveMerge(change_id.to_string()));
        }
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("first".to_string(), WaitState::ResolveWait))
        );
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor.resolve_wait_changes.insert("first".to_string());

    let outcome = executor
        .retry_deferred_merges_for(vec!["first".to_string()], None)
        .await;
    assert_eq!(outcome, MergeTaskOutcome::Merged);

    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "first".to_string(),
                workspace_name: "ws-first".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome: MergeTaskOutcome::Merged,
            },
            &merge_result_tx,
        )
        .await;
    assert!(disposition.is_merged());

    {
        let guard = shared.read().await;
        assert_eq!(
            guard.base_mutating_lane_occupant(),
            Some("second".to_string())
        );
        assert!(!guard
            .resolve_wait_change_ids()
            .contains(&"first".to_string()));
        assert!(!guard
            .reject_wait_change_ids()
            .contains(&"first".to_string()));
        assert!(guard.global_invariants_hold());
    }
    let retry_result =
        tokio::time::timeout(std::time::Duration::from_secs(2), merge_result_rx.recv())
            .await
            .or_fail("second retry result should arrive")
            .or_fail("second retry result channel should remain open");
    assert_eq!(retry_result.change_id, "second");
    assert_eq!(retry_result.origin, MergeResultOrigin::ResolveWaitRetry);
}

#[tokio::test]
async fn retry_lane_busy_release_allows_subsequent_repromotion() {
    // Serialize against other suites that manipulate the global merge lock so
    // their `try_lock` contention checks do not race this test's held guard.
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);
    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("change-a".to_string(), WaitState::ResolveWait))
        );
        assert!(guard.is_base_mutating_lane_occupied());
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let merge_guard = global_merge_lock().lock().await;
    let deferred_by_lock = executor
        .attempt_merge(
            &["retry-rev".to_string()],
            &["change-a".to_string()],
            &[PathBuf::from("/tmp/retry-archive")],
            None,
        )
        .await
        .or_fail("attempt_merge should report lock contention as a deferred retry");
    let outcome = match deferred_by_lock {
        MergeAttempt::Deferred(deferred) => {
            assert!(deferred.auto_resumable);
            assert!(
                deferred.reason.contains("Merge lane busy"),
                "test must exercise the global_merge_lock contention branch, got: {}",
                deferred.reason
            );
            MergeTaskOutcome::Deferred {
                reason: deferred.reason,
                auto_resumable: deferred.auto_resumable,
            }
        }
        other => panic!("expected lock-contention deferral, got {other:?}"),
    };
    drop(merge_guard);

    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "change-a".to_string(),
                workspace_name: "ws-change-a".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome,
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(disposition, MergeResultDisposition::Deferred);
    {
        let guard = shared.read().await;
        assert!(!guard.is_base_mutating_lane_occupied());
        assert_eq!(
            guard.resolve_wait_change_ids(),
            vec!["change-a".to_string()]
        );
    }
    let promoted_again = shared
        .write()
        .await
        .promote_next_base_mutating_lane_waiter();
    assert_eq!(
        promoted_again,
        Some(("change-a".to_string(), WaitState::ResolveWait)),
        "released lane-busy retry must be promotable again on the next trigger"
    );
    assert!(shared.read().await.global_invariants_hold());
}

#[tokio::test]
async fn deferred_retry_lane_repromotes_after_merge_completion_trigger() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);
    let (merge_result_tx, mut merge_result_rx) = mpsc::channel(8);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some(("change-a".to_string(), WaitState::ResolveWait))
        );
    }
    executor.set_shared_orchestrator_state(shared.clone());

    executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "change-a".to_string(),
                workspace_name: "ws-change-a".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome: MergeTaskOutcome::deferred("Merge lane busy", true),
            },
            &merge_result_tx,
        )
        .await;
    assert!(!shared.read().await.is_base_mutating_lane_occupied());

    executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "blocking-merge".to_string(),
                workspace_name: "ws-blocking-merge".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: MergeTaskOutcome::Merged,
            },
            &merge_result_tx,
        )
        .await;

    assert!(
        shared.read().await.is_base_mutating_lane_occupied(),
        "merged trigger must promote the released retry waiter without user action"
    );
    let retry_result = tokio::time::timeout(
        std::time::Duration::from_millis(200),
        merge_result_rx.recv(),
    )
    .await
    .or_fail("promotion should spawn a retry task result")
    .or_fail("promotion result channel closed");
    assert_eq!(retry_result.change_id, "change-a");
    assert_eq!(retry_result.origin, MergeResultOrigin::ResolveWaitRetry);
}

#[tokio::test]
async fn finite_scheduler_does_not_drain_while_spawned_retry_is_pending() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (merge_result_tx, mut merge_result_rx) = mpsc::channel(4);
    let mut executor = ParallelExecutor::new(repo_root, config, None);
    let queued = Vec::new();
    let in_flight = HashSet::new();

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["retry-a".to_string(), "retry-b".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        for change_id in ["retry-a", "retry-b"] {
            guard.apply_observation(
                change_id,
                crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
            );
            guard.apply_command(ReducerCommand::ResolveMerge(change_id.to_string()));
        }
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor.sync_resolve_wait_from_shared_state().await;

    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "blocking-merge".to_string(),
                workspace_name: "ws-blocking-merge".to_string(),
                origin: MergeResultOrigin::PostArchiveMerge,
                outcome: MergeTaskOutcome::Merged,
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(
        executor.pending_merge_count.load(Ordering::Relaxed),
        1,
        "post-archive merge completion should release one count and spawn one retry count"
    );
    assert!(!executor.is_fully_drained(true, true, true));
    assert!(
        !executor
            .should_exit_when_idle(true, &queued, &in_flight, None)
            .await,
        "finite scheduler must not exit while detached retry result is pending"
    );

    let spawned_retry = tokio::time::timeout(
        std::time::Duration::from_millis(200),
        merge_result_rx.recv(),
    )
    .await
    .or_fail("spawned retry should report through the merge-result channel")
    .or_fail("merge-result channel closed before spawned retry reported");
    assert_eq!(spawned_retry.change_id, "retry-a");
    assert_eq!(spawned_retry.origin, MergeResultOrigin::ResolveWaitRetry);
    assert!(
        !executor.is_fully_drained(true, true, true),
        "receiving a spawned result is not enough; the scheduler must handle it first"
    );

    assert!(executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: "retry-a".to_string(),
                workspace_name: "ws-retry-a".to_string(),
                origin: MergeResultOrigin::ResolveWaitRetry,
                outcome: MergeTaskOutcome::Merged,
            },
            &merge_result_tx,
        )
        .await
        .is_merged());

    assert!(
        !shared
            .read()
            .await
            .resolve_wait_change_ids()
            .contains(&"retry-a".to_string()),
        "handled merged retry should clear the completed ResolveWait entry"
    );
    assert!(
        shared.read().await.is_base_mutating_lane_occupied(),
        "handling the completed retry should promote the next waiter"
    );
    assert!(
        shared.read().await.is_base_mutating_lane_occupied(),
        "handling the completed retry should promote the next waiter before drain can complete"
    );
}

#[tokio::test]
async fn test_manual_resolve_wait_retries_after_in_flight_apply_completes() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use crate::parallel::WorkspaceResult;
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config();
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("change-a", workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["applying-change".to_string(), "change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
    }
    executor.set_shared_orchestrator_state(shared);
    executor.sync_resolve_wait_from_shared_state().await;
    executor.last_dispatched_resolve_wait_changes = executor.resolve_wait_changes.clone();

    assert!(
        !executor.should_dispatch_resolve_wait_retry(),
        "unchanged ResolveWait should stay pending while unrelated apply work is still in flight"
    );

    executor
        .handle_workspace_completion(
            WorkspaceResult {
                change_id: "applying-change".to_string(),
                workspace_name: "applying-change".to_string(),
                final_revision: None,
                error: None,
                rejected: None,
            },
            1,
            &mut HashSet::from(["applying-change".to_string()]),
            &mpsc::channel(1).0,
        )
        .await;
    executor.trigger_resolve_wait_retry_dispatch();
    executor.maybe_dispatch_resolve_wait_retry().await;

    let mut saw_retry_dispatch = false;
    let mut saw_manual_deferral = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            crate::events::ExecutionEvent::Log(log)
                if log
                    .message
                    .contains("ResolveWait retry dispatch started for 'change-a'") =>
            {
                saw_retry_dispatch = true;
            }
            crate::events::ExecutionEvent::MergeDeferred {
                change_id,
                auto_resumable: false,
                ..
            } if change_id == "change-a" => saw_manual_deferral = true,
            _ => {}
        }
    }

    assert!(
        saw_retry_dispatch,
        "completion of unrelated in-flight apply work must wake scheduler-owned ResolveWait retry"
    );
    assert!(
        saw_manual_deferral,
        "retry attempt must produce a visible terminal wait outcome instead of silent pending"
    );
}

#[tokio::test]
async fn test_scheduler_dispatches_synced_manual_resolve_wait_without_queued_work() {
    use std::sync::Arc;
    use tokio::sync::mpsc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (tx, mut rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(repo_root, config, Some(tx));

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
    }
    executor.set_shared_orchestrator_state(shared);

    executor.sync_resolve_wait_from_shared_state().await;
    executor.trigger_resolve_wait_retry_dispatch();

    assert!(
        executor.should_dispatch_resolve_wait_retry(),
        "synced ResolveWait intent should be dispatchable even when no queued/in-flight work exists"
    );

    executor.maybe_dispatch_resolve_wait_retry().await;

    let saw_retry_event = tokio::time::timeout(std::time::Duration::from_millis(200), async {
        loop {
            match rx.recv().await {
                Some(crate::events::ExecutionEvent::Log(log))
                    if log
                        .message
                        .contains("ResolveWait retry dispatch started for 'change-a'") =>
                {
                    break true;
                }
                Some(_) => continue,
                None => break false,
            }
        }
    })
    .await
    .unwrap_or(false);
    assert!(
        saw_retry_event,
        "manual startup path must reach retry dispatch instead of stopping as a zero-change no-op"
    );

    assert_eq!(
        executor.last_dispatched_resolve_wait_changes, executor.resolve_wait_changes,
        "dispatch path should snapshot synced ResolveWait ids"
    );
    assert!(
        !executor.resolve_wait_retry_triggered,
        "dispatch path should consume retry trigger"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn test_scheduler_reconciliation_missing_candidate_warn_is_observable_but_bounded() {
    use crate::events::{ExecutionEvent, LogLevel};
    use std::io::{self, Write};
    use std::sync::{Arc, Mutex as StdMutex};
    use tokio::sync::mpsc;
    use tracing_subscriber::fmt::MakeWriter;

    #[derive(Clone)]
    struct CapturedLogs(Arc<StdMutex<Vec<u8>>>);

    struct CapturedLogWriter(Arc<StdMutex<Vec<u8>>>);

    impl Write for CapturedLogWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0
                .lock()
                .expect("captured log buffer poisoned")
                .extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl<'a> MakeWriter<'a> for CapturedLogs {
        type Writer = CapturedLogWriter;

        fn make_writer(&'a self) -> Self::Writer {
            CapturedLogWriter(self.0.clone())
        }
    }

    // Held for the whole capture: tracing's max-level hint is process-global, so
    // this WARN-only subscriber disables `info!` on every thread while it is
    // installed, and would blank out an overlapping INFO capture test's records.
    // See `crate::test_support::tracing_capture_lock`.
    let _capture_exclusion = crate::test_support::tracing_capture_lock().lock().await;
    let captured_logs = Arc::new(StdMutex::new(Vec::new()));
    let subscriber = tracing_subscriber::fmt()
        .with_ansi(false)
        .without_time()
        .with_max_level(tracing::Level::WARN)
        .with_writer(CapturedLogs(captured_logs.clone()))
        .finish();
    let _subscriber_guard = tracing::subscriber::set_default(subscriber);
    crate::test_support::refresh_tracing_interest();

    let config = create_test_config();
    let repo_dir = tempfile::tempdir().or_fail("create temp repo");
    let changes_dir = repo_dir.path().join("openspec/changes");
    let loadable_change_id = "fix-missing-candidate-log-spam";
    let loadable_change_dir = changes_dir.join(loadable_change_id);
    std::fs::create_dir_all(&loadable_change_dir).or_fail("create loadable change dir");
    std::fs::write(
        loadable_change_dir.join("proposal.md"),
        "# Fix missing candidate log spam\n",
    )
    .or_fail("write loadable proposal");
    std::fs::write(
        loadable_change_dir.join("tasks.md"),
        "- [ ] Add bounded warning\n",
    )
    .or_fail("write loadable tasks");

    let (tx, mut rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    // The missing-candidate verdict is reached only on *conclusive* archived-dirty
    // repair evidence, and this temp directory is not a Git repository. The double
    // resolves a base branch and answers "no workspace", which is the conclusive
    // negative this bounded-warning test is about; without it the pass would
    // correctly defer instead of warning.
    executor.set_workspace_manager(Box::new(TestWorkspaceManager::new(Arc::new(
        AtomicUsize::new(0),
    ))));

    let missing_change_id = "definitely-missing-candidate-for-reconciliation";
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            missing_change_id.to_string(),
            loadable_change_id.to_string(),
        ],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(missing_change_id.to_string()));
        guard.apply_command(ReducerCommand::AddToQueue(loadable_change_id.to_string()));
    }
    executor.set_shared_orchestrator_state(shared);

    let mut queued = Vec::new();
    let in_flight = HashSet::new();

    let first_added = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
        .await;
    let second_added = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
        .await;

    assert_eq!(
        first_added.queued_added, 1,
        "loadable reducer-queued change should be added"
    );
    assert_eq!(
        first_added.repair_added, 0,
        "missing candidate test should not add repair candidates"
    );
    assert_eq!(
        second_added.total_added(),
        0,
        "second reconciliation should not add duplicates"
    );
    assert!(
        queued.iter().any(|change| change.id == loadable_change_id),
        "loadable reducer-queued change should be present in scheduler-local queue"
    );
    assert!(
        !queued.iter().any(|change| change.id == missing_change_id),
        "missing reducer-queued candidate must not be inserted into scheduler-local queue"
    );

    let mut candidate_not_found_events = 0usize;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::Log(log) = event {
            if log.level == LogLevel::Warn && log.message.contains("candidate_not_found") {
                candidate_not_found_events += 1;
            }
        }
    }
    assert_eq!(
        candidate_not_found_events, 1,
        "candidate_not_found should remain visible once without repeated TUI-visible warnings"
    );

    drop(_subscriber_guard);
    let captured = String::from_utf8(
        captured_logs
            .lock()
            .expect("captured log buffer poisoned")
            .clone(),
    )
    .expect("tracing output should be valid UTF-8");
    let structured_warn_count = captured
        .matches("Queue reconciliation could not load reducer-queued change")
        .count();
    assert_eq!(
        structured_warn_count, 1,
        "tracing warn should be emitted once for missing reducer-queued candidate"
    );
}

#[tokio::test]
async fn test_reducer_visible_queue_addition_marks_reanalysis_timestamp_and_enqueues_change() {
    let config = create_test_config();
    let repo_dir = tempfile::tempdir().or_fail("create temp repo");
    let change_id = "reducer-visible-queue-addition";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create reducer-visible change dir");
    std::fs::write(
        change_dir.join("proposal.md"),
        "# Reducer visible queue addition\n",
    )
    .or_fail("write reducer-visible proposal");
    std::fs::write(change_dir.join("tasks.md"), "- [ ] Add queue coverage\n")
        .or_fail("write reducer-visible tasks");

    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, None);
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
    }
    executor.set_shared_orchestrator_state(shared);

    let mut queued = Vec::new();
    let outcome = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;

    assert_eq!(outcome.queued_added, 1);
    assert_eq!(outcome.repair_added, 0);
    assert_eq!(queued.len(), 1);
    assert_eq!(queued[0].id, change_id);
    assert!(
        executor.last_queue_change_at.lock().await.is_some(),
        "reducer-visible queued additions should stamp queue-change debounce state"
    );
}

#[tokio::test]
async fn test_reducer_visible_queue_addition_preserves_existing_reanalysis_timestamp() {
    let config = create_test_config();
    let repo_dir = tempfile::tempdir().or_fail("create temp repo");
    let change_id = "reducer-visible-queue-debounce-preserved";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create reducer-visible change dir");
    std::fs::write(
        change_dir.join("proposal.md"),
        "# Reducer visible queue debounce preserved\n",
    )
    .or_fail("write reducer-visible proposal");
    std::fs::write(change_dir.join("tasks.md"), "- [ ] Add queue coverage\n")
        .or_fail("write reducer-visible tasks");

    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, None);
    let existing_timestamp = std::time::Instant::now() - std::time::Duration::from_secs(5);
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(existing_timestamp);
    }

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
    }
    executor.set_shared_orchestrator_state(shared);

    let mut queued = Vec::new();
    let outcome = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;

    assert_eq!(outcome.queued_added, 1);
    assert_eq!(outcome.repair_added, 0);
    assert_eq!(queued.len(), 1);
    assert_eq!(queued[0].id, change_id);
    assert_eq!(
        *executor.last_queue_change_at.lock().await,
        Some(existing_timestamp),
        "reducer-visible reconciliation must not refresh an existing queue debounce timestamp"
    );
}

#[tokio::test]
async fn test_archived_dirty_reconciliation_skips_workspace_already_merged_to_base() {
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    init_git_repo(workspace_dir.path()).await;

    let change_id = "fix-dependency-target-handling";
    let archive_dir = workspace_dir
        .path()
        .join("openspec/changes/archive/2026-05-08-fix-dependency-target-handling");
    std::fs::create_dir_all(&archive_dir).or_fail("create archived change dir");
    std::fs::write(
        archive_dir.join("proposal.md"),
        "# Fix dependency target handling\n",
    )
    .or_fail("write archived proposal");
    std::fs::write(
        archive_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] Archive move completed\n",
    )
    .or_fail("write archived tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(workspace_dir.path())
        .output()
        .await
        .or_fail("git add archived change");
    Command::new("git")
        .args(["commit", "-m", "Archive fix-dependency-target-handling"])
        .current_dir(workspace_dir.path())
        .output()
        .await
        .or_fail("git commit archived change");

    let (tx, mut rx) = mpsc::channel(64);
    let config = create_test_config();
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(change_id, workspace_dir.path().to_path_buf()),
    );

    // The merged-evidence stop gate must hold *after* the explicit-intent
    // boundary is passed, so this fixture gives the change real reducer queue
    // intent instead of relying on the absence of intent.
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
    }
    executor.set_shared_orchestrator_state(shared.clone());

    assert_eq!(
        shared.read().await.queued_change_ids(),
        vec![change_id.to_string()],
        "fixture must pass the explicit-intent boundary before the merged stop gate is exercised"
    );

    let mut queued = Vec::new();
    let added = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;

    assert_eq!(
        added.total_added(),
        0,
        "an explicitly queued but already-merged worktree must stay terminal residue instead of becoming repair work"
    );
    assert!(
        queued.is_empty(),
        "merged leftover worktree must not enter scheduler-local queued work"
    );

    while let Ok(event) = rx.try_recv() {
        if let crate::events::ExecutionEvent::Log(log) = event {
            assert!(
                !log.message.contains("archived_dirty_repair_candidate"),
                "merged terminal worktree must not emit archived-dirty repair diagnostics: {}",
                log.message
            );
        }
    }
}

#[tokio::test]
async fn test_archived_dirty_reconciliation_skips_manual_merge_wait() {
    use crate::events::ExecutionEvent;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    init_git_repo(workspace_dir.path()).await;

    let change_id = "add-session-signers";
    let archive_dir = workspace_dir
        .path()
        .join("openspec/changes/archive/2026-05-14-add-session-signers");
    std::fs::write(workspace_dir.path().join("base-only.txt"), "base\n")
        .or_fail("write base content");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(workspace_dir.path())
        .output()
        .await
        .or_fail("git add base content");
    Command::new("git")
        .args(["commit", "-m", "base before archived workspace"])
        .current_dir(workspace_dir.path())
        .output()
        .await
        .or_fail("git commit base content");
    std::fs::create_dir_all(&archive_dir).or_fail("create archived change dir");
    std::fs::write(archive_dir.join("proposal.md"), "# Add session signers\n")
        .or_fail("write archived proposal");
    std::fs::write(
        archive_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] Archive move completed\n",
    )
    .or_fail("write archived tasks");
    std::fs::write(
        archive_dir.join("report.md"),
        "# uncommitted archive report\n",
    )
    .or_fail("leave archived workspace dirty");

    let (tx, mut rx) = mpsc::channel(64);
    let config = create_test_config();
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(change_id, workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    // Explicit queue intent that survives into manual merge wait. A resolve
    // failure restores `MergeWait` without clearing `QueueIntent::Queued`, so
    // this change really does reach candidate evaluation and is stopped by the
    // merge-wait gate itself rather than by having no ordinary intent at all.
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
        guard.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: change_id.to_string(),
            error: "base has unresolved conflicts".to_string(),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    assert_eq!(
        shared.read().await.queued_change_ids(),
        vec![change_id.to_string()],
        "fixture must pass the explicit-intent boundary before the merge-wait gate is exercised"
    );
    assert_eq!(
        shared.read().await.merge_wait_change_ids(),
        vec![change_id.to_string()]
    );

    let mut queued = Vec::new();
    let added = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;
    let rediscovered = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;

    assert_eq!(added.total_added(), 0);
    assert_eq!(rediscovered.total_added(), 0);
    assert!(queued.is_empty());

    let mut manual_wait_diagnostic_count = 0usize;
    while let Ok(event) = rx.try_recv() {
        if let crate::events::ExecutionEvent::Log(log) = event {
            assert!(
                !log.message.contains("archived_dirty_repair_candidate"),
                "manual merge-wait worktree must not be requeued as archived-dirty repair: {}",
                log.message
            );
            if log.message.contains("manual_merge_wait") {
                manual_wait_diagnostic_count += 1;
            }
        }
    }
    assert_eq!(manual_wait_diagnostic_count, 1);

    // Manual merge wait advances only through an accepted `ResolveMerge`, which
    // moves the change onto the reducer-owned resolve lane instead of back into
    // ordinary queued work.
    assert!(matches!(
        shared
            .write()
            .await
            .apply_command(ReducerCommand::ResolveMerge(change_id.to_string())),
        crate::orchestration::state::ReduceOutcome::Changed(_)
    ));
    assert_eq!(
        shared.read().await.resolve_wait_change_ids(),
        vec![change_id.to_string()]
    );
    assert!(shared.read().await.merge_wait_change_ids().is_empty());

    let after_resolve_intent = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;
    assert_eq!(
        after_resolve_intent.total_added(),
        0,
        "resolve lane intent must not be laundered into ordinary queued work"
    );
}

#[tokio::test]
async fn test_archived_dirty_reconciliation_keeps_terminal_error_stopped_until_retry() {
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    init_git_repo(workspace_dir.path()).await;

    let change_id = "fix-dependency-target-handling";
    let archive_dir = workspace_dir
        .path()
        .join("openspec/changes/archive/2026-05-08-fix-dependency-target-handling");
    std::fs::write(workspace_dir.path().join("base-only.txt"), "base\n")
        .or_fail("write unrelated base content");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(workspace_dir.path())
        .output()
        .await
        .or_fail("git add base content before dirty repair fixture");
    Command::new("git")
        .args(["commit", "-m", "base before archived dirty repair"])
        .current_dir(workspace_dir.path())
        .output()
        .await
        .or_fail("git commit base content before dirty repair fixture");
    std::fs::create_dir_all(&archive_dir).or_fail("create archived change dir after base commit");
    std::fs::write(
        archive_dir.join("proposal.md"),
        "# Fix dependency target handling\n",
    )
    .or_fail("write archived proposal after base commit");
    std::fs::write(
        archive_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] Archive move completed\n- [ ] Commit finalization pending\n",
    )
    .or_fail("write archived tasks after base commit");
    std::fs::write(archive_dir.join("report.md"), "# final report\n")
        .or_fail("leave archived workspace dirty after base commit");

    let (tx, mut rx) = mpsc::channel(64);
    let config = create_test_config();
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(std::time::Instant::now());
    }
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(change_id, workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
        guard.apply_execution_event(&crate::events::ExecutionEvent::ApplyStarted {
            change_id: change_id.to_string(),
            command: "apply".to_string(),
        });
        guard.apply_execution_event(&crate::events::ExecutionEvent::ArchiveFailed {
            change_id: change_id.to_string(),
            error: "Archive commit finalization failed".to_string(),
            reason: Some("archive_commit_incomplete".to_string()),
            summary: Some("archive move complete, commit incomplete".to_string()),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let mut queued = Vec::new();
    let added = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;
    let last_queue_change_after_repair = *executor.last_queue_change_at.lock().await;
    let rediscovered = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;

    assert_eq!(
        added.total_added(),
        0,
        "terminal-error reducer state must not be rediscovered as ordinary archived-dirty repair work"
    );
    assert_eq!(
        rediscovered.total_added(),
        0,
        "unchanged terminal-error rediscovery should remain stopped"
    );
    assert_eq!(
        *executor.last_queue_change_at.lock().await,
        last_queue_change_after_repair,
        "terminal-error reconciliation must not refresh normal queue debounce"
    );
    assert!(queued.is_empty());

    {
        let guard = shared.read().await;
        assert!(
            guard.is_terminal_error_change(change_id),
            "fixture must reach the real post-failure terminal-error shape"
        );
        assert!(
            guard.queued_change_ids().is_empty(),
            "a terminal error revokes ordinary queue intent until RetryError restores it"
        );
    }

    while let Ok(event) = rx.try_recv() {
        if let crate::events::ExecutionEvent::Log(log) = event {
            assert!(
                !log.message.contains("archived_dirty_repair_candidate"),
                "terminal-error worktree must not emit archived-dirty repair diagnostics: {}",
                log.message
            );
        }
    }

    // Accepted `RetryError` is the only path back: the identical workspace
    // evidence that was refused above now resolves to archive-finalization
    // repair work, which proves the stop was the terminal-error gate rather
    // than unusable evidence.
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::RetryError(change_id.to_string()));
    }
    assert_eq!(
        shared.read().await.queued_change_ids(),
        vec![change_id.to_string()]
    );

    let after_retry = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;
    assert_eq!(
        after_retry.repair_added, 1,
        "explicit RetryError must re-enable archived-dirty repair for the same workspace evidence"
    );
    assert_eq!(
        queued
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec![change_id],
        "retry recovery must resolve the change from its preserved workspace"
    );

    let mut repair_candidate_diagnostics = 0usize;
    while let Ok(event) = rx.try_recv() {
        if let crate::events::ExecutionEvent::Log(log) = event {
            if log.message.contains("archived_dirty_repair_candidate") {
                repair_candidate_diagnostics += 1;
            }
        }
    }
    assert_eq!(repair_candidate_diagnostics, 1);
}

async fn assert_parallel_acceptance_failure_stalls_within_one_run(stale_checkpoint: bool) {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    init_git_repo(repo_dir.path()).await;

    let change_id = "acceptance-restart";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create active change dir");
    std::fs::write(change_dir.join("proposal.md"), "# Acceptance restart\n")
        .or_fail("write active proposal");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write active tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git add active change");
    Command::new("git")
        .args(["commit", "-m", "Add active change"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git commit active change");
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let workspace_path = workspace_base.path().join(change_id);
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            change_id,
            workspace_path.to_string_lossy().as_ref(),
            "HEAD",
        ])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("create resumed worktree");
    Command::new("git")
        .args([
            "commit",
            "--allow-empty",
            "-m",
            &format!("Apply: {change_id}"),
        ])
        .current_dir(&workspace_path)
        .output()
        .await
        .or_fail("create applied resume commit");

    let checkpoint_path = workspace_path.join(".cflx/acceptance-state.json");
    if stale_checkpoint {
        // Conflux's own runtime directory is excluded from Git the way a real
        // workspace carrying it must be. Without this the Apply finalization
        // stage gate would classify the checkpoint below as untracked agent
        // work and spend the whole iteration budget on stage repair, which is
        // a different scenario from the one under test.
        // `info/exclude` lives in the common Git directory, so writing it once
        // in the base repository also covers the linked worktree.
        let exclude_path = repo_dir.path().join(".git/info/exclude");
        std::fs::create_dir_all(exclude_path.parent().or_fail("exclude parent"))
            .or_fail("create Git info dir");
        std::fs::write(&exclude_path, ".cflx/\n").or_fail("exclude the Conflux runtime directory");

        // A checkpoint left behind by an older Conflux version claims an almost
        // exhausted retry budget for this exact change. Dispatch must ignore it.
        let finding_identity =
            crate::orchestration::acceptance::normalize_findings(&["repeated finding"
                .to_string()
                .into()])[0]
                .identity
                .clone();
        std::fs::create_dir_all(checkpoint_path.parent().or_fail("checkpoint parent"))
            .or_fail("create stale checkpoint dir");
        std::fs::write(
            &checkpoint_path,
            format!(
                "{{\"state\":\"failed\",\"revision\":\"stale\",\"updated_at\":\"now\",                 \"workspace_path\":\"{}\",\"change_id\":\"{change_id}\",                 \"previous_finding_identities\":[\"{finding_identity}\"],                 \"semantic_fingerprint\":\"stale\",\"cycle_count\":{}}}",
                workspace_path.display(),
                MAX_ACCEPTANCE_RETRY_CYCLES - 1,
            ),
        )
        .or_fail("write stale checkpoint");
    }

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        // Apply only checks off the acceptance follow-up boxes, so the
        // semantic fingerprint (which ignores follow-up sections) stays
        // unchanged and only repeated findings drive the stall decision.
        //
        // It stages what it edits because the Apply finalization stage gate
        // requires the agent to select change-owned files itself. Leaving the
        // edit unstaged would fail the gate on every task-complete boundary and
        // spend the whole iteration budget on stage repair, which is not the
        // behavior under test here.
        apply_command: Some(format!(
            "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
             > openspec/changes/{change_id}/tasks.next \
             && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md \
             && git add openspec/changes/{change_id}/tasks.md\""
        )),
        acceptance_command: Some(
            "sh -c 'echo ACCEPTANCE: FAIL; echo FINDINGS:; echo - repeated finding'".to_string(),
        ),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(128);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision.clone(),
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch resumed workspace");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");
    // Repeated findings without semantic progress are a runtime retry judgement,
    // not a reviewer-validated external blocker. The loop stops and requires an
    // explicit retry, without inventing a blocker category or writing anything
    // into the change directory. The stop is a hold, so the change is never
    // failed: its diagnostic travels on the acceptance-phase hold below.
    assert_eq!(
        result.error, None,
        "a repeated-finding stop must hold the change, not fail it"
    );
    assert!(
        crate::parallel::acceptance_state::parse_blocked_marker(&workspace_path, change_id)
            .or_fail("read change directory")
            .is_none(),
        "acceptance must not create a blocked marker under the change directory"
    );

    if stale_checkpoint {
        assert!(
            checkpoint_path.exists(),
            "dispatch must not consume generated acceptance state"
        );
    } else {
        assert!(
            !checkpoint_path.exists(),
            "dispatch must never create an acceptance checkpoint"
        );
    }

    let mut acceptance_count = 0;
    let mut apply_count = 0;
    let mut saw_gated = false;
    let mut execution_hold = None;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                acceptance_count += 1;
            }
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                apply_count += 1;
            }
            ExecutionEvent::AcceptanceGated { change_id: id, .. } if id == change_id => {
                saw_gated = true;
            }
            ExecutionEvent::ExecutionBlocked {
                change_id: id,
                blocker,
            } if id == change_id => {
                execution_hold = Some(blocker);
            }
            _ => {}
        }
    }
    assert_eq!(
        acceptance_count, 2,
        "the first failure must retry apply and only the repeated failure may stop"
    );
    assert_eq!(
        apply_count, 1,
        "exactly one apply retry precedes the repeated-finding stop"
    );
    assert!(
        !saw_gated,
        "evidence-free retry exhaustion must not emit an external-blocker lifecycle transition"
    );

    let blocker = execution_hold.or_fail("the repeated-finding stop must emit an acceptance hold");
    assert_eq!(blocker.phase, "acceptance");
    assert!(
        blocker
            .error_summary
            .contains("repeated_acceptance_finding"),
        "diagnostic must name the retry judgement: {}",
        blocker.error_summary
    );
    assert!(
        blocker.error_summary.contains("retry explicitly"),
        "diagnostic must state the operator action: {}",
        blocker.error_summary
    );
    // No invented external category: the hold classifies as non-terminal
    // `stalled`, which is what keeps the worktree preserved.
    assert_eq!(blocker.unblock_condition, None);
    let mut state = OrchestratorState::new(vec![change_id.to_string()], 0);
    state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
        change_id: change_id.to_string(),
        command: "accept".to_string(),
    });
    state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
        change_id: change_id.to_string(),
        blocker,
    });
    assert_eq!(state.display_status(change_id), "stalled");
    let runtime = state
        .change_runtime(change_id)
        .or_fail("runtime entry for the held change");
    assert!(
        matches!(
            runtime.terminal,
            crate::orchestration::state::TerminalState::None
        ),
        "a repeated-finding hold must stay non-terminal, got {:?}",
        runtime.terminal
    );
    assert_eq!(runtime.wait_state, WaitState::Stalled);
}

/// Observations from one dispatch whose acceptance command emits bare
/// `ACCEPTANCE: GATED` for its first `bare_attempts` invocations and then the
/// supplied final verdict payload.
struct GatedDispatch {
    result: WorkspaceResult,
    workspace_path: std::path::PathBuf,
    acceptance_invocations: u32,
    apply_invocations: u32,
    stalled_events: Vec<crate::events::StalledBlocker>,
    prompts: Vec<String>,
}

/// Reducer state standing in for one Conflux process lifetime.
///
/// An acceptance stall now lives here and nowhere else, so passing a fresh
/// state models a restart and reusing one models a second dispatch inside the
/// same process.
fn new_process_state(change_id: &str) -> Arc<tokio::sync::RwLock<OrchestratorState>> {
    Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        10,
    )))
}

/// Dispatch one change against a gated-then-final acceptance fixture.
///
/// `shared_state` is the reducer that owns the in-memory acceptance hold for
/// this simulated process. Nothing is read from or written to the XDG state
/// area, so tests cannot observe each other's holds.
#[allow(clippy::too_many_arguments)]
async fn dispatch_gated_run(
    repo_root: &std::path::Path,
    workspace_base_dir: &std::path::Path,
    state_dir: &std::path::Path,
    shared_state: &Arc<tokio::sync::RwLock<OrchestratorState>>,
    change_id: &str,
    bare_attempts: u32,
    final_verdict: &str,
    explicit_retry: bool,
) -> GatedDispatch {
    let base_revision = get_current_commit(repo_root)
        .await
        .or_fail("get base revision");

    let counter = state_dir.join("attempts");
    let prompt_dir = state_dir.join("prompts");
    std::fs::create_dir_all(&prompt_dir).or_fail("create prompt capture dir");
    // The final verdict is read from a file so JSON quoting survives the shell
    // round trip intact.
    let verdict_file = state_dir.join("final-verdict.txt");
    std::fs::write(&verdict_file, final_verdict).or_fail("write final verdict fixture");
    let counter_display = counter.display().to_string();
    let prompt_dir_display = prompt_dir.display().to_string();
    let verdict_display = verdict_file.display().to_string();

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base_dir.to_string_lossy().to_string()),
        // Stages its own edit: the finalization stage gate requires the Apply
        // agent to select change-owned files itself.
        apply_command: Some(format!(
            "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
             > openspec/changes/{change_id}/tasks.next \
             && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md \
             && git add -A\""
        )),
        acceptance_command: Some(format!(
            "sh -c 'n=$(cat \"{counter_display}\" 2>/dev/null || echo 0); n=$((n+1)); \
             echo $n > \"{counter_display}\"; \
             printf \"%s\" \"$0\" > \"{prompt_dir_display}/attempt-$n.txt\"; \
             if [ $n -gt {bare_attempts} ]; then cat \"{verdict_display}\"; \
             else echo \"ACCEPTANCE: GATED\"; fi' {{prompt}}"
        )),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));
    executor.set_shared_orchestrator_state(shared_state.clone());
    executor.set_explicit_retry(explicit_retry);
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_root.to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch gated change");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    let workspace_path = workspace_base_dir.join(format!("cflx-{change_id}"));
    let workspace_path = if workspace_path.exists() {
        workspace_path
    } else {
        executor
            .workspace_manager
            .find_existing_workspace(change_id)
            .await
            .ok()
            .flatten()
            .map(|workspace| workspace.path)
            .unwrap_or_else(|| workspace_base_dir.join(change_id))
    };

    let mut observed = GatedDispatch {
        result,
        workspace_path,
        acceptance_invocations: 0,
        apply_invocations: 0,
        stalled_events: Vec::new(),
        prompts: Vec::new(),
    };

    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                observed.acceptance_invocations += 1;
            }
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                observed.apply_invocations += 1;
            }
            ExecutionEvent::AcceptanceGated {
                change_id: id,
                blocker,
            } if id == change_id => observed.stalled_events.push(blocker),
            _ => {}
        }
    }

    let mut attempt = 1;
    while let Ok(prompt) =
        std::fs::read_to_string(prompt_dir.join(format!("attempt-{attempt}.txt")))
    {
        observed.prompts.push(prompt);
        attempt += 1;
    }

    observed
}

fn workspace_porcelain_status(workspace_path: &std::path::Path) -> String {
    let output = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(workspace_path)
        .output()
        .or_fail("read workspace git status");
    String::from_utf8(output.stdout).or_fail("decode git status")
}

fn workspace_head(workspace_path: &std::path::Path) -> String {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(workspace_path)
        .output()
        .or_fail("read workspace HEAD");
    String::from_utf8(output.stdout)
        .or_fail("decode HEAD")
        .trim()
        .to_string()
}

const VALIDATED_BLOCKER_VERDICT: &str = concat!(
    r#"{"acceptance":"gated","blocker":{"category":"credential","#,
    r#""evidence":["STAGING_API_KEY is unset in the verification environment"],"#,
    r#""unblock_condition":"STAGING_API_KEY is present in the verification environment","#,
    r#""next_action":"provision STAGING_API_KEY then retry acceptance","resumable":true}}"#,
    "\n"
);

/// gated → gated → PASS: exactly two acceptance-only retries, one apply, no
/// stalled transition, and a clean worktree with the apply commit intact.
#[tokio::test]
async fn parallel_bare_gated_retries_then_passes_without_stalling() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create fixture state dir");
    let change_id = "parallel-bare-gated-pass";
    let shared_state = new_process_state(change_id);
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let observed = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        state_dir.path(),
        &shared_state,
        change_id,
        2,
        "ACCEPTANCE: PASS\n",
        false,
    )
    .await;

    assert!(
        observed.result.error.is_none(),
        "bare gated within budget must not fail the workspace: {:?}",
        observed.result.error
    );
    assert_eq!(
        observed.acceptance_invocations, 3,
        "the initial attempt plus exactly two protocol retries must run"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "a bare gated protocol retry must never rerun apply"
    );
    assert!(
        observed.stalled_events.is_empty(),
        "bare gated input must emit no stalled lifecycle transition"
    );

    assert!(!observed.prompts[0].contains("<acceptance_protocol_retry>"));
    for attempt in [1usize, 2] {
        let prompt = &observed.prompts[attempt];
        assert!(prompt.contains("<acceptance_protocol_retry>"));
        assert!(prompt.contains("without a validated structured blocker"));
        assert!(prompt.contains("Supported categories:"));
    }

    assert!(
        !observed
            .workspace_path
            .join("openspec/changes")
            .join(change_id)
            .join("APPLY_BLOCKED")
            .exists(),
        "acceptance must not create a marker under the change directory"
    );
}

/// Three consecutive bare gated results exhaust the shared budget, produce a
/// terminal protocol error, and still leave a clean worktree with no hold.
#[tokio::test]
async fn parallel_bare_gated_exhaustion_is_terminal_and_creates_no_hold() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create fixture state dir");
    let change_id = "parallel-bare-gated-exhausted";
    let shared_state = new_process_state(change_id);
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let observed = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        state_dir.path(),
        &shared_state,
        change_id,
        5,
        "ACCEPTANCE: PASS\n",
        false,
    )
    .await;

    let error = observed
        .result
        .error
        .as_deref()
        .or_fail("exhausted bare gated retries must be terminal");
    assert!(error.contains("bare-blocker protocol failure"), "{error}");
    assert!(
        error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"),
        "{error}"
    );
    assert_eq!(
        observed.acceptance_invocations, 3,
        "no fourth protocol retry may start after exhaustion"
    );
    assert_eq!(observed.apply_invocations, 1);
    assert!(observed.stalled_events.is_empty());

    // No hold anywhere, and the worktree is untouched by acceptance.
    assert!(shared_state
        .read()
        .await
        .acceptance_stalled_change_ids()
        .is_empty());
    assert_eq!(workspace_porcelain_status(&observed.workspace_path), "");
}

/// A validated structured blocker stalls immediately, records the hold in the
/// reducer only, and preserves the clean worktree and apply commit. A restart —
/// a fresh reducer — must then run acceptance again rather than restoring the
/// stall, and an explicit retry inside the same process must resume acceptance
/// without rerunning apply.
/// Heavy: three full dispatch rounds against real git worktrees put this over
/// the one-second default-suite budget. The individual behaviours it chains are
/// also covered by faster default tests (blocker projection in
/// `execution::state`, reducer hold semantics in `orchestration::state`,
/// dispatch suppression in
/// `in_memory_stalled_change_is_not_requeued_until_its_hold_is_cleared`); this
/// test exists to prove they compose end to end.
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn parallel_validated_blocker_stalls_then_restart_reruns_acceptance() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let change_id = "parallel-validated-stall";
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    // --- 1. Enter the stall -------------------------------------------------
    let first_process = new_process_state(change_id);
    let first = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        TempDir::new().or_fail("state dir").path(),
        &first_process,
        change_id,
        0,
        VALIDATED_BLOCKER_VERDICT,
        false,
    )
    .await;

    assert!(
        first.result.error.is_none(),
        "a validated stall is not an error: {:?}",
        first.result.error
    );
    assert_eq!(
        first.acceptance_invocations, 1,
        "a validated blocker must not consume protocol retry budget"
    );
    assert_eq!(first.stalled_events.len(), 1);
    assert_eq!(first.stalled_events[0].category, "credential");
    assert!(first.stalled_events[0].resumable);

    let apply_revision = workspace_head(&first.workspace_path);
    assert_eq!(
        workspace_porcelain_status(&first.workspace_path),
        "",
        "entering a stall must leave the managed worktree clean"
    );
    assert!(!first
        .workspace_path
        .join("openspec/changes")
        .join(change_id)
        .join("APPLY_BLOCKED")
        .exists());

    // The hold exists in the reducer and nowhere else, and it is a validated
    // external prerequisite wait rather than an execution stall.
    assert!(first_process
        .read()
        .await
        .acceptance_stalled_change_ids()
        .contains(change_id));
    assert_eq!(
        first_process.read().await.display_status(change_id),
        "blocked"
    );
    assert_eq!(
        first_process
            .read()
            .await
            .change_runtime(change_id)
            .expect("runtime entry for an externally blocked change")
            .blocker_kind(),
        crate::orchestration::state::BlockerKind::External
    );

    // --- 2. Restart: no hold survives, so acceptance runs again -------------
    let restarted_process = new_process_state(change_id);
    let restarted = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        TempDir::new().or_fail("restart state dir").path(),
        &restarted_process,
        change_id,
        0,
        VALIDATED_BLOCKER_VERDICT,
        false,
    )
    .await;

    assert!(restarted.result.error.is_none());
    assert_eq!(
        restarted.acceptance_invocations, 1,
        "a restart must run acceptance again for a complete unarchived apply"
    );
    assert_eq!(
        restarted.apply_invocations, 0,
        "a restart must not rerun apply for a complete apply revision"
    );
    assert_eq!(workspace_porcelain_status(&first.workspace_path), "");
    assert_eq!(
        workspace_head(&first.workspace_path),
        apply_revision,
        "the apply commit must survive a stalled restart"
    );

    // --- 3. Explicit retry resumes acceptance only --------------------------
    let retried = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        TempDir::new().or_fail("retry state dir").path(),
        &restarted_process,
        change_id,
        0,
        "ACCEPTANCE: PASS\n",
        true,
    )
    .await;

    assert_eq!(
        retried.acceptance_invocations, 1,
        "explicit retry must re-run acceptance"
    );
    assert_eq!(
        retried.apply_invocations, 0,
        "explicit retry must resume at acceptance without rerunning apply"
    );
}

/// Ordinary queue reconciliation must not re-submit an in-memory-stalled
/// change, and clearing the hold must release the change again.
#[tokio::test]
async fn in_memory_stalled_change_is_not_requeued_until_its_hold_is_cleared() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let change_id = "parallel-queue-stalled";
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let shared_state = new_process_state(change_id);
    let observed = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        TempDir::new().or_fail("state dir").path(),
        &shared_state,
        change_id,
        0,
        VALIDATED_BLOCKER_VERDICT,
        false,
    )
    .await;
    assert_eq!(observed.stalled_events.len(), 1);

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, None);
    executor.set_shared_orchestrator_state(shared_state.clone());

    let queued = vec![make_test_change(change_id)];
    let classification = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;
    assert_eq!(
        classification.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::AcceptanceStalled),
        "an in-memory stalled change must not be classified as dispatchable"
    );
    assert!(
        !classification.has_dispatchable_apply(),
        "ordinary reconciliation must not re-submit a stalled change (Blocked -> Blocked)"
    );
    assert!(classification.has_blocked_or_waiting_work());

    // An explicit operator retry clears the hold and the change is dispatchable
    // again — a hold can never block work forever.
    shared_state
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue(change_id.to_string()));

    let classification = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;
    assert_ne!(
        classification.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::AcceptanceStalled),
        "a cleared hold must release the change"
    );
}

/// The external-blocker branch in `dispatch.rs` emits `AcceptanceGated` and then
/// the compatibility `WorkspaceStatusUpdated { Blocked }` on the same channel.
///
/// The TUI boundary owns an `EventDispatcher` that reduces *both* events, so the
/// ordered pair — not the structured event alone — is what queue classification
/// actually sees. (The headless CLI path records the structured hold directly
/// through `record_stall_in_shared_state` and forwards channel events to the Web
/// projection without reducing them a second time, which is why this
/// reducer-owning boundary is the one under test.)
///
/// Before monotonic reducer precedence the second event rebuilt the hold as a
/// generic stall, both held sets went empty, and the unchanged applied workspace
/// became an ordinary dispatchable candidate that would repeat Acceptance.
#[tokio::test]
async fn external_blocker_hold_survives_dispatch_status_through_the_tui_event_dispatcher() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    let change_id = "external-blocked-dispatch";

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue(change_id.to_string()));

    let dispatcher =
        crate::events::EventDispatcher::new(shared.clone(), crate::events::cli_event_sinks());

    // Exactly the ordered pair the external-blocker branch produces.
    dispatcher
        .dispatch(ExecutionEvent::AcceptanceGated {
            change_id: change_id.to_string(),
            blocker: crate::events::StalledBlocker::acceptance_external(
                "credential",
                "STAGING_API_KEY is unset",
            ),
        })
        .await;
    dispatcher
        .dispatch(ExecutionEvent::WorkspaceStatusUpdated {
            change_id: change_id.to_string(),
            workspace_name: format!("ws-{change_id}"),
            status: WorkspaceStatus::Blocked,
        })
        .await;

    {
        let guard = shared.read().await;
        assert_eq!(guard.display_status(change_id), "blocked");
        let view = guard
            .blocker_view(change_id)
            .or_fail("the hold must survive the compatibility status event");
        assert_eq!(
            view.kind,
            crate::orchestration::state::BlockerKind::External,
            "the generic status must not downgrade the blocker kind"
        );
        assert_eq!(view.origin.as_deref(), Some("acceptance"));
        assert!(view.unblock_condition.is_some());
        assert!(view.resumable);
        assert_eq!(
            guard.externally_blocked_change_ids(),
            HashSet::from([change_id.to_string()])
        );
    }

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.set_shared_orchestrator_state(shared.clone());

    let queued = vec![make_test_change(change_id)];
    let classification = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;

    assert_eq!(
        classification.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::AcceptanceStalled),
        "the held change must stay held after the compatibility status event"
    );
    assert!(
        !classification.has_dispatchable_apply(),
        "an unchanged applied workspace must not automatically repeat acceptance"
    );
    assert!(classification.has_blocked_or_waiting_work());

    // The hold is a wait, not a wall: an explicit retry still releases it.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
    let after_retry = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;
    assert_ne!(
        after_retry.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::AcceptanceStalled),
        "an explicit retry must release the preserved hold"
    );
}

/// A restart is modelled by a fresh reducer: no hold exists, so the same queued
/// change is dispatchable again and acceptance decides its fate.
#[tokio::test]
async fn restart_drops_the_in_memory_stall_and_makes_the_change_dispatchable() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let change_id = "parallel-restart-stalled";
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let stalled_process = new_process_state(change_id);
    let observed = dispatch_gated_run(
        repo_dir.path(),
        workspace_base.path(),
        TempDir::new().or_fail("state dir").path(),
        &stalled_process,
        change_id,
        0,
        VALIDATED_BLOCKER_VERDICT,
        false,
    )
    .await;
    assert_eq!(observed.stalled_events.len(), 1);

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, None);
    executor.set_shared_orchestrator_state(new_process_state(change_id));

    let queued = vec![make_test_change(change_id)];
    let classification = executor
        .classify_queued_work(&queued, &HashSet::new())
        .await;
    assert_ne!(
        classification.class_for(change_id),
        Some(crate::parallel::queue_state::QueuedWorkClass::AcceptanceStalled),
        "no stall state may survive a restart"
    );
}

/// The whole acceptance stall lifecycle — recording a hold, suppressing
/// dispatch, presenting `stalled`, and consuming an explicit retry — must do no
/// file I/O at all. No module that participates in it may reach for the retired
/// out-of-worktree store, so deleting `~/.local/state/cflx/**` cannot change the
/// next action for any workspace.
#[test]
fn acceptance_stall_lifecycle_does_no_file_io() {
    for (label, source) in [
        ("parallel dispatch", include_str!("../dispatch.rs")),
        ("queue classification", include_str!("../queue_state.rs")),
        ("reducer", include_str!("../../orchestration/state.rs")),
        ("cleanup", include_str!("../cleanup.rs")),
        ("merge", include_str!("../merge.rs")),
        ("archive", include_str!("../../execution/archive.rs")),
    ] {
        for forbidden in [
            "AcceptanceStallStore",
            "load_valid_acceptance_stall",
            "persist_acceptance_stall",
            "acceptance-stalls",
        ] {
            assert!(
                !source.contains(forbidden),
                "{label} must not consult out-of-worktree acceptance stall state ({forbidden})"
            );
        }
    }
}

/// Observations collected from one dispatch driven by a stateful fake
/// acceptance command that withholds a canonical verdict for the first
/// `missing_attempts` invocations and then emits `ACCEPTANCE: PASS`./// Observations collected from one dispatch driven by a stateful fake
/// acceptance command that withholds a canonical verdict for the first
/// `missing_attempts` invocations and then emits `ACCEPTANCE: PASS`.
struct MissingVerdictDispatch {
    result: WorkspaceResult,
    workspace_path: std::path::PathBuf,
    acceptance_invocations: u32,
    apply_invocations: u32,
    retry_progress_logs: Vec<String>,
    acceptance_error_logs: Vec<String>,
    saw_processing_error: bool,
    /// Prompt text handed to each acceptance invocation, in order.
    prompts: Vec<String>,
}

/// Dispatch one change whose acceptance command exits without a canonical
/// verdict for its first `missing_attempts` invocations.
///
/// The command is the ordinary configured acceptance command on every
/// invocation — the fixture never supplies a harness session, resume flag, or
/// job identifier, so continuity can only come from Conflux-managed prompt
/// context.
async fn dispatch_with_missing_verdict_attempts(
    change_id: &str,
    missing_attempts: u32,
) -> MissingVerdictDispatch {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create acceptance fixture state dir");
    init_missing_verdict_repo(repo_dir.path(), change_id).await;
    dispatch_missing_verdict_run(
        repo_dir.path(),
        workspace_base.path(),
        state_dir.path(),
        change_id,
        missing_attempts,
    )
    .await
}

/// Create the base repository fixture for a missing-verdict dispatch.
///
/// The change starts with an incomplete task so apply genuinely runs once; a
/// protocol retry must then re-run acceptance only.
async fn init_missing_verdict_repo(repo_root: &std::path::Path, change_id: &str) {
    let change_dir = repo_root.join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create active change dir");
    std::fs::write(change_dir.join("proposal.md"), "# Missing verdict\n")
        .or_fail("write active proposal");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [ ] done\n",
    )
    .or_fail("write active tasks");
    init_git_repo(repo_root).await;
}

/// Run one dispatch against an existing repository fixture. Calling this twice
/// with the same repository and workspace base — but a fresh executor, agent,
/// and acceptance counter — models a process restart over the same unarchived
/// workspace.
async fn dispatch_missing_verdict_run(
    repo_root: &std::path::Path,
    workspace_base_dir: &std::path::Path,
    state_dir: &std::path::Path,
    change_id: &str,
    missing_attempts: u32,
) -> MissingVerdictDispatch {
    let repo_dir = repo_root;
    let workspace_base = workspace_base_dir;
    let base_revision = get_current_commit(repo_dir)
        .await
        .or_fail("get base revision");

    let counter = state_dir.join("attempts");
    let prompt_dir = state_dir.join("prompts");
    std::fs::create_dir_all(&prompt_dir).or_fail("create prompt capture dir");
    let counter_display = counter.display().to_string();
    let prompt_dir_display = prompt_dir.display().to_string();

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.to_string_lossy().to_string()),
        // Stages its own edit: the finalization stage gate requires the Apply
        // agent to select change-owned files itself.
        apply_command: Some(format!(
            "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
             > openspec/changes/{change_id}/tasks.next \
             && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md \
             && git add -A\""
        )),
        acceptance_command: Some(format!(
            "sh -c 'n=$(cat \"{counter_display}\" 2>/dev/null || echo 0); n=$((n+1)); \
             echo $n > \"{counter_display}\"; \
             printf \"%s\" \"$0\" > \"{prompt_dir_display}/attempt-$n.txt\"; \
             if [ $n -gt {missing_attempts} ]; then echo \"ACCEPTANCE: PASS\"; \
             else echo \"Monitoring verification, waiting for the owned job to finish\"; fi' \
             {{prompt}}"
        )),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(repo_dir.to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch missing-verdict change");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    let workspace_path = workspace_base.join(format!("cflx-{change_id}"));
    let workspace_path = if workspace_path.exists() {
        workspace_path
    } else {
        executor
            .workspace_manager
            .find_existing_workspace(change_id)
            .await
            .ok()
            .flatten()
            .map(|workspace| workspace.path)
            .unwrap_or_else(|| workspace_base.join(change_id))
    };

    let mut observed = MissingVerdictDispatch {
        result,
        workspace_path,
        acceptance_invocations: 0,
        apply_invocations: 0,
        retry_progress_logs: Vec::new(),
        acceptance_error_logs: Vec::new(),
        saw_processing_error: false,
        prompts: Vec::new(),
    };

    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                observed.acceptance_invocations += 1;
            }
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                observed.apply_invocations += 1;
            }
            ExecutionEvent::ProcessingError { id, .. } if id == change_id => {
                observed.saw_processing_error = true;
            }
            ExecutionEvent::Log(log) => {
                if log.message.contains("protocol retry") {
                    observed.retry_progress_logs.push(log.message.clone());
                }
                if matches!(log.level, crate::events::LogLevel::Error)
                    && log.operation.as_deref() == Some("acceptance")
                {
                    observed.acceptance_error_logs.push(log.message.clone());
                }
            }
            _ => {}
        }
    }

    let mut attempt = 1;
    while let Ok(prompt) =
        std::fs::read_to_string(prompt_dir.join(format!("attempt-{attempt}.txt")))
    {
        observed.prompts.push(prompt);
        attempt += 1;
    }

    observed
}

/// A status-only acceptance exit must re-invoke the ordinary acceptance command
/// with bounded continuation context instead of failing the workspace, and a
/// later canonical PASS must archive normally.
#[tokio::test]
async fn parallel_missing_verdict_retries_then_passes_without_terminal_error() {
    let change_id = "missing-verdict-retry-pass";
    let observed = dispatch_with_missing_verdict_attempts(change_id, 2).await;

    assert!(
        observed.result.error.is_none(),
        "acceptance must continue through the protocol retry instead of failing: {:?}",
        observed.result.error
    );
    assert!(
        observed.result.final_revision.is_some(),
        "a canonical PASS after protocol retries must still hand off to archive"
    );
    assert_eq!(
        observed.acceptance_invocations, 3,
        "the initial attempt plus two protocol retries must run the acceptance command"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "a protocol retry re-runs acceptance only; the implementation did not fail"
    );
    assert!(
        !observed.saw_processing_error,
        "an in-budget protocol retry must not report the change as a terminal error, so queue \
         reconciliation cannot classify it as terminal_error_retry_required"
    );
    assert!(
        observed.acceptance_error_logs.is_empty(),
        "no acceptance error event may be emitted before exhaustion: {:?}",
        observed.acceptance_error_logs
    );

    // Non-terminal progress must be visible with attempt/maximum values.
    assert_eq!(
        observed.retry_progress_logs.len(),
        2,
        "each protocol retry must report progress: {:?}",
        observed.retry_progress_logs
    );
    assert!(observed.retry_progress_logs[0].contains("protocol retry 1/2"));
    assert!(observed.retry_progress_logs[1].contains("protocol retry 2/2"));

    // Continuation comes only from Conflux-managed prompt context.
    assert_eq!(observed.prompts.len(), 3);
    assert!(
        !observed.prompts[0].contains("<acceptance_protocol_retry>"),
        "the initial attempt must not receive corrective retry context"
    );
    for prompt in &observed.prompts[1..] {
        assert!(prompt.contains("<acceptance_protocol_retry>"));
        assert!(prompt.contains("emit exactly one canonical verdict"));
        assert!(
            prompt.contains("Monitoring verification"),
            "the retry must carry bounded prior acceptance output"
        );
        assert!(
            prompt.contains("Missing acceptance verdict"),
            "the retry must carry the recorded missing-verdict diagnostic"
        );
        let lower = prompt.to_ascii_lowercase();
        for forbidden in ["session_id", "--resume", "job_id"] {
            assert!(
                !lower.contains(forbidden),
                "continuation must stay harness neutral, found `{forbidden}`"
            );
        }
    }

    assert!(
        !observed
            .workspace_path
            .join("ACCEPTANCE_REPORT.json")
            .exists(),
        "protocol retries must not create a workspace acceptance report"
    );
    assert!(
        !observed
            .workspace_path
            .join(".cflx/acceptance-state.json")
            .exists(),
        "protocol retries must not create a durable acceptance checkpoint"
    );
}

/// Three consecutive missing verdicts exhaust the dedicated budget and produce
/// exactly one bounded terminal diagnostic.
#[tokio::test]
async fn parallel_missing_verdict_exhaustion_is_terminal_with_bounded_evidence() {
    let change_id = "missing-verdict-exhausted";
    let observed = dispatch_with_missing_verdict_attempts(change_id, u32::MAX).await;

    let error = observed
        .result
        .error
        .as_ref()
        .or_fail("exhausted protocol retries must fail the workspace");
    assert!(error.contains("missing-verdict protocol failure"));
    assert!(error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"));
    assert!(
        error.contains("Monitoring verification"),
        "terminal diagnostic must retain bounded evidence, got: {error}"
    );

    assert_eq!(
        observed.acceptance_invocations, 3,
        "no fourth protocol retry may start"
    );
    assert_eq!(observed.apply_invocations, 1);
    assert_eq!(
        observed.retry_progress_logs.len(),
        2,
        "only the two in-budget retries report non-terminal progress"
    );
    assert_eq!(
        observed.acceptance_error_logs.len(),
        1,
        "exhaustion must emit exactly one terminal acceptance error: {:?}",
        observed.acceptance_error_logs
    );
    assert!(observed.acceptance_error_logs[0].contains("Missing acceptance verdict"));

    assert!(
        !observed
            .workspace_path
            .join("ACCEPTANCE_REPORT.json")
            .exists(),
        "an exhausted missing verdict must not create a workspace acceptance report"
    );
}

/// Constitutional restart behavior: the protocol counter is active-run memory,
/// so a run that starts on a still-unarchived workspace runs acceptance again
/// from workspace state and cannot infer PASS from prior narrative output.
#[tokio::test]
async fn parallel_restart_reruns_acceptance_without_inferring_pass_from_prior_output() {
    let change_id = "missing-verdict-restart";
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create acceptance state dir");
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    // Model the post-restart world directly: an applied but unarchived
    // workspace and no out-of-worktree runtime state at all. A previous run's
    // protocol retries left nothing behind.
    let workspace_path = workspace_base.path().join(change_id);
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            change_id,
            workspace_path.to_string_lossy().as_ref(),
            "HEAD",
        ])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("create applied-but-unarchived worktree");
    std::fs::write(
        workspace_path
            .join("openspec/changes")
            .join(change_id)
            .join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("mark tasks applied in the resumed worktree");
    for args in [
        vec!["add", "-A"],
        vec!["commit", "-m", &format!("Apply: {change_id}")],
    ] {
        Command::new("git")
            .args(args)
            .current_dir(&workspace_path)
            .output()
            .await
            .or_fail("record the applied worktree commit");
    }

    let observed = dispatch_missing_verdict_run(
        repo_dir.path(),
        workspace_base.path(),
        state_dir.path(),
        change_id,
        u32::MAX,
    )
    .await;

    assert_eq!(
        observed.acceptance_invocations, 3,
        "the still-unarchived workspace must run acceptance again with a full, fresh protocol budget"
    );
    assert_eq!(
        observed.retry_progress_logs.len(),
        2,
        "the restarted run must start a fresh protocol budget at retry 1/2, got {:?}",
        observed.retry_progress_logs
    );
    assert!(observed.retry_progress_logs[0].contains("protocol retry 1/2"));
    assert!(observed.retry_progress_logs[1].contains("protocol retry 2/2"));
    assert!(
        observed
            .prompts
            .first()
            .is_some_and(|prompt| !prompt.contains("<acceptance_protocol_retry>")),
        "the restarted run's first attempt must not resume a prior protocol retry"
    );
    assert!(
        observed.result.final_revision.is_none(),
        "an unarchived workspace must never be treated as accepted from prior narrative output"
    );
    assert!(
        observed
            .result
            .error
            .as_ref()
            .is_some_and(|error| error.contains("missing-verdict protocol failure")),
        "acceptance must reach a verdict again rather than inheriting a prior outcome: {:?}",
        observed.result.error
    );
    assert!(
        !workspace_path.join(".cflx/acceptance-state.json").exists(),
        "restart routing must stay derivable from workspace file/git state"
    );
    assert!(
        !workspace_path.join("ACCEPTANCE_REPORT.json").exists(),
        "restart must not require a generated acceptance retry checkpoint"
    );
}

#[tokio::test]
async fn parallel_repeated_acceptance_failure_stops_without_a_change_directory_marker() {
    assert_parallel_acceptance_failure_stalls_within_one_run(false).await;
}

#[tokio::test]
async fn parallel_restart_ignores_generated_acceptance_state_when_deciding_retries() {
    assert_parallel_acceptance_failure_stalls_within_one_run(true).await;
}

/// End-to-end regression for the post-archive false `MergeWait`.
///
/// Runs apply -> acceptance PASS -> archive commit -> post-archive merge
/// verification in one dispatch and proves that no generated acceptance
/// checkpoint is created, that archive leaves a clean worktree, and that merge
/// verification therefore never produces a manual deferral.
#[tokio::test]
async fn parallel_pass_to_archive_to_merge_never_creates_or_cleans_an_acceptance_checkpoint() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");

    // The active change is part of the base commit so the dispatched worktree
    // and the base branch share a head; post-archive merge then exercises the
    // archive verification path rather than pre-sync handling.
    let change_id = "post-archive-clean";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create active change dir");
    std::fs::write(change_dir.join("proposal.md"), "# Post archive\n")
        .or_fail("write active proposal");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write active tasks");
    init_git_repo(repo_dir.path()).await;
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some("sh -c 'true'".to_string()),
        acceptance_command: Some("sh -c 'echo ACCEPTANCE: PASS'".to_string()),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(128);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch change through the full pipeline");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    assert!(
        result.error.is_none(),
        "pass-to-archive pipeline must succeed: {:?}",
        result.error
    );
    assert!(
        result.final_revision.is_some(),
        "archive must produce a final revision"
    );

    let workspace = executor
        .workspace_manager
        .find_existing_workspace(change_id)
        .await
        .or_fail("look up archived workspace")
        .or_fail("archived workspace should still exist before merge");

    assert!(
        !workspace.path.join(".cflx/acceptance-state.json").exists(),
        "acceptance must never create a workspace checkpoint"
    );
    assert!(
        !repo_dir.path().join(".cflx/acceptance-state.json").exists(),
        "acceptance must never create a base-repository checkpoint"
    );

    let status = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("read post-archive worktree status");
    assert!(
        String::from_utf8_lossy(&status.stdout).trim().is_empty(),
        "post-archive worktree must be clean, got: {}",
        String::from_utf8_lossy(&status.stdout)
    );
    assert!(
        crate::execution::archive::is_archive_commit_complete(change_id, Some(&workspace.path))
            .await
            .or_fail("verify archive completion"),
        "archive completion verification must succeed without checkpoint cleanup"
    );

    while rx.try_recv().is_ok() {}

    // Post-archive merge verification must clear the archive gate. The stub
    // resolve command in this fixture may still fail the later conflict phase;
    // what this regression asserts is that archive verification never produces
    // a manual deferral and that the change reaches the resolving stage.
    let attempt = executor
        .attempt_merge(
            std::slice::from_ref(&workspace.workspace_name),
            &[change_id.to_string()],
            std::slice::from_ref(&workspace.path),
            None,
        )
        .await;
    if let Ok(crate::parallel::merge::MergeAttempt::Deferred(deferred)) = &attempt {
        assert!(
            deferred.auto_resumable,
            "a valid archive must never enter manual MergeWait: {}",
            deferred.reason
        );
    }

    let mut reached_resolving = false;
    while let Ok(event) = rx.try_recv() {
        if let ParallelEvent::ResolveStarted { change_id: id, .. } = event {
            if id == change_id {
                reached_resolving = true;
            }
        }
    }
    assert!(
        reached_resolving,
        "archive verification must pass and hand the change to the resolving stage"
    );
}

#[tokio::test]
async fn test_resumed_workspace_marker_stops_parallel_dispatch_before_apply_acceptance_and_archive()
{
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    init_git_repo(repo_dir.path()).await;

    let change_id = "acceptance-stalled";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create active change dir");
    std::fs::write(change_dir.join("proposal.md"), "# Acceptance stalled\n")
        .or_fail("write active proposal");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write active tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git add active change");
    Command::new("git")
        .args(["commit", "-m", "Add active change"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git commit active change");
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let workspace_path = workspace_base.path().join(format!("cflx-{change_id}"));
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            change_id,
            workspace_path.to_string_lossy().as_ref(),
            "HEAD",
        ])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("create resumed worktree");
    // Apply-origin markers keep their existing conservative blocked routing;
    // they are never migrated or consumed by acceptance.
    let marker_path = workspace_path
        .join("openspec/changes")
        .join(change_id)
        .join("APPLY_BLOCKED/marker.md");
    std::fs::create_dir_all(marker_path.parent().or_fail("marker parent"))
        .or_fail("create marker dir");
    std::fs::write(&marker_path, "origin: apply\nreason: apply blocked\n")
        .or_fail("write apply marker");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some("sh -c 'echo unexpected-apply >&2; exit 42'".to_string()),
        acceptance_command: Some("sh -c 'echo unexpected-acceptance >&2; exit 43'".to_string()),
        archive_command: Some("sh -c 'echo unexpected-archive >&2; exit 44'".to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(128);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch resumed blocked workspace");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    assert!(result.error.is_none());
    assert!(result.final_revision.is_none());
    assert!(
        crate::parallel::acceptance_state::parse_blocked_marker(&workspace_path, change_id)
            .or_fail("read preserved marker")
            .is_some()
    );

    let mut saw_apply_started = false;
    let mut saw_acceptance_started = false;
    let mut saw_archive_started = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                saw_apply_started = true;
            }
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                saw_acceptance_started = true;
            }
            ExecutionEvent::ArchiveStarted { change_id: id, .. } if id == change_id => {
                saw_archive_started = true;
            }
            _ => {}
        }
    }
    assert!(!saw_apply_started);
    assert!(!saw_acceptance_started);
    assert!(!saw_archive_started);
}

#[tokio::test]
async fn test_resumed_merged_leftover_worktree_does_not_emit_apply_or_acceptance_started() {
    use crate::events::ExecutionEvent;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    init_git_repo(repo_dir.path()).await;

    let change_id = "fix-dependency-target-handling";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create active change dir");
    std::fs::write(
        change_dir.join("proposal.md"),
        "# Fix dependency target handling\n",
    )
    .or_fail("write active proposal");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write active tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git add active change");
    Command::new("git")
        .args(["commit", "-m", "Add active change"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git commit active change");
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let workspace_path = workspace_base.path().join(format!("cflx-{change_id}"));
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            change_id,
            workspace_path.to_string_lossy().as_ref(),
            "HEAD",
        ])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("create leftover worktree");

    std::fs::remove_dir_all(workspace_path.join("openspec/changes").join(change_id))
        .or_fail("remove active change dir in leftover worktree");
    let archive_dir =
        workspace_path.join("openspec/changes/archive/2026-05-08-fix-dependency-target-handling");
    std::fs::create_dir_all(&archive_dir).or_fail("create archive dir in leftover worktree");
    std::fs::write(
        archive_dir.join("proposal.md"),
        "# Fix dependency target handling\n",
    )
    .or_fail("write archived proposal in leftover worktree");
    std::fs::write(
        archive_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write archived tasks in leftover worktree");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_path)
        .output()
        .await
        .or_fail("git add archive in leftover worktree");
    Command::new("git")
        .args(["commit", "-m", "Archive fix-dependency-target-handling"])
        .current_dir(&workspace_path)
        .output()
        .await
        .or_fail("git commit archive in leftover worktree");

    Command::new("git")
        .args(["checkout", "main"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("checkout base branch");
    Command::new("git")
        .args(["merge", "--ff-only", change_id])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("merge archive branch to base");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some("sh -c 'echo unexpected-apply >&2; exit 42'".to_string()),
        acceptance_command: Some("sh -c 'echo unexpected-acceptance >&2; exit 43'".to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(128);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch merged leftover worktree");

    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    assert!(
        result.error.is_none(),
        "merged leftover should be terminal no-op: {:?}",
        result.error
    );
    assert!(
        result.final_revision.is_none(),
        "merged leftover should not hand off another revision for merge"
    );

    let mut saw_apply_started = false;
    let mut saw_acceptance_started = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                saw_apply_started = true;
            }
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                saw_acceptance_started = true;
            }
            _ => {}
        }
    }

    assert!(
        !saw_apply_started,
        "merged leftover must not re-enter apply"
    );
    assert!(
        !saw_acceptance_started,
        "merged leftover must not re-enter acceptance"
    );
}

#[test]
fn test_stale_retry_reason_detects_deleted_workspace_path() {
    let temp_dir = TempDir::new().or_fail("create temp dir");
    let workspace_path = temp_dir.path().join("deleted-worktree");
    let workspace = WorkspaceInfo {
        path: workspace_path.clone(),
        change_id: "alpha".to_string(),
        workspace_name: "ws-alpha".to_string(),
        last_modified: std::time::SystemTime::now(),
    };

    let reason = ParallelExecutor::stale_retry_reason(&workspace).or_fail("stale reason");

    assert!(reason.contains(&workspace_path.display().to_string()));
}

#[test]
fn test_stale_retry_reason_allows_existing_workspace_path() {
    let temp_dir = TempDir::new().or_fail("create temp dir");
    let workspace = WorkspaceInfo {
        path: temp_dir.path().to_path_buf(),
        change_id: "alpha".to_string(),
        workspace_name: "ws-alpha".to_string(),
        last_modified: std::time::SystemTime::now(),
    };

    assert!(ParallelExecutor::stale_retry_reason(&workspace).is_none());
}

#[tokio::test]
async fn test_missing_workspace_retry_clears_resolve_wait_in_reducer() {
    use std::sync::Arc;
    use tokio::sync::mpsc;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;

    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(tx),
    );
    executor.workspace_manager = Box::new(TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0))));

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "manual retry requested".to_string(),
            auto_resumable: false,
        });
        guard.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor.sync_resolve_wait_from_shared_state().await;

    executor.retry_deferred_merges().await;
    executor.sync_resolve_wait_from_shared_state().await;

    assert!(
        executor.resolve_wait_changes.is_empty(),
        "missing archived workspace must not leave executor-local ResolveWait pending"
    );
    assert!(
        shared.read().await.resolve_wait_change_ids().is_empty(),
        "missing archived workspace must clear reducer-owned ResolveWait"
    );
    assert_ne!(
        shared.read().await.display_status("alpha"),
        "resolve pending",
        "TUI display must not remain indefinitely resolve pending after missing workspace handling"
    );

    let mut saw_retry_dispatch = false;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::Log(log) = event {
            if log
                .message
                .contains("ResolveWait retry dispatch started for 'alpha'")
            {
                saw_retry_dispatch = true;
            }
        }
    }
    assert!(
        saw_retry_dispatch,
        "missing workspace path must still prove retry evaluation ran"
    );
}

#[tokio::test]
async fn test_stale_workspace_retry_clears_resolve_wait_in_reducer() {
    use std::sync::Arc;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    let stale_path = workspace_dir.path().join("deleted-workspace");
    init_git_repo(repo_dir.path()).await;

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("alpha", stale_path),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "manual retry requested".to_string(),
            auto_resumable: false,
        });
        guard.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor.sync_resolve_wait_from_shared_state().await;

    executor.retry_deferred_merges().await;
    executor.sync_resolve_wait_from_shared_state().await;

    assert!(executor.resolve_wait_changes.is_empty());
    assert!(shared.read().await.resolve_wait_change_ids().is_empty());
    assert_ne!(
        shared.read().await.display_status("alpha"),
        "resolve pending"
    );
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_deferred_merge_success_clears_shared_resolve_wait_and_runs_hook_once() {
    use crate::hooks::{HookConfig, HookConfigValue, HookRunner, HooksConfig};
    use crate::vcs::GitWorkspaceManager;
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let workspace_base = repo_root.join("worktrees");
    init_git_repo(repo_root).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.to_string_lossy().to_string()),
        ..Default::default()
    });
    let mut manager = GitWorkspaceManager::new(
        workspace_base.clone(),
        repo_root.to_path_buf(),
        1,
        config.clone(),
    );
    let workspace = manager
        .create_workspace("alpha", None)
        .await
        .or_fail("create workspace");
    let original_change_dir = workspace.path.join("openspec/changes/alpha");
    std::fs::create_dir_all(&original_change_dir).or_fail("create original change dir");
    std::fs::write(original_change_dir.join("proposal.md"), "# alpha draft\n")
        .or_fail("write original change file");
    std::fs::create_dir_all(workspace.path.join("openspec/changes/archive/alpha"))
        .or_fail("create archive dir");
    std::fs::write(
        workspace
            .path
            .join("openspec/changes/archive/alpha/proposal.md"),
        "# alpha\n",
    )
    .or_fail("write archive file");
    std::fs::remove_dir_all(&original_change_dir).or_fail("remove original change dir");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("git add workspace archive");
    Command::new("git")
        .args(["commit", "-m", "Archive alpha"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("git commit workspace archive");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("git add worktree gitfile");
    Command::new("git")
        .args(["commit", "-m", "Track alpha worktree"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("git commit worktree gitfile");

    let hook_marker = repo_root.join("hook-count.txt");
    let hook_command = format!("printf 'alpha\\n' >> {}", hook_marker.to_string_lossy());
    let hooks = HookRunner::new(
        HooksConfig {
            on_merged: Some(HookConfigValue::Full(HookConfig {
                command: hook_command,
                continue_on_failure: false,
                timeout: 5,
                git_commit_no_verify: false,
                max_retries: 0,
                retry_delay_secs: 1,
            })),
            ..Default::default()
        },
        repo_root,
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        0,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "Resolve in progress for another change".to_string(),
            auto_resumable: true,
        });
    }

    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(manager);
    executor.set_shared_orchestrator_state(shared.clone());
    executor.set_hooks(hooks);

    match (MergeAttempt::Merged {
        revision: "merge-rev-alpha".to_string(),
    }) {
        MergeAttempt::Merged { revision } => {
            executor
                .clear_resolve_wait_intent_for_outcome("alpha")
                .await;
            if let Some(ref hooks) = executor.hooks {
                let hook_ctx = crate::hooks::HookContext::new(0, 0, 0, false)
                    .with_change("alpha", 0, 0)
                    .with_apply_count(0)
                    .with_parallel_context(&workspace.path.to_string_lossy(), None);
                hooks
                    .run_hook(crate::hooks::HookType::OnMerged, &hook_ctx)
                    .await
                    .or_fail("on_merged hook should succeed");
            }
            executor
                .mark_deferred_merge_completed_in_shared_state("alpha", &revision)
                .await;
            crate::parallel::events::send_event(
                &executor.event_tx,
                ParallelEvent::MergeCompleted {
                    change_id: "alpha".to_string(),
                    revision,
                },
            )
            .await;
        }
        MergeAttempt::Deferred(deferred) => {
            panic!("expected merge success, got deferred: {}", deferred.reason);
        }
    }
    executor.sync_resolve_wait_from_shared_state().await;

    assert!(executor.resolve_wait_changes.is_empty());
    assert!(!executor.has_resolve_wait().await);
    assert!(shared.read().await.resolve_wait_change_ids().is_empty());

    executor.trigger_resolve_wait_retry_dispatch();
    executor.maybe_dispatch_resolve_wait_retry().await;

    let hook_output = std::fs::read_to_string(&hook_marker).or_fail("read hook marker");
    assert_eq!(
        hook_output.lines().filter(|line| *line == "alpha").count(),
        1,
        "on_merged hook must run exactly once for deferred retry success"
    );

    let mut merge_completed = 0usize;
    let mut resolve_started = 0usize;
    while let Ok(event) = rx.try_recv() {
        match event {
            crate::events::ExecutionEvent::MergeCompleted { change_id, .. }
                if change_id == "alpha" =>
            {
                merge_completed += 1;
            }
            crate::events::ExecutionEvent::ResolveStarted { change_id, .. }
                if change_id == "alpha" =>
            {
                resolve_started += 1;
            }
            _ => {}
        }
    }
    assert_eq!(merge_completed, 1);
    assert_eq!(resolve_started, 0);
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_stale_already_merged_resolve_wait_skips_merge_and_hook() {
    use crate::hooks::{HookConfig, HookConfigValue, HookRunner, HooksConfig};
    use crate::vcs::GitWorkspaceManager;
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();
    let workspace_base = repo_root.join("worktrees");
    init_git_repo(repo_root).await;

    std::fs::create_dir_all(repo_root.join("openspec/changes/archive/alpha"))
        .or_fail("create archive dir");
    std::fs::write(
        repo_root.join("openspec/changes/archive/alpha/proposal.md"),
        "# alpha\n",
    )
    .or_fail("write archive file");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("git add base archive");
    Command::new("git")
        .args(["commit", "-m", "Archive alpha on base"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("git commit base archive");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.to_string_lossy().to_string()),
        ..Default::default()
    });
    let manager = GitWorkspaceManager::new(
        workspace_base.clone(),
        repo_root.to_path_buf(),
        1,
        config.clone(),
    );

    let hook_marker = repo_root.join("stale-hook-count.txt");
    let hook_command = format!("printf 'alpha\\n' >> {}", hook_marker.to_string_lossy());
    let hooks = HookRunner::new(
        HooksConfig {
            on_merged: Some(HookConfigValue::Full(HookConfig {
                command: hook_command,
                continue_on_failure: false,
                timeout: 5,
                git_commit_no_verify: false,
                max_retries: 0,
                retry_delay_secs: 1,
            })),
            ..Default::default()
        },
        repo_root,
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["alpha".to_string()],
        0,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "Resolve in progress for another change".to_string(),
            auto_resumable: true,
        });
    }

    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(manager);
    executor.set_shared_orchestrator_state(shared.clone());
    executor.set_hooks(hooks);

    executor.retry_deferred_merges().await;
    executor.sync_resolve_wait_from_shared_state().await;

    assert!(executor.resolve_wait_changes.is_empty());
    assert!(!executor.has_resolve_wait().await);
    assert!(shared.read().await.resolve_wait_change_ids().is_empty());
    assert!(
        !hook_marker.exists(),
        "stale already-merged retry must not run on_merged hook"
    );

    while let Ok(event) = rx.try_recv() {
        match event {
            crate::events::ExecutionEvent::MergeStarted { .. }
            | crate::events::ExecutionEvent::ResolveStarted { .. }
            | crate::events::ExecutionEvent::MergeCompleted { .. } => {
                panic!("stale already-merged retry must not emit merge/resolve event: {event:?}");
            }
            _ => {}
        }
    }
}

#[tokio::test]
async fn test_resumed_archived_dispatch_clears_reducer_queue_intent() {
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::mpsc;
    use tokio::task::JoinSet;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    init_git_repo(repo_dir.path()).await;

    let change_id = "improve-warning-popup-readability";
    let change_dir = repo_dir.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("create active change dir");
    std::fs::write(
        change_dir.join("proposal.md"),
        "# Improve warning popup readability\n",
    )
    .or_fail("write active proposal");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write active tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git add active change");
    Command::new("git")
        .args(["commit", "-m", "Add active change"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git commit active change");
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let workspace_path = workspace_base.path().join(format!("cflx-{change_id}"));
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            change_id,
            workspace_path.to_string_lossy().as_ref(),
            "HEAD",
        ])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("create archived worktree");
    std::fs::remove_dir_all(workspace_path.join("openspec/changes").join(change_id))
        .or_fail("remove active change dir in worktree");
    let archive_dir = workspace_path
        .join("openspec/changes/archive/2026-05-08-improve-warning-popup-readability");
    std::fs::create_dir_all(&archive_dir).or_fail("create archive dir in worktree");
    std::fs::write(
        archive_dir.join("proposal.md"),
        "# Improve warning popup readability\n",
    )
    .or_fail("write archived proposal");
    std::fs::write(
        archive_dir.join("tasks.md"),
        "## Implementation Tasks\n- [x] done\n",
    )
    .or_fail("write archived tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace_path)
        .output()
        .await
        .or_fail("git add archive in worktree");
    Command::new("git")
        .args(["commit", "-m", "Archive improve-warning-popup-readability"])
        .current_dir(&workspace_path)
        .output()
        .await
        .or_fail("git commit archive in worktree");

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
            change_id.to_string(),
        ));
    }

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some("sh -c 'echo unexpected-apply >&2; exit 42'".to_string()),
        acceptance_command: Some("sh -c 'echo unexpected-acceptance >&2; exit 43'".to_string()),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(128);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.set_shared_orchestrator_state(shared.clone());
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch archived worktree");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    assert!(result.error.is_none());
    assert!(result.final_revision.is_some());
    assert!(
        shared.read().await.queued_change_ids().is_empty(),
        "resumed Archived dispatch must clear reducer queued intent before scheduler reconciliation can re-add it"
    );

    let mut saw_apply_started = false;
    let mut saw_archived = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                saw_apply_started = true;
            }
            ExecutionEvent::ChangeArchived(id) if id == change_id => {
                saw_archived = true;
            }
            _ => {}
        }
    }
    assert!(!saw_apply_started);
    assert!(saw_archived);
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn push_post_archive_success_cleans_workspace_and_does_not_merge_base() {
    use crate::parallel::WorkspaceResult;
    use crate::vcs::GitWorkspaceManager;

    let repo = TempDir::new().or_fail("create repo tempdir");
    let remote = TempDir::new().or_fail("create remote tempdir");
    let workspace_base = repo.path().join("worktrees");
    init_git_repo(repo.path()).await;
    Command::new("git")
        .args(["init", "--bare"])
        .current_dir(remote.path())
        .output()
        .await
        .or_fail("init bare remote");
    Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            remote.path().to_str().or_fail("remote path utf8"),
        ])
        .current_dir(repo.path())
        .output()
        .await
        .or_fail("add origin remote");

    let base_head = get_current_commit(repo.path())
        .await
        .or_fail("read base head before push");
    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.to_string_lossy().to_string()),
        ..Default::default()
    });
    let mut manager = GitWorkspaceManager::new(
        workspace_base.clone(),
        repo.path().to_path_buf(),
        1,
        config.clone(),
    );
    let workspace = manager
        .create_workspace("alpha", None)
        .await
        .or_fail("create alpha workspace");
    std::fs::create_dir_all(workspace.path.join("openspec/changes/archive/alpha"))
        .or_fail("create archive dir");
    std::fs::write(
        workspace
            .path
            .join("openspec/changes/archive/alpha/proposal.md"),
        "# alpha\n",
    )
    .or_fail("write archive marker");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("git add archive in workspace");
    Command::new("git")
        .args(["commit", "-m", "Archive alpha"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("git commit archive in workspace");
    let workspace_head = get_current_commit(&workspace.path)
        .await
        .or_fail("read workspace head");

    let (tx, mut rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(repo.path().to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(manager);
    executor.post_archive_action = PostArchiveAction::PushToRemote {
        remote: "origin".to_string(),
    };

    let outcome = executor
        .handle_merge_and_cleanup(WorkspaceResult {
            change_id: "alpha".to_string(),
            workspace_name: workspace.name.clone(),
            final_revision: Some(workspace_head.clone()),
            error: None,
            rejected: None,
        })
        .await;
    assert_eq!(outcome, MergeTaskOutcome::Merged);
    assert_eq!(
        get_current_commit(repo.path())
            .await
            .or_fail("read base head after push"),
        base_head,
        "push mode must not merge into base"
    );
    assert!(
        !workspace.path.exists(),
        "successful push should cleanup worktree"
    );
    let remote_head =
        crate::vcs::git::commands::run_git(&["rev-parse", "refs/heads/alpha"], remote.path())
            .await
            .or_fail("read pushed remote branch");
    assert_eq!(remote_head, workspace_head);

    let mut saw_push_completed = false;
    let mut saw_merge_completed = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::PushCompleted { change_id, .. } if change_id == "alpha" => {
                saw_push_completed = true;
            }
            ExecutionEvent::MergeCompleted { change_id, .. } if change_id == "alpha" => {
                saw_merge_completed = true;
            }
            _ => {}
        }
    }
    assert!(saw_push_completed);
    assert!(!saw_merge_completed);
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn push_post_archive_failure_preserves_workspace_and_skips_on_merged_hook() {
    use crate::hooks::{HookConfig, HookConfigValue, HookRunner, HooksConfig};
    use crate::parallel::WorkspaceResult;
    use crate::vcs::GitWorkspaceManager;

    let repo = TempDir::new().or_fail("create repo tempdir");
    let workspace_base = repo.path().join("worktrees");
    init_git_repo(repo.path()).await;
    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.to_string_lossy().to_string()),
        ..Default::default()
    });
    let mut manager = GitWorkspaceManager::new(
        workspace_base.clone(),
        repo.path().to_path_buf(),
        1,
        config.clone(),
    );
    let workspace = manager
        .create_workspace("alpha", None)
        .await
        .or_fail("create alpha workspace");
    std::fs::create_dir_all(workspace.path.join("openspec/changes/archive/alpha"))
        .or_fail("create archive dir");
    std::fs::write(
        workspace
            .path
            .join("openspec/changes/archive/alpha/proposal.md"),
        "# alpha\n",
    )
    .or_fail("write archive marker");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("git add archive in workspace");
    Command::new("git")
        .args(["commit", "-m", "Archive alpha"])
        .current_dir(&workspace.path)
        .output()
        .await
        .or_fail("git commit archive in workspace");
    let workspace_head = get_current_commit(&workspace.path)
        .await
        .or_fail("read workspace head");
    let hook_marker = repo.path().join("on-merged-ran.txt");
    let hooks = HookRunner::new(
        HooksConfig {
            on_merged: Some(HookConfigValue::Full(HookConfig {
                command: format!("touch {}", hook_marker.to_string_lossy()),
                continue_on_failure: false,
                timeout: 5,
                git_commit_no_verify: false,
                max_retries: 0,
                retry_delay_secs: 1,
            })),
            ..Default::default()
        },
        repo.path(),
    );
    let (tx, mut rx) = mpsc::channel(16);
    let mut executor = ParallelExecutor::new(repo.path().to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(manager);
    executor.set_hooks(hooks);
    executor.post_archive_action = PostArchiveAction::PushToRemote {
        remote: "missing-remote".to_string(),
    };

    let outcome = executor
        .handle_merge_and_cleanup(WorkspaceResult {
            change_id: "alpha".to_string(),
            workspace_name: workspace.name.clone(),
            final_revision: Some(workspace_head),
            error: None,
            rejected: None,
        })
        .await;
    // `PushFailed` already owns this change transition, so the shared boundary
    // reports it as already reported rather than promoting it to run-fatal.
    match &outcome {
        MergeTaskOutcome::RecoverableAlreadyReported {
            change_id,
            kind,
            detail,
        } => {
            assert_eq!(change_id, "alpha");
            assert_eq!(*kind, crate::parallel::AlreadyReportedFailureKind::Push);
            assert!(detail.contains("Failed to push archived alpha"), "{detail}");
        }
        other => panic!("a reported push failure must not become run-fatal, got {other:?}"),
    }
    assert_eq!(
        outcome.disposition(),
        MergeResultDisposition::ContinueWithErrors
    );
    assert!(
        workspace.path.exists(),
        "failed push must preserve worktree for inspection/retry"
    );
    assert!(
        !hook_marker.exists(),
        "push mode must not execute on_merged hooks"
    );

    let mut saw_push_failed = false;
    let mut saw_hook_failed = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::PushFailed { change_id, .. } if change_id == "alpha" => {
                saw_push_failed = true;
            }
            ExecutionEvent::HookFailed { change_id, .. } if change_id == "alpha" => {
                saw_hook_failed = true;
            }
            _ => {}
        }
    }
    assert!(saw_push_failed);
    assert!(!saw_hook_failed);
}

#[tokio::test]
async fn test_reject_wait_lane_clear_promotion_starts_rejection_review() {
    use crate::events::ExecutionEvent;
    use std::sync::Arc;
    use tempfile::TempDir;

    use tokio::sync::mpsc;

    let workspace_dir = TempDir::new().or_fail("unexpected error");
    let change_id = "change-rejected";
    let rejected_dir = workspace_dir
        .path()
        .join("openspec")
        .join("changes")
        .join(change_id);
    std::fs::create_dir_all(&rejected_dir).or_fail("unexpected error");
    std::fs::write(
        rejected_dir.join("REJECTED.md"),
        "# REJECTED\n\n- change_id: change-rejected\n- reason: regression\n",
    )
    .or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo REJECTION_REVIEW: BLOCK'".to_string()),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_strict_process_cleanup: Some(false),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(PathBuf::from("/tmp/test-repo"), config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(change_id, workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["lane-owner".to_string(), change_id.to_string()],
        2,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "lane-owner".to_string(),
            workspace_name: "lane-owner".to_string(),
            status: WorkspaceStatus::Resolving,
        });
        guard.mark_reject_wait(change_id);
        assert_eq!(guard.display_status(change_id), "reject pending");
        guard.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "lane-owner".to_string(),
            worktree_change_ids: None,
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    executor.retry_deferred_base_lane_waiters().await;

    let mut saw_rejecting_status = false;
    let mut saw_review_completed = false;
    let mut emitted = Vec::new();
    while let Ok(event) = rx.try_recv() {
        match &event {
            ExecutionEvent::WorkspaceStatusUpdated {
                change_id: id,
                status: WorkspaceStatus::Rejecting,
                ..
            } if id == change_id => saw_rejecting_status = true,
            ExecutionEvent::RejectionReviewCompleted { change_id: id, .. }
            | ExecutionEvent::RejectionReviewFailed { change_id: id, .. }
                if id == change_id =>
            {
                saw_review_completed = true;
            }
            _ => {}
        }
        emitted.push(event);
    }
    // A rejection-review *failure* is a mark-revoking transition, so the producer
    // no longer pre-applies it: only the authoritative dispatcher may, because
    // only there is the reducer edge visible. Stand in for that dispatcher here.
    {
        let mut guard = shared.write().await;
        for event in &emitted {
            if matches!(event, ExecutionEvent::RejectionReviewFailed { .. }) {
                guard.apply_execution_event(event);
            }
        }
    }

    assert!(
        saw_rejecting_status,
        "lane-clear promotion must emit active rejecting status before running review"
    );
    assert!(
        saw_review_completed,
        "lane-clear promotion must execute the deferred rejection review"
    );
    let guard = shared.read().await;
    assert!(guard.reject_wait_change_ids().is_empty());
    let final_status = guard.display_status(change_id);
    assert!(
        matches!(final_status, "stalled" | "error"),
        "the deferred review attempt must leave reject pending after execution"
    );
}

#[tokio::test]
async fn test_reject_wait_lane_clear_promotes_only_one_waiter() {
    use crate::events::ExecutionEvent;
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    let first_workspace = TempDir::new().or_fail("unexpected error");
    let second_workspace = TempDir::new().or_fail("unexpected error");
    let first_id = "change-rejected-a";
    let second_id = "change-rejected-b";
    for (change_id, workspace) in [
        (first_id, first_workspace.path()),
        (second_id, second_workspace.path()),
    ] {
        let rejected_dir = workspace.join("openspec").join("changes").join(change_id);
        std::fs::create_dir_all(&rejected_dir).or_fail("unexpected error");
        std::fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED\n")
            .or_fail("unexpected error");
    }

    let config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo REJECTION_REVIEW: BLOCK'".to_string()),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_strict_process_cleanup: Some(false),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(PathBuf::from("/tmp/test-repo"), config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(first_id, first_workspace.path().to_path_buf())
            .with_existing_workspace(second_id, second_workspace.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            "lane-owner".to_string(),
            first_id.to_string(),
            second_id.to_string(),
        ],
        2,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "lane-owner".to_string(),
            workspace_name: "lane-owner".to_string(),
            status: WorkspaceStatus::Resolving,
        });
        guard.mark_reject_wait(first_id);
        guard.mark_reject_wait(second_id);
        guard.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "lane-owner".to_string(),
            worktree_change_ids: None,
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    executor.retry_deferred_base_lane_waiters().await;

    let mut rejecting_updates = Vec::new();
    let mut emitted = Vec::new();
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::WorkspaceStatusUpdated {
            change_id,
            status: WorkspaceStatus::Rejecting,
            ..
        } = &event
        {
            rejecting_updates.push(change_id.clone());
        }
        emitted.push(event);
    }
    // The authoritative dispatcher owns the `RejectionReviewFailed` transition;
    // the producer must not pre-apply it, or the mark-revoking edge would be
    // invisible where marks are reconciled.
    {
        let mut guard = shared.write().await;
        for event in &emitted {
            if matches!(event, ExecutionEvent::RejectionReviewFailed { .. }) {
                guard.apply_execution_event(event);
            }
        }
    }

    assert_eq!(rejecting_updates, vec![first_id.to_string()]);
    let guard = shared.read().await;
    let first_status = guard.display_status(first_id);
    assert!(
        matches!(first_status, "stalled" | "error"),
        "the promoted first waiter must leave reject pending after its review attempt"
    );
    assert_eq!(guard.display_status(second_id), "reject pending");
    assert_eq!(guard.reject_wait_change_ids(), vec![second_id.to_string()]);
}

/// A deferred CONFIRM verdict whose rejection flow fails is a change-local
/// failure already owned by `RejectionReviewFailed`; it must not cross the
/// shared base-lane boundary as a completed merge.
#[tokio::test]
async fn deferred_confirm_rejection_flow_failure_is_already_reported_not_merged() {
    use crate::parallel::{AlreadyReportedFailureKind, MergeResult, MergeResultOrigin};

    let workspace_dir = TempDir::new().or_fail("create rejecting workspace");
    let change_id = "reject-confirm-flow-failure";
    let rejected_dir = workspace_dir
        .path()
        .join("openspec")
        .join("changes")
        .join(change_id);
    std::fs::create_dir_all(&rejected_dir).or_fail("create change directory");
    std::fs::write(
        rejected_dir.join("REJECTED.md"),
        "# REJECTED\n\n- change_id: reject-confirm-flow-failure\n- reason: unrecoverable blocker\n",
    )
    .or_fail("write REJECTED.md");

    // `execute_rejection_flow` checks out the base branch in this repo root, so
    // a missing repository fails the flow deterministically *after* the CONFIRM
    // verdict has already been produced.
    let missing_repo_root = workspace_dir.path().join("missing-repo-root");

    let config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo REJECTION_REVIEW: CONFIRM'".to_string()),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_strict_process_cleanup: Some(false),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(missing_repo_root, config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(change_id, workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["lane-owner".to_string(), change_id.to_string()],
        2,
    )));
    {
        let mut guard = shared.write().await;
        // The change only enters RejectWait while another change holds the
        // post-archive base-mutating lane; releasing it promotes this waiter.
        guard.apply_execution_event(&ExecutionEvent::ChangeArchived("lane-owner".to_string()));
        guard.mark_reject_wait(change_id);
        guard.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "lane-owner".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some((change_id.to_string(), WaitState::RejectWait))
        );
        assert!(guard.is_base_mutating_lane_occupied());
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor.reject_wait_changes.insert(change_id.to_string());

    let outcome = executor
        .retry_deferred_rejection_review_for(change_id.to_string())
        .await;

    match &outcome {
        MergeTaskOutcome::RecoverableAlreadyReported {
            change_id: scoped_id,
            kind,
            ..
        } => {
            assert_eq!(scoped_id, change_id);
            assert_eq!(*kind, AlreadyReportedFailureKind::RejectionReview);
        }
        other => panic!(
            "a failed CONFIRM rejection flow must not report a completed merge, got {other:?}"
        ),
    }
    assert_eq!(
        outcome.disposition(),
        MergeResultDisposition::ContinueWithErrors
    );

    let mut rejection_review_failures = 0;
    let mut saw_rejected_or_completed = false;
    let mut producer_errors = Vec::new();
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::RejectionReviewFailed { change_id: id, .. } if id == change_id => {
                rejection_review_failures += 1;
            }
            ExecutionEvent::RejectionReviewCompleted { change_id: id, .. }
            | ExecutionEvent::ChangeRejected { change_id: id, .. }
            | ExecutionEvent::ChangeDequeued { change_id: id } => {
                if id == change_id {
                    saw_rejected_or_completed = true;
                }
            }
            ExecutionEvent::Error { message } => producer_errors.push(message),
            _ => {}
        }
    }
    assert_eq!(
        rejection_review_failures, 1,
        "the rejection-review owner must report the failure exactly once"
    );
    assert!(
        !saw_rejected_or_completed,
        "a failed rejection flow must not synthesize rejection success events"
    );
    assert!(
        producer_errors.is_empty(),
        "the change-scoped owner must not also emit a global Error: {producer_errors:?}"
    );

    // The scheduler boundary continues the run and stays free of a duplicate
    // global Error.
    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);
    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: change_id.to_string(),
                workspace_name: format!("ws-{change_id}"),
                origin: MergeResultOrigin::RejectWaitRetry,
                outcome,
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(disposition, MergeResultDisposition::ContinueWithErrors);
    assert!(
        executor.run_fatal_abort.is_none(),
        "an already-reported rejection failure must not abort the run"
    );
    assert!(executor.had_change_failures());
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::Error { message } = event {
            panic!("the queue wrapper must not duplicate the reported failure: {message}");
        }
    }
    {
        let guard = shared.read().await;
        assert!(
            !guard.is_base_mutating_lane_occupied(),
            "the borrowed base-mutating lane must be released regardless of severity"
        );
        assert!(guard.global_invariants_hold());
    }
    assert!(
        workspace_dir.path().join("openspec").exists(),
        "workspace evidence must survive for explicit retry"
    );
}

/// Losing base identity during a deferred CONFIRM must fail closed: guessing a
/// branch name would commit REJECTED.md onto whatever branch carries it.
#[tokio::test]
async fn deferred_confirm_base_identity_failure_is_run_fatal_without_mutation() {
    use crate::parallel::{MergeResult, MergeResultOrigin};

    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;

    let workspace_dir = TempDir::new().or_fail("create rejecting workspace");
    let change_id = "reject-confirm-base-identity";
    let rejected_dir = workspace_dir
        .path()
        .join("openspec")
        .join("changes")
        .join(change_id);
    std::fs::create_dir_all(&rejected_dir).or_fail("create change directory");
    std::fs::write(
        rejected_dir.join("REJECTED.md"),
        "# REJECTED\n\n- change_id: reject-confirm-base-identity\n- reason: unrecoverable blocker\n",
    )
    .or_fail("write REJECTED.md");

    let config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo REJECTION_REVIEW: CONFIRM'".to_string()),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_strict_process_cleanup: Some(false),
        ..Default::default()
    });
    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace(change_id, workspace_dir.path().to_path_buf())
            .with_failing_original_branch(),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["lane-owner".to_string(), change_id.to_string()],
        2,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::ChangeArchived("lane-owner".to_string()));
        guard.mark_reject_wait(change_id);
        guard.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "lane-owner".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(
            guard.promote_next_base_mutating_lane_waiter(),
            Some((change_id.to_string(), WaitState::RejectWait))
        );
    }
    executor.set_shared_orchestrator_state(shared.clone());
    executor.reject_wait_changes.insert(change_id.to_string());

    let outcome = executor
        .retry_deferred_rejection_review_for(change_id.to_string())
        .await;

    match &outcome {
        MergeTaskOutcome::RunFatal { detail } => {
            assert!(
                detail.contains(change_id),
                "run-fatal detail must name the change it aborted on: {detail}"
            );
        }
        other => panic!("lost base identity must fail closed as run-fatal, got {other:?}"),
    }
    assert_eq!(outcome.disposition(), MergeResultDisposition::AbortRun);

    assert!(
        !repo_dir
            .path()
            .join("openspec")
            .join("changes")
            .join(change_id)
            .join("REJECTED.md")
            .exists(),
        "the rejection flow must not run against a guessed base branch"
    );

    let mut producer_errors = Vec::new();
    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::RejectionReviewCompleted { change_id: id, .. }
            | ExecutionEvent::RejectionReviewFailed { change_id: id, .. }
            | ExecutionEvent::ChangeRejected { change_id: id, .. }
            | ExecutionEvent::ChangeDequeued { change_id: id } => {
                if id == change_id {
                    panic!("aborting on lost base identity must not mutate rejection state");
                }
            }
            ExecutionEvent::Error { message } => producer_errors.push(message),
            _ => {}
        }
    }
    assert!(
        producer_errors.is_empty(),
        "the global Error owner is the queue boundary, not the producer: {producer_errors:?}"
    );

    let (merge_result_tx, _merge_result_rx) = mpsc::channel(4);
    executor.pending_merge_count.fetch_add(1, Ordering::Relaxed);
    let disposition = executor
        .handle_merge_result_with_tx(
            MergeResult {
                change_id: change_id.to_string(),
                workspace_name: format!("ws-{change_id}"),
                origin: MergeResultOrigin::RejectWaitRetry,
                outcome,
            },
            &merge_result_tx,
        )
        .await;

    assert_eq!(disposition, MergeResultDisposition::AbortRun);
    assert!(executor.run_fatal_abort.is_some());
    let global_errors = {
        let mut collected = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let ExecutionEvent::Error { message } = event {
                collected.push(message);
            }
        }
        collected
    };
    assert_eq!(
        global_errors.len(),
        1,
        "an aborting run emits exactly one global Error: {global_errors:?}"
    );
    assert!(shared.read().await.global_invariants_hold());
}

#[tokio::test]
async fn test_scheduler_does_not_busy_retry_unchanged_resolve_wait() {
    use std::sync::Arc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_observation(
            "change-a",
            crate::orchestration::state::WorkspaceObservation::WorkspaceArchived,
        );
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
    }
    executor.set_shared_orchestrator_state(shared);

    executor.sync_resolve_wait_from_shared_state().await;
    executor.trigger_resolve_wait_retry_dispatch();
    executor.maybe_dispatch_resolve_wait_retry().await;

    let dispatched_snapshot = executor.resolve_wait_changes.clone();
    assert_eq!(
        executor.last_dispatched_resolve_wait_changes,
        dispatched_snapshot
    );
    assert!(!executor.resolve_wait_retry_triggered);
    assert!(
        !executor.should_dispatch_resolve_wait_retry(),
        "unchanged resolve-wait intent must not be retried again without a new trigger"
    );
}

#[tokio::test]
async fn test_dirty_to_clean_resolve_wait_wakes_retry_without_new_trigger() {
    use std::sync::Arc;
    use tempfile::TempDir;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    init_git_repo(repo_dir.path()).await;
    std::fs::write(repo_dir.path().join("dirty.txt"), "dirty").or_fail("dirty base");

    let config = create_test_config();
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, None);
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("change-a", workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["change-a".to_string()],
        3,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "change-a".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        guard.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
    }
    executor.set_shared_orchestrator_state(shared);
    executor.sync_resolve_wait_from_shared_state().await;
    executor.last_dispatched_resolve_wait_changes = executor.resolve_wait_changes.clone();

    executor.maybe_dispatch_resolve_wait_retry().await;
    assert!(
        !executor.should_dispatch_resolve_wait_retry(),
        "dirty observation should be deduped after the first scheduler evaluation"
    );

    std::fs::remove_file(repo_dir.path().join("dirty.txt")).or_fail("clean base");

    executor.maybe_dispatch_resolve_wait_retry().await;

    assert_eq!(
        executor.last_dispatched_resolve_wait_changes, executor.resolve_wait_changes,
        "dirty-to-clean transition should wake scheduler-owned ResolveWait retry without another M keypress"
    );
    assert!(!executor.resolve_wait_retry_triggered);
}

#[tokio::test]
async fn test_resolve_wait_helper_tracks_state() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    assert!(!executor.has_resolve_wait().await);

    executor
        .resolve_wait_changes
        .insert("test-change".to_string());

    assert!(executor.has_resolve_wait().await);

    executor.resolve_wait_changes.clear();

    assert!(!executor.has_resolve_wait().await);
}

#[tokio::test]
async fn test_auto_resumable_deferral_uses_resolve_pending_not_manual_merge_wait() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    executor.resolve_wait_changes.insert("change-a".to_string());
    executor.merge_wait_changes.remove("change-a");

    assert!(executor.resolve_wait_changes.contains("change-a"));
    assert!(executor.merge_wait_changes.is_empty());
    assert!(executor.has_resolve_wait().await);
}

#[tokio::test]
async fn test_manual_deferral_uses_merge_wait_not_resolve_pending() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    executor.resolve_wait_changes.insert("change-a".to_string());
    executor.resolve_wait_changes.remove("change-a");
    executor.merge_wait_changes.insert("change-a".to_string());

    assert!(!executor.resolve_wait_changes.contains("change-a"));
    assert!(executor.merge_wait_changes.contains("change-a"));
    assert!(!executor.has_resolve_wait().await);
}

/// Test that changes in MergeWait state are correctly filtered during loop iteration.
/// This test validates the spec requirement:
/// "The loop continues processing runnable changes and MergeWait is not treated as a terminal completion reason."
#[tokio::test]
async fn test_merge_wait_does_not_block_runnable_changes() {
    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let mut executor = ParallelExecutor::new(repo_root, config, None);

    // MergeWait は scheduler break 条件に含まれないため、
    // ResolveWait が空なら completion 判定に影響しない。
    executor
        .merge_wait_changes
        .insert("merge-wait-only".to_string());
    assert!(executor.resolve_wait_changes.is_empty());
    assert!(!executor.has_resolve_wait().await);
}

/// Test concurrent re-analysis: verify that re-analysis reason is properly tracked
/// and logged during execution.
///
/// This test validates task 2.1 requirement:
/// - Initial analysis has reason "initial"
/// - Completion triggers have reason "completion"
/// - Queue notifications have reason "queue"
#[tokio::test]
async fn test_concurrent_reanalysis_queue_dispatch() {
    use crate::tui::queue::DynamicQueue;
    use std::sync::Arc;
    use tokio::sync::mpsc;

    let config = create_test_config();
    let repo_root = PathBuf::from("/tmp/test-repo");
    let (tx, _rx) = mpsc::channel(100);

    // Create executor with dynamic queue
    let queue = Arc::new(DynamicQueue::new());
    let mut executor = ParallelExecutor::new(repo_root.clone(), config.clone(), Some(tx));
    executor.set_dynamic_queue(queue.clone());

    // Add initial change to queue (will trigger queue notification)
    queue.push("test-change".to_string()).await;

    // Verify queue has one item
    assert_eq!(queue.len().await, 1);

    // Verify executor is set up correctly
    assert!(executor.dynamic_queue.is_some());

    // Test debounce logic
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(std::time::Instant::now());
    }

    // Immediate check: should NOT reanalyze (debounce active)
    assert!(!executor.should_reanalyze(false).await);

    // Simulate debounce period expiry without waiting 11 real seconds.
    {
        let mut last_change = executor.last_queue_change_at.lock().await;
        *last_change = Some(std::time::Instant::now() - std::time::Duration::from_secs(11));
    }

    // After simulated debounce expiry: should reanalyze
    assert!(executor.should_reanalyze(false).await);

    // Verify AnalysisStarted event would be emitted
    // (Full execution test would require mocking apply/archive commands)
}

/// Test that on_merged hook is executed when parallel merge succeeds
#[tokio::test]
async fn test_on_merged_hook_execution() {
    use crate::hooks::{HookConfig, HookRunner, HooksConfig};
    use tempfile::TempDir;

    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path().to_path_buf();

    // Create a marker file path to verify hook execution
    let marker_file = repo_root.join("hook_executed.marker");
    let marker_file_str = marker_file.to_string_lossy().to_string();

    // Set up hooks configuration with on_merged hook that creates a marker file
    let hook_command = if cfg!(target_os = "windows") {
        format!("cmd /C echo executed > {}", marker_file_str)
    } else {
        format!("touch {}", marker_file_str)
    };

    let hooks_config = HooksConfig {
        on_merged: Some(crate::hooks::HookConfigValue::Full(HookConfig {
            command: hook_command,
            continue_on_failure: true,
            timeout: 5,
            git_commit_no_verify: false,
            max_retries: 0,
            retry_delay_secs: 3,
        })),
        ..Default::default()
    };

    let hook_runner = HookRunner::new(hooks_config, ".");

    // Create a simple HookContext for testing
    let hook_context = crate::hooks::HookContext::new(1, 1, 0, false)
        .with_change("test-change", 5, 5)
        .with_parallel_context("/tmp/test-workspace", None);

    // Execute the hook
    let result = hook_runner
        .run_hook(crate::hooks::HookType::OnMerged, &hook_context)
        .await;
    assert!(result.is_ok(), "Hook execution should succeed");

    // Allow some time for file creation
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Verify the marker file was created
    assert!(
        marker_file.exists(),
        "Hook marker file should exist at {:?}",
        marker_file
    );
}

/// Test that attempt_merge defers when worktree is dirty
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_attempt_merge_deferred_when_resolve_active() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(10);
    let mut executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    // Simulate an already running manual resolve for another change.
    let manual_resolve_counter = Arc::new(AtomicUsize::new(1));
    executor.set_manual_resolve_counter(manual_resolve_counter.clone());

    let revisions = vec!["test-workspace".to_string()];
    let change_ids = vec!["test-change".to_string()];
    let archive_paths = vec![repo_root.to_path_buf()];

    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Deferred(deferred)) => {
            assert!(deferred.auto_resumable);
            assert!(
                deferred.reason.contains("Resolve in progress"),
                "Expected deferred reason to mention resolve in progress, got: {}",
                deferred.reason
            );
        }
        Ok(MergeAttempt::Merged { .. }) => {
            panic!("Merge should have been deferred while resolve is active");
        }
        Err(e) => {
            panic!("Unexpected error: {}", e);
        }
    }

    manual_resolve_counter.store(0, Ordering::SeqCst);
}

#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_deferred_when_worktree_dirty() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create archive directory to simulate that archive was successful (change moved to archive)
    let archive_dir = repo_root.join("openspec/changes/archive/2024-01-01-test-change");
    fs::create_dir_all(&archive_dir).or_fail("unexpected error");
    fs::write(archive_dir.join("spec.md"), "# Archived Test").or_fail("unexpected error");

    // Commit the archive
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Archive: test-change"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create a dirty file (uncommitted change)
    fs::write(repo_root.join("dirty.txt"), "dirty content").or_fail("unexpected error");

    // Create executor
    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    let revisions = vec!["test-workspace".to_string()];
    let change_ids = vec!["test-change".to_string()];
    let archive_paths = vec![repo_root.to_path_buf()];

    // Attempt merge should be deferred because worktree is dirty
    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Deferred(deferred)) => {
            assert!(!deferred.auto_resumable);
            assert!(
                deferred.reason.contains("incomplete") || deferred.reason.contains("dirty"),
                "Expected deferred reason to mention incomplete archive or dirty worktree, got: {}",
                deferred.reason
            );
        }
        Ok(MergeAttempt::Merged { .. }) => {
            panic!("Merge should have been deferred due to dirty worktree");
        }
        Err(e) => {
            panic!("Unexpected error: {}", e);
        }
    }
}

/// Test that attempt_merge defers when archive entry is missing
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_deferred_when_archive_entry_missing() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Note: No archive directory created - this simulates archive entry missing
    // And no openspec/changes/test-change directory (simulating change was removed but not archived)

    // Create executor
    let config = create_test_config();
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    let revisions = vec!["test-workspace".to_string()];
    let change_ids = vec!["test-change".to_string()];
    let archive_paths = vec![repo_root.to_path_buf()];

    // Attempt merge should be deferred because archive entry is missing
    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Deferred(deferred)) => {
            assert!(!deferred.auto_resumable);
            assert!(
                deferred.reason.contains("incomplete")
                    || deferred.reason.contains("archive")
                    || deferred.reason.contains("missing"),
                "Expected deferred reason to mention incomplete archive or missing entry, got: {}",
                deferred.reason
            );
        }
        Ok(MergeAttempt::Merged { .. }) => {
            panic!("Merge should have been deferred due to missing archive entry");
        }
        Err(e) => {
            panic!("Unexpected error: {}", e);
        }
    }
}

/// Test that attempt_merge proceeds when archive is complete
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_merge_proceeds_when_archive_complete() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create archive directory but NOT openspec/changes/test-change (proper archive)
    let archive_dir = repo_root.join("openspec/changes/archive/test-change");
    fs::create_dir_all(&archive_dir).or_fail("unexpected error");
    fs::write(archive_dir.join("spec.md"), "# Archived").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Archive: test-change"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create worktree for the change (outside the main repo to avoid dirty working tree)
    let workspace_base = TempDir::new().or_fail("unexpected error");
    let workspace_path = workspace_base.path().join("ws-test-change");

    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            "ws-test-change",
            workspace_path.to_str().or_fail("unexpected error"),
            "HEAD",
        ])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create executor
    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    let revisions = vec!["ws-test-change".to_string()];
    let change_ids = vec!["test-change".to_string()];

    // Attempt merge should succeed because change is properly archived
    let archive_paths = vec![workspace_path.clone()];
    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Merged { .. }) => {
            // Success - merge was allowed
        }
        Ok(MergeAttempt::Deferred(deferred)) => {
            panic!(
                "Merge should have succeeded when change is archived, got deferred: {}",
                deferred.reason
            );
        }
        Err(e) => {
            // This is also acceptable - merge may fail for other reasons (e.g., merge conflicts)
            // but it should not be deferred due to archive verification.
            println!("Merge failed with error (acceptable): {}", e);
        }
    }
}

/// Regression: detached HEAD must be reported as execution error, not MergeWait/deferred.
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn test_attempt_merge_errors_on_detached_head() {
    let _merge_lock_test_guard = merge_lock_test_mutex().lock().await;
    use std::fs;
    use tempfile::TempDir;
    use tokio::sync::mpsc;

    // Create temporary repository
    let temp_dir = TempDir::new().or_fail("unexpected error");
    let repo_root = temp_dir.path();

    // Initialize git repo
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create initial commit
    fs::write(repo_root.join("README.md"), "initial").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Initial"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create archive directory but NOT openspec/changes/test-change (proper archive)
    let archive_dir = repo_root.join("openspec/changes/archive/test-change");
    fs::create_dir_all(&archive_dir).or_fail("unexpected error");
    fs::write(archive_dir.join("spec.md"), "# Archived").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Archive: test-change"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Detach HEAD explicitly
    let detached_rev = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    let detached_rev = String::from_utf8_lossy(&detached_rev.stdout)
        .trim()
        .to_string();
    Command::new("git")
        .args(["checkout", detached_rev.as_str()])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create worktree for the change (outside the main repo to avoid dirty working tree)
    let workspace_base = TempDir::new().or_fail("unexpected error");
    let workspace_path = workspace_base.path().join("ws-test-change");

    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            "ws-test-change",
            workspace_path.to_str().or_fail("unexpected error"),
            "HEAD",
        ])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");

    // Create executor
    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });
    let (tx, _rx) = mpsc::channel(10);
    let executor = ParallelExecutor::new(repo_root.to_path_buf(), config, Some(tx));

    let revisions = vec!["ws-test-change".to_string()];
    let change_ids = vec!["test-change".to_string()];
    let archive_paths = vec![workspace_path.clone()];

    let result = executor
        .attempt_merge(&revisions, &change_ids, &archive_paths, None)
        .await;

    match result {
        Ok(MergeAttempt::Deferred(deferred)) => {
            panic!(
                "Detached HEAD must not become MergeDeferred: {}",
                deferred.reason
            );
        }
        Ok(MergeAttempt::Merged { revision }) => {
            panic!("Detached HEAD must not merge successfully: {}", revision);
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("Detached HEAD state detected"),
                "Expected detached HEAD error, got: {}",
                msg
            );
        }
    }
}

/// Regression: when an acceptance command emits a canonical standalone verdict
/// but the child process keeps stdout open (e.g. opencode + MCP children),
/// the executor MUST finalize the verdict via the grace period and terminate
/// the child instead of waiting for the inactivity-timeout retry.
///
/// The test shortens the grace period to 1 second using a task-local override
/// (so concurrent tests are not affected) and uses an acceptance command that
/// sleeps for 30 seconds after emitting `ACCEPTANCE: PASS`. The execution
/// must complete in well under the sleep duration and must return PASS.
#[tokio::test]
async fn test_acceptance_finalizes_on_standalone_verdict_without_inactivity_retry() {
    use std::time::{Duration, Instant};
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        // Emit canonical standalone PASS, then keep the process alive long
        // enough that the executor MUST cut it off via the grace period.
        acceptance_command: Some("sh -c 'echo ACCEPTANCE: PASS; sleep 30'".to_string()),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        // 5s inactivity timeout would otherwise also rescue this test, so
        // disable it to ensure we are exercising the verdict-grace path only.
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let started = Instant::now();
    let (result, _iteration) = crate::parallel::executor::scoped_verdict_grace_secs_for_test(
        1,
        execute_acceptance_in_workspace(
            "change-a",
            repo_root.path(),
            &mut agent,
            None,
            None,
            &ai_runner,
            &acceptance_config,
            &acceptance_tail_injected,
            &acceptance_history,
            Some("main"),
            None,
            crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
        ),
    )
    .await
    .or_fail("unexpected error");
    let elapsed = started.elapsed();

    assert!(
        matches!(result, crate::orchestration::AcceptanceResult::Pass),
        "expected acceptance PASS via verdict grace, got {:?}",
        result
    );
    assert!(
        elapsed < Duration::from_secs(15),
        "verdict-grace finalization should complete well under the 30s sleep, took {:?}",
        elapsed
    );

    let report_path = repo_root.path().join("ACCEPTANCE_REPORT.json");
    assert!(
        !report_path.exists(),
        "verdict-finalized PASS must record acceptance history without creating {}",
        report_path.display()
    );

    let history = acceptance_history.lock().await;
    let attempts = history
        .get("change-a")
        .expect("verdict-finalized PASS must be recorded in acceptance history");
    assert_eq!(attempts.len(), 1);
    assert!(attempts[0].passed);
    assert!(
        attempts[0]
            .stdout_tail
            .as_deref()
            .unwrap_or_default()
            .contains("ACCEPTANCE: PASS"),
        "acceptance history should retain PASS stdout tail, got {:?}",
        attempts[0].stdout_tail
    );
    assert!(
        attempts[0].commit_hash.is_some(),
        "acceptance history should retain final revision"
    );
}

/// Regression: malformed trailing-text verdicts (e.g. `ACCEPTANCE: PASSAll ...`)
/// MUST NOT be treated as canonical PASS by the parallel executor. The legacy
/// `starts_with` check accepted these and could lock in a bogus pass; the
/// strict canonical contract falls through to CONTINUE so the loop can retry.
#[tokio::test]
async fn test_acceptance_command_failure_does_not_create_acceptance_report() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(
            "sh -c 'echo command-failed-before-verdict; echo stderr-tail >&2; exit 42'".to_string(),
        ),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        "change-a",
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    let crate::orchestration::AcceptanceResult::CommandFailed { diagnostic, .. } = &result else {
        panic!("failing acceptance command should return CommandFailed, got {result:?}");
    };
    let report_path = repo_root.path().join("ACCEPTANCE_REPORT.json");
    assert!(
        !report_path.exists(),
        "command-failure acceptance must not create misleading {}",
        report_path.display()
    );

    // The transport evidence lives only in the bounded latest-only diagnosis.
    assert_eq!(diagnostic.exit_code, Some(42));
    assert!(
        diagnostic
            .stdout_tail
            .as_deref()
            .unwrap_or_default()
            .contains("command-failed-before-verdict"),
        "the command-recovery diagnosis must carry the stdout tail, got {:?}",
        diagnostic.stdout_tail
    );

    // A command that never completed produced no verdict, so canonical
    // Acceptance history — shared and agent-local — stays untouched. Otherwise
    // the failed output would be replayed to the next reviewer as previous
    // findings and would consume attempt numbering.
    assert!(
        acceptance_history.lock().await.get("change-a").is_none(),
        "command failures must not enter shared canonical Acceptance history"
    );
    assert!(
        agent.get_last_acceptance_attempt("change-a").is_none(),
        "command failures must not enter agent-local canonical Acceptance history"
    );
    assert_eq!(
        agent.next_acceptance_attempt_number("change-a"),
        1,
        "a command failure must not consume canonical attempt numbering"
    );
}

#[tokio::test]
async fn test_acceptance_cancels_while_waiting_for_silent_streaming_output() {
    use std::time::{Duration, Instant};

    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'sleep 30'".to_string()),
        ..Default::default()
    });
    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };
    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));
    let cancel = CancellationToken::new();
    let cancel_clone = cancel.clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(150)).await;
        cancel_clone.cancel();
    });

    let started = Instant::now();
    let (result, _iteration) = execute_acceptance_in_workspace(
        "change-a",
        repo_root.path(),
        &mut agent,
        None,
        Some(&cancel),
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("acceptance cancellation should return a result");

    assert!(
        matches!(result, crate::orchestration::AcceptanceResult::Cancelled),
        "silent acceptance command should cancel instead of waiting for output, got {:?}",
        result
    );
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "cancellation should not wait for the 30s child sleep"
    );
}

#[tokio::test]
async fn test_archive_cancels_while_waiting_for_silent_streaming_output() {
    use std::time::{Duration, Instant};

    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    let change_id = "change-a";
    let change_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] done\n",
    )
    .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Base"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        archive_command: Some("sh -c 'sleep 30'".to_string()),
        ..Default::default()
    });
    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };
    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    let archive_history = Arc::new(Mutex::new(crate::history::ArchiveHistory::new()));
    let apply_history = Arc::new(Mutex::new(crate::history::ApplyHistory::new()));
    let cancel = CancellationToken::new();
    let cancel_clone = cancel.clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(150)).await;
        cancel_clone.cancel();
    });

    let started = Instant::now();
    let result = execute_archive_in_workspace(
        change_id,
        repo_root.path(),
        config.get_archive_command().or_fail("unexpected error"),
        &config,
        None,
        VcsBackend::Git,
        None,
        None,
        Some(&cancel),
        &ai_runner,
        &archive_history,
        &apply_history,
        &shared_stagger_state,
    )
    .await;

    let err = result.expect_err("silent archive command should be cancelled");
    assert!(
        err.to_string().contains("Cancelled archive"),
        "expected archive cancellation error, got {err}"
    );
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "cancellation should not wait for the 30s child sleep"
    );
}

#[tokio::test]
async fn test_acceptance_trailing_text_pass_is_not_canonical() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(
            "sh -c 'echo ACCEPTANCE: PASSAll acceptance criteria verified'".to_string(),
        ),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        "change-a",
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    assert!(
        matches!(
            result,
            crate::orchestration::AcceptanceResult::MissingVerdict { .. }
        ),
        "trailing-text PASS must NOT satisfy canonical verdict; expected missing-verdict protocol failure, got {:?}",
        result
    );
    assert!(
        !matches!(result, crate::orchestration::AcceptanceResult::Continue),
        "a malformed verdict must never be classified as an intentional CONTINUE"
    );

    assert!(
        !repo_root.path().join("ACCEPTANCE_REPORT.json").exists(),
        "malformed trailing-text verdict must not produce a workspace-root acceptance report"
    );
}

/// Regression for `prevent-premature-acceptance-exit`: an acceptance agent
/// that starts a long-running check, reports it is monitoring/waiting for the
/// completion result, and exits without that result or a canonical verdict
/// must be classified as an explicit missing-verdict protocol failure — never
/// as an intentional `CONTINUE` — and must not consume the explicit-CONTINUE
/// retry counter.
#[tokio::test]
async fn test_acceptance_status_only_exit_is_missing_verdict_not_continue() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    // Simulate a premature acceptance exit: the agent narrates that it is
    // monitoring a long-running verification and exits without a completion
    // result or any canonical verdict.
    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(
            "sh -c 'echo Started long-running verification job; \
             echo Monitoring verification, will emit the verdict once the \
             completion notification arrives'"
                .to_string(),
        ),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, iteration) = execute_acceptance_in_workspace(
        "change-a",
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    match &result {
        crate::orchestration::AcceptanceResult::MissingVerdict { findings } => {
            assert!(
                findings
                    .iter()
                    .any(|finding| finding.contains("Monitoring verification")),
                "missing-verdict result must retain bounded output evidence, got {:?}",
                findings
            );
        }
        other => panic!(
            "status-only acceptance exit must be a missing-verdict protocol failure, got {:?}",
            other
        ),
    }
    assert!(
        !matches!(result, crate::orchestration::AcceptanceResult::Continue),
        "status-only exit must never be reported as an intentional CONTINUE"
    );
    assert_eq!(iteration, 1, "attempt must still be recorded");

    // The recorded attempt must carry the actionable missing-verdict
    // diagnostic instead of the CONTINUE history marker, so the explicit
    // CONTINUE retry counter is not consumed.
    let history_findings = acceptance_history
        .lock()
        .await
        .last_findings("change-a")
        .or_fail("missing-verdict attempt must be recorded in acceptance history");
    assert!(
        history_findings
            .first()
            .is_some_and(|first| first.contains("Missing acceptance verdict")),
        "attempt evidence must identify the missing verdict, got {:?}",
        history_findings
    );
    assert!(
        !history_findings
            .iter()
            .any(|finding| finding.contains("Investigation incomplete - continue later")),
        "missing-verdict attempt must not record the CONTINUE history marker"
    );
    assert_eq!(
        agent.count_consecutive_acceptance_continues("change-a"),
        0,
        "missing verdict must not consume the explicit-CONTINUE retry counter"
    );

    assert!(
        !repo_root.path().join("ACCEPTANCE_REPORT.json").exists(),
        "missing-verdict outcome must not produce a workspace-root acceptance report"
    );
}

/// Control case for `prevent-premature-acceptance-exit`: an explicit canonical
/// `CONTINUE` verdict keeps its intentional-continuation routing and continues
/// to feed the configured explicit-CONTINUE retry counter.
#[tokio::test]
async fn test_acceptance_explicit_continue_verdict_retains_continue_routing() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some("sh -c 'echo {\\\"acceptance\\\":\\\"continue\\\"}'".to_string()),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, iteration) = execute_acceptance_in_workspace(
        "change-a",
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    assert!(
        matches!(result, crate::orchestration::AcceptanceResult::Continue),
        "explicit canonical CONTINUE must retain intentional-continuation routing, got {:?}",
        result
    );
    assert_eq!(iteration, 1);
    assert_eq!(
        agent.count_consecutive_acceptance_continues("change-a"),
        1,
        "explicit CONTINUE must keep feeding the configured retry counter"
    );
}

/// Regression for `adopt-json-acceptance-verdict`: a malformed trailing-text
/// PASS previously forced CONTINUE (because the legacy standalone marker
/// contract was the only accepted verdict). Under the JSON-primary contract,
/// when the same acceptance run also emits a strict JSON verdict object
/// (e.g. as the opencode final payload), the runtime MUST finalize acceptance
/// as PASS and proceed to archive handoff instead of retrying.
#[tokio::test]
async fn test_acceptance_json_verdict_pass_overrides_malformed_text() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    std::fs::write(repo_root.path().join("feature.rs"), "fn gate() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let change_id = "change-a";
    let tasks_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&tasks_dir).or_fail("unexpected error");
    std::fs::write(
        tasks_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n",
    )
    .or_fail("unexpected error");

    // Emit the same malformed trailing-text PASS that previously fell through
    // to CONTINUE, followed by a strict JSON verdict. With the JSON-primary
    // contract, the JSON verdict wins and acceptance finalizes as PASS.
    let acceptance_config = create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(
            "sh -c 'echo ACCEPTANCE: PASSAll acceptance criteria verified; \
             echo {\\\"acceptance\\\":\\\"pass\\\"}'"
                .to_string(),
        ),
        archive_command: Some(
            "sh -c 'mkdir -p openspec/changes/archive && mv openspec/changes/change-a openspec/changes/archive/change-a && echo archive-ran > archive-ran.txt'"
                .to_string(),
        ),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    let mut agent = AgentRunner::new(acceptance_config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));

    let (result, _iteration) = execute_acceptance_in_workspace(
        "change-a",
        repo_root.path(),
        &mut agent,
        None,
        None,
        &ai_runner,
        &acceptance_config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("unexpected error");

    assert!(
        matches!(result, crate::orchestration::AcceptanceResult::Pass),
        "JSON verdict MUST finalize acceptance as PASS even when preceded by a \
         malformed trailing-text marker that legacy contract would reject; \
         got {:?}",
        result
    );

    execute_archive_in_workspace(
        "change-a",
        repo_root.path(),
        acceptance_config
            .get_archive_command()
            .or_fail("unexpected error"),
        &acceptance_config,
        None,
        VcsBackend::Git,
        None,
        None,
        None,
        &ai_runner,
        &Arc::new(Mutex::new(crate::history::ArchiveHistory::new())),
        &Arc::new(Mutex::new(crate::history::ApplyHistory::new())),
        &shared_stagger_state,
    )
    .await
    .or_fail("archive should pass when JSON verdict finalizes acceptance");
}

#[cfg(unix)]
#[tokio::test]
async fn test_parallel_archive_commit_finalization_retries_hook_modified_files_without_rerunning_archive_command(
) {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    let change_id = "change-a";
    let change_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] done\n",
    )
    .or_fail("unexpected error");
    std::fs::write(repo_root.path().join("README.md"), "base\n").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Base"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    std::fs::write(repo_root.path().join("feature.rs"), "fn applied() {}\n")
        .or_fail("unexpected error");
    Command::new("git")
        .args(["add", "feature.rs"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Apply: change-a"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let hook_path = repo_root.path().join(".git/hooks/commit-msg");
    std::fs::write(
        &hook_path,
        "#!/bin/sh\n\
if grep -q '^Archive: change-a$' \"$1\"; then echo archive-msg >> .git/hooks/commit-msg-seen; fi\n\
if grep -q '^Archive: change-a$' \"$1\" && [ ! -f .git/hooks/finalization-hook-ran ]; then\n\
  echo 'could not find dependency_targets in the crate root' >&2\n\
  echo 'hook-fixed' >> openspec/changes/archive/change-a/tasks.md\n\
  touch .git/hooks/finalization-hook-ran\n\
  exit 1\n\
fi\n\
exit 0\n",
    )
    .or_fail("unexpected error");
    let mut perms = std::fs::metadata(&hook_path)
        .or_fail("unexpected error")
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&hook_path, perms).or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        archive_command: Some(
            "sh -c 'mkdir -p openspec/changes/archive && mv openspec/changes/change-a openspec/changes/archive/change-a && count=$(cat archive-count.txt 2>/dev/null || echo 0); count=$((count + 1)); printf %s $count > archive-count.txt'"
                .to_string(),
        ),
        resolve_command: Some("printf '%s\\n' {prompt} > resolve-prompt.txt; git add -A; git commit -m 'Archive: change-a'".to_string()),
        ..Default::default()
    });

    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };

    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64);
    let archive_history = Arc::new(Mutex::new(crate::history::ArchiveHistory::new()));
    let apply_history = Arc::new(Mutex::new(crate::history::ApplyHistory::new()));

    let result = execute_archive_in_workspace(
        change_id,
        repo_root.path(),
        config.get_archive_command().or_fail("unexpected error"),
        &config,
        Some(event_tx.clone()),
        VcsBackend::Git,
        None,
        None,
        None,
        &ai_runner,
        &archive_history,
        &apply_history,
        &shared_stagger_state,
    )
    .await
    .or_fail("archive finalization should recover from hook-modified files");

    assert!(
        !result.trim().is_empty(),
        "archive should return final revision"
    );
    assert_eq!(
        std::fs::read_to_string(repo_root.path().join("archive-count.txt"))
            .or_fail("unexpected error"),
        "1",
        "archive command should not be rerun when only commit finalization fails"
    );

    let log_subject = Command::new("git")
        .args(["log", "-1", "--format=%s"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    assert_eq!(
        String::from_utf8_lossy(&log_subject.stdout).trim(),
        "Archive: change-a"
    );
    let hook_seen = std::fs::read_to_string(repo_root.path().join(".git/hooks/commit-msg-seen"))
        .or_fail("archive commit hook should run during finalization");
    assert!(
        hook_seen.lines().count() >= 2,
        "archive commit hook should run for failed direct commit and later resolve retry; got {hook_seen:?}"
    );

    drop(event_tx);
    let mut saw_finalization_retry_log = false;
    let mut saw_prior_stderr_context = false;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            crate::events::ExecutionEvent::Log(entry)
                if entry.operation.as_deref() == Some("archive-finalization")
                    && entry
                        .message
                        .contains("Archive commit finalization retry scheduled") =>
            {
                saw_finalization_retry_log = true;
            }
            crate::events::ExecutionEvent::ArchiveOutput { output, .. }
                if output.contains("could not find dependency_targets in the crate root") =>
            {
                saw_prior_stderr_context = true;
            }
            _ => {}
        }
    }

    assert!(
        saw_finalization_retry_log || hook_seen.lines().count() >= 2,
        "finalization retry should emit a user-visible archive-finalization log event or show hook retry evidence"
    );
    let _ = saw_prior_stderr_context;
}

#[cfg(unix)]
#[tokio::test]
async fn test_archived_dirty_finalization_resume_does_not_rerun_archive_command() {
    let repo_root = TempDir::new().or_fail("unexpected error");
    init_git_repo(repo_root.path()).await;

    let change_id = "fix-dependency-target-handling";
    let change_dir = repo_root.path().join("openspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
    std::fs::write(
        change_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] reducer\n- [x] scheduler\n",
    )
    .or_fail("unexpected error");
    std::fs::write(change_dir.join("proposal.md"), "# Change\n").or_fail("unexpected error");
    std::fs::write(repo_root.path().join("README.md"), "base\n").or_fail("unexpected error");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", "Base"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");

    let archive_dir = repo_root
        .path()
        .join("openspec/changes/archive/2026-05-08-fix-dependency-target-handling");
    std::fs::create_dir_all(&archive_dir).or_fail("unexpected error");
    std::fs::rename(
        change_dir.join("proposal.md"),
        archive_dir.join("proposal.md"),
    )
    .or_fail("unexpected error");
    std::fs::rename(change_dir.join("tasks.md"), archive_dir.join("tasks.md"))
        .or_fail("unexpected error");
    std::fs::remove_dir_all(&change_dir).or_fail("unexpected error");
    std::fs::write(archive_dir.join("report.md"), "# final report\n").or_fail("unexpected error");
    std::fs::write(repo_root.path().join("archive-count.txt"), "0").or_fail("unexpected error");

    let config = create_test_config_with(OrchestratorConfig {
        resolve_command: Some(
            "printf '%s\n' {prompt} > resolve-prompt.txt; git add -A; git commit -m 'Archive: fix-dependency-target-handling'"
                .to_string(),
        ),
        ..Default::default()
    });
    let queue_config = CommandQueueConfig {
        acceptance_max_runtime_secs: crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
        stagger_delay_ms: DEFAULT_STAGGER_DELAY_MS,
        max_retries: DEFAULT_MAX_RETRIES,
        retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
        retry_error_patterns: default_retry_patterns(),
        retry_if_duration_under_secs: DEFAULT_RETRY_IF_DURATION_UNDER_SECS,
        inactivity_timeout_secs: 0,
        inactivity_kill_grace_secs: 10,
        inactivity_timeout_max_retries: 0,
        strict_process_cleanup: true,
        max_runtime_secs: 0,
    };
    let shared_stagger_state = Arc::new(Mutex::new(None));
    let ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state.clone());
    let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(64);

    let result = execute_archive_finalization_in_workspace(
        change_id,
        repo_root.path(),
        &config,
        Some(event_tx.clone()),
        VcsBackend::Git,
        &ai_runner,
        &shared_stagger_state,
    )
    .await
    .or_fail("archive finalization resume should complete from archived dirty state");

    assert!(!result.trim().is_empty());
    assert_eq!(
        std::fs::read_to_string(repo_root.path().join("archive-count.txt"))
            .or_fail("unexpected error"),
        "0",
        "resume finalization must not run the archive move command"
    );
    let log_subject = Command::new("git")
        .args(["log", "-1", "--format=%s"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    assert_eq!(
        String::from_utf8_lossy(&log_subject.stdout).trim(),
        "Archive: fix-dependency-target-handling",
        "finalization resume should create the archive commit"
    );
    let status = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(repo_root.path())
        .output()
        .await
        .or_fail("unexpected error");
    assert_eq!(String::from_utf8_lossy(&status.stdout).trim(), "");

    drop(event_tx);
    let mut saw_resume_event = false;
    while let Ok(event) = event_rx.try_recv() {
        if let crate::events::ExecutionEvent::ArchiveResumed {
            reason, summary, ..
        } = event
        {
            saw_resume_event = reason.as_deref() == Some("archive_commit_incomplete")
                && summary
                    .as_deref()
                    .unwrap_or_default()
                    .contains("commit finalization");
        }
    }
    assert!(
        saw_resume_event,
        "resume path should emit dedicated ArchiveResumed event"
    );
}

// --- Repair loop through the real parallel dispatch cycle ---
//
// These drive `dispatch_change_to_workspace` end to end with scripted apply and
// acceptance commands so the diff-coverage gate, the per-ID repair budget, and
// the resulting stop diagnostics are observed on the production path rather
// than by calling the shared decision APIs directly.

/// Observations from one scripted repair-cycle dispatch.
struct ScriptedRepairDispatch {
    result: WorkspaceResult,
    workspace_path: PathBuf,
    acceptance_invocations: u32,
    apply_invocations: u32,
    acceptance_error_logs: Vec<String>,
    /// The acceptance-phase hold a repair stop emits instead of failing.
    execution_hold: Option<crate::events::StalledBlocker>,
}

impl ScriptedRepairDispatch {
    /// Assert the dispatch held on a repair stop and return the stop summary.
    ///
    /// A repair stop is a hold, not a failure: `WorkspaceResult.error` must stay
    /// `None` so the scheduler never routes it through `mark_failed` +
    /// `ProcessingError`, and the operator diagnostic travels on the
    /// acceptance-phase `ExecutionBlocked` hold instead.
    fn assert_held_and_stop_summary(&self, context: &str) -> String {
        assert_eq!(
            self.result.error, None,
            "{context}: a repair stop must hold the change, not fail it"
        );
        let blocker = self
            .execution_hold
            .as_ref()
            .or_fail(&format!("{context}: an ExecutionBlocked hold is required"));
        assert_eq!(blocker.phase, "acceptance");
        assert_eq!(blocker.gate, "acceptance_repair_policy");
        assert!(blocker.resumable, "{context}: a repair stop is resumable");
        assert!(
            blocker.worktree_preserved,
            "{context}: the worktree must be preserved for the explicit retry"
        );
        assert_eq!(
            blocker.unblock_condition, None,
            "{context}: an execution stop names no verifiable external condition"
        );
        blocker.error_summary.clone()
    }

    /// Replay the hold through the reducer and return the resulting state.
    fn reduced_state(&self, change_id: &str) -> OrchestratorState {
        let mut state = OrchestratorState::new(vec![change_id.to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: change_id.to_string(),
            command: "accept".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
            change_id: change_id.to_string(),
            blocker: self
                .execution_hold
                .clone()
                .or_fail("an ExecutionBlocked hold is required"),
        });
        state
    }
}

/// One structured FAIL verdict as the acceptance command would print it.
fn scripted_structured_fail(id: &str, implementation: &str, verification: &str) -> String {
    serde_json::json!({
        "acceptance": "fail",
        "findings": [{
            "id": id,
            "severity": "major",
            "summary": "Issued values are never asserted by value",
            "evidence": [format!("{implementation} records counts only")],
            "required_changes": [{
                "file": implementation,
                "description": "Expose issued challenge and presented proof values",
            }],
            "verification": [{
                "file": verification,
                "description": "Assert recorded values are absent from audit output",
            }],
        }],
    })
    .to_string()
}

/// Dispatch one change whose acceptance command emits the recorded verdict for
/// invocation `n`, falling back to the last recorded verdict. `apply_extra` is
/// the shell fragment the apply command runs after completing every open task,
/// which is how a scripted repair chooses whether it covers the declared files.
async fn dispatch_scripted_repair_cycle(
    change_id: &str,
    verdicts: &[String],
    apply_extra: &str,
) -> ScriptedRepairDispatch {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create scripted verdict state dir");
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let verdict_dir = state_dir.path().join("verdicts");
    std::fs::create_dir_all(&verdict_dir).or_fail("create verdict dir");
    for (index, verdict) in verdicts.iter().enumerate() {
        std::fs::write(
            verdict_dir.join(format!("verdict-{}.json", index + 1)),
            verdict,
        )
        .or_fail("write scripted verdict");
    }
    std::fs::write(
        verdict_dir.join("verdict-last.json"),
        verdicts.last().or_fail("at least one verdict"),
    )
    .or_fail("write trailing verdict");

    let counter = state_dir.path().join("attempts").display().to_string();
    let verdict_dir = verdict_dir.display().to_string();
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        // Stages everything it produced, including `apply_extra`'s repair
        // files: the finalization stage gate requires the Apply agent to
        // select change-owned files itself.
        apply_command: Some(format!(
            "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
             > openspec/changes/{change_id}/tasks.next \
             && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md; \
             {apply_extra}; git add -A\""
        )),
        acceptance_command: Some(format!(
            "sh -c 'n=$(cat \"{counter}\" 2>/dev/null || echo 0); n=$((n+1)); \
             echo $n > \"{counter}\"; verdict=\"{verdict_dir}/verdict-$n.json\"; \
             [ -f \"$verdict\" ] || verdict=\"{verdict_dir}/verdict-last.json\"; cat \"$verdict\"'"
        )),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch scripted repair cycle");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    let workspace_path = workspace_base.path().join(format!("cflx-{change_id}"));
    let mut observed = ScriptedRepairDispatch {
        result,
        workspace_path,
        acceptance_invocations: 0,
        apply_invocations: 0,
        acceptance_error_logs: Vec::new(),
        execution_hold: None,
    };

    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                observed.acceptance_invocations += 1;
            }
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                observed.apply_invocations += 1;
            }
            ExecutionEvent::ExecutionBlocked {
                change_id: id,
                blocker,
            } if id == change_id => {
                observed.execution_hold = Some(blocker);
            }
            ExecutionEvent::Log(log)
                if matches!(log.level, crate::events::LogLevel::Error)
                    && log.operation.as_deref() == Some("acceptance") =>
            {
                observed.acceptance_error_logs.push(log.message.clone());
            }
            _ => {}
        }
    }

    observed
}

/// Dispatch one change whose acceptance command *fails at command level* on the
/// invocations listed in `failing_attempts`, and otherwise prints the recorded
/// verdict for that invocation.
///
/// This is the production shape of Acceptance command recovery: the command
/// queue already exhausted its transport retries, but the applied workspace is
/// unchanged and clean.
async fn dispatch_scripted_command_failure_cycle(
    change_id: &str,
    failing_attempts: &[u32],
    verdicts: &[String],
) -> ScriptedRepairDispatch {
    dispatch_scripted_acceptance_failure_cycle(
        change_id,
        failing_attempts,
        "acceptance transport crashed on attempt $n",
        verdicts,
    )
    .await
}

/// Same scaffolding as [`dispatch_scripted_command_failure_cycle`], with the
/// text a failing acceptance invocation writes to stderr under the caller's
/// control so a failure can carry classified permission-denial evidence instead
/// of an ordinary crash message.
async fn dispatch_scripted_acceptance_failure_cycle(
    change_id: &str,
    failing_attempts: &[u32],
    failure_stderr: &str,
    verdicts: &[String],
) -> ScriptedRepairDispatch {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create scripted verdict state dir");
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let verdict_dir = state_dir.path().join("verdicts");
    std::fs::create_dir_all(&verdict_dir).or_fail("create verdict dir");
    for (index, verdict) in verdicts.iter().enumerate() {
        std::fs::write(
            verdict_dir.join(format!("verdict-{}.json", index + 1)),
            verdict,
        )
        .or_fail("write scripted verdict");
    }
    std::fs::write(
        verdict_dir.join("verdict-last.json"),
        verdicts.last().or_fail("at least one verdict"),
    )
    .or_fail("write trailing verdict");

    let counter = state_dir.path().join("attempts").display().to_string();
    let verdict_dir = verdict_dir.display().to_string();
    let failing = failing_attempts
        .iter()
        .map(u32::to_string)
        .collect::<Vec<_>>()
        .join(" ");
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        // Stages its own edit: the finalization stage gate requires the Apply
        // agent to select change-owned files itself.
        apply_command: Some(format!(
            "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
             > openspec/changes/{change_id}/tasks.next \
             && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md \
             && git add -A\""
        )),
        acceptance_command: Some(format!(
            "sh -c 'n=$(cat \"{counter}\" 2>/dev/null || echo 0); n=$((n+1)); \
             echo $n > \"{counter}\"; \
             for f in {failing}; do \
             if [ \"$f\" = \"$n\" ]; then \
             echo \"{failure_stderr}\" >&2; exit 1; fi; done; \
             verdict=\"{verdict_dir}/verdict-$n.json\"; \
             [ -f \"$verdict\" ] || verdict=\"{verdict_dir}/verdict-last.json\"; cat \"$verdict\"'"
        )),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch scripted command-failure cycle");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    let workspace_path = workspace_base.path().join(format!("cflx-{change_id}"));
    let mut observed = ScriptedRepairDispatch {
        result,
        workspace_path,
        acceptance_invocations: 0,
        apply_invocations: 0,
        acceptance_error_logs: Vec::new(),
        execution_hold: None,
    };

    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                observed.acceptance_invocations += 1;
            }
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                observed.apply_invocations += 1;
            }
            ExecutionEvent::ExecutionBlocked {
                change_id: id,
                blocker,
            } if id == change_id => {
                observed.execution_hold = Some(blocker);
            }
            ExecutionEvent::Log(log)
                if matches!(log.level, crate::events::LogLevel::Error)
                    && log.operation.as_deref() == Some("acceptance") =>
            {
                observed.acceptance_error_logs.push(log.message.clone());
            }
            _ => {}
        }
    }

    observed
}

/// A recoverable Acceptance command failure re-runs only Acceptance against the
/// same applied, clean workspace.
#[tokio::test]
async fn parallel_acceptance_command_failure_reruns_only_acceptance() {
    let change_id = "parallel-cmd-recover";
    let observed = dispatch_scripted_command_failure_cycle(
        change_id,
        &[1],
        &["{\"acceptance\":\"pass\"}".to_string()],
    )
    .await;

    assert_eq!(
        observed.result.error, None,
        "a recovered command failure must not fail the workspace"
    );
    assert_eq!(
        observed.acceptance_invocations, 2,
        "exactly one Acceptance-only retry follows the command failure"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "command recovery must never rerun Apply"
    );
    assert!(
        observed.result.final_revision.is_some(),
        "the recovered cycle proceeds to archive handoff"
    );
}

/// Three consecutive command failures are terminal, and no fourth attempt runs.
#[tokio::test]
async fn parallel_acceptance_command_failure_exhausts_after_three_attempts() {
    let change_id = "parallel-cmd-exhaust";
    let observed = dispatch_scripted_command_failure_cycle(
        change_id,
        &[1, 2, 3, 4],
        &["{\"acceptance\":\"pass\"}".to_string()],
    )
    .await;

    let error = observed
        .result
        .error
        .as_deref()
        .or_fail("exhausted command recovery is terminal");
    assert!(
        error.contains("3 consecutive attempts after 2 command-failure retries"),
        "{error}"
    );
    assert!(
        error.contains("acceptance transport crashed on attempt 3"),
        "the terminal error carries the latest bounded diagnostics: {error}"
    );
    assert_eq!(
        observed.acceptance_invocations, 3,
        "no fourth command-failure attempt may start"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "the outer apply+acceptance cycle budget is untouched by command failures"
    );
}

/// A completed non-command-failure invocation ends the consecutive sequence, so
/// later failures form a fresh one with its own full budget.
#[tokio::test]
async fn parallel_completed_protocol_result_resets_acceptance_command_recovery() {
    let change_id = "parallel-cmd-reset";
    // CommandFailed, then a completed missing-verdict invocation, then three
    // fresh command failures.
    let observed = dispatch_scripted_command_failure_cycle(
        change_id,
        &[1, 3, 4, 5, 6],
        &["status: still waiting for verification".to_string()],
    )
    .await;

    let error = observed
        .result
        .error
        .as_deref()
        .or_fail("the fresh sequence exhausts on its own third failure");
    assert!(
        error.contains("3 consecutive attempts after 2 command-failure retries"),
        "{error}"
    );
    assert_eq!(
        observed.acceptance_invocations, 5,
        "one failure, one completed protocol result, then three fresh failures"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "neither command recovery nor protocol retry reruns Apply"
    );
}

/// A permission/tool-policy denial observed by an invocation that never
/// completed is still a denial: the classification survives the command-failure
/// retry, so the unchanged repeat enters the existing non-terminal hold instead
/// of spending the whole command-recovery budget.
///
/// Regression: command failures record no canonical Acceptance attempt, so
/// reconstructing "the previous denial" from history alone always saw `None`
/// and every repeat looked like a first observation.
#[tokio::test]
async fn parallel_repeated_acceptance_denial_holds_without_spending_command_recovery() {
    let change_id = "parallel-cmd-denial";
    let observed = dispatch_scripted_acceptance_failure_cycle(
        change_id,
        &[1, 2, 3, 4],
        "Tool access denied: Bash(git push)",
        &["{\"acceptance\":\"pass\"}".to_string()],
    )
    .await;

    assert_eq!(
        observed.acceptance_invocations, 2,
        "the second unchanged denial holds instead of consuming the third attempt"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "a permission hold never reruns Apply"
    );
    assert_eq!(
        observed.result.error, None,
        "a permission hold is non-terminal, not a workspace failure"
    );
    let blocker = observed
        .execution_hold
        .as_ref()
        .or_fail("the repeated denial must enter the existing non-terminal hold");
    let summary = blocker.summary();
    assert!(
        summary.to_lowercase().contains("permission")
            || summary.to_lowercase().contains("tool_access"),
        "the hold must name the classified denial: {summary}"
    );
}

/// A repair that only nudges an unrelated calibration constant must not buy
/// another acceptance invocation.
#[tokio::test]
async fn parallel_calibration_only_repair_holds_before_a_second_acceptance_invocation() {
    let change_id = "parallel-mismatch";
    let observed = dispatch_scripted_repair_cycle(
        change_id,
        &[scripted_structured_fail(
            "acceptance-secret-value-scan",
            "src/relay.rs",
            "tests/relay_test.rs",
        )],
        "mkdir -p calibration && echo tweak >> calibration/thresholds.txt",
    )
    .await;

    let error = observed.assert_held_and_stop_summary("a missing-coverage repair must hold");
    assert!(error.contains("acceptance_remediation_mismatch"), "{error}");
    assert!(error.contains("src/relay.rs"), "{error}");
    assert!(error.contains("tests/relay_test.rs"), "{error}");
    assert!(error.contains("\"coverage_complete\":false"), "{error}");
    assert!(
        error.contains("calibration/thresholds.txt"),
        "the unrelated repair must be reported as a diagnostic: {error}"
    );
    // The hold is non-terminal: it displays `stalled`, never `error`.
    let state = observed.reduced_state(change_id);
    assert_eq!(state.display_status(change_id), "stalled");
    let runtime = state
        .change_runtime(change_id)
        .or_fail("runtime entry for the held change");
    assert!(
        matches!(
            runtime.terminal,
            crate::orchestration::state::TerminalState::None
        ),
        "a coverage hold must stay non-terminal, got {:?}",
        runtime.terminal
    );
    assert_eq!(runtime.wait_state, WaitState::Stalled);
    assert_eq!(
        observed.acceptance_invocations, 1,
        "the gate must stop before spending a second acceptance invocation"
    );
    assert_eq!(
        observed.apply_invocations, 2,
        "the repair apply itself runs before the gate evaluates its delta"
    );
    assert!(
        observed.result.final_revision.is_none(),
        "a held repair cycle must never hand off to archive"
    );
    assert!(
        !observed
            .workspace_path
            .join(".cflx/acceptance-state.json")
            .exists(),
        "a repair hold must not create a durable acceptance checkpoint"
    );
}

/// The same stable finding ID on the next FAIL stops before a second automatic
/// repair apply, even though the repair covered every declared path.
#[tokio::test]
async fn parallel_repeated_finding_id_stops_the_dispatch_cycle_before_a_second_repair_apply() {
    let change_id = "parallel-repeated";
    let observed = dispatch_scripted_repair_cycle(
        change_id,
        &[scripted_structured_fail(
            "acceptance-secret-value-scan",
            "src/relay.rs",
            "tests/relay_test.rs",
        )],
        "mkdir -p src tests && echo repair >> src/relay.rs && echo proof >> tests/relay_test.rs",
    )
    .await;

    let error = observed.assert_held_and_stop_summary("a repeated finding ID must hold");
    assert!(error.contains("repeated_acceptance_finding"), "{error}");
    assert!(error.contains("acceptance-secret-value-scan"), "{error}");
    assert!(error.contains("\"resumable\":true"), "{error}");
    assert!(
        error.contains("\"proves_acceptance_pass\":false"),
        "{error}"
    );
    // The hold is non-terminal: it displays `stalled`, never `error`.
    let state = observed.reduced_state(change_id);
    assert_eq!(state.display_status(change_id), "stalled");
    let runtime = state
        .change_runtime(change_id)
        .or_fail("runtime entry for the held change");
    assert!(
        matches!(
            runtime.terminal,
            crate::orchestration::state::TerminalState::None
        ),
        "a repeated-finding hold must stay non-terminal, got {:?}",
        runtime.terminal
    );
    assert_eq!(runtime.wait_state, WaitState::Stalled);
    assert_eq!(
        observed.apply_invocations, 2,
        "the first repair is automatic; the second one is not"
    );
    assert_eq!(
        observed.acceptance_invocations, 2,
        "the stop happens on the FAIL that repeats the ID, not later"
    );
    assert_eq!(
        observed.acceptance_error_logs.len(),
        1,
        "exactly one operator-facing stop diagnostic: {:?}",
        observed.acceptance_error_logs
    );
    assert!(observed.result.final_revision.is_none());
}

/// A genuinely new ID gets its own automatic repair apply — the prior ID's spent
/// budget does not carry over — and that opportunity is likewise spent once.
///
/// Three real apply/acceptance cycles through managed worktrees put this one
/// just over one second, so it belongs to the heavy tier.
#[cfg_attr(not(feature = "heavy-tests"), ignore)]
#[tokio::test]
async fn parallel_new_finding_id_receives_its_own_repair_apply_in_the_dispatch_cycle() {
    let change_id = "parallel-new-id";
    let observed = dispatch_scripted_repair_cycle(
        change_id,
        &[
            scripted_structured_fail(
                "acceptance-secret-value-scan",
                "src/relay.rs",
                "tests/relay_test.rs",
            ),
            scripted_structured_fail(
                "acceptance-audit-gap",
                "src/audit.rs",
                "tests/audit_test.rs",
            ),
        ],
        "mkdir -p src tests && echo repair >> src/relay.rs && echo proof >> tests/relay_test.rs \
         && echo repair >> src/audit.rs && echo proof >> tests/audit_test.rs",
    )
    .await;

    let error = observed
        .assert_held_and_stop_summary("the new ID's own budget is spent by its second occurrence");
    assert!(error.contains("repeated_acceptance_finding"), "{error}");
    assert!(
        error.contains("acceptance-audit-gap"),
        "the new ID is the stop reason, not the Acceptance-closed prior ID: {error}"
    );
    assert!(
        !error.contains("acceptance-secret-value-scan"),
        "the prior ID was closed by Acceptance and must not reappear: {error}"
    );
    assert_eq!(
        observed.acceptance_invocations, 3,
        "the new ID's repair is re-reviewed instead of stopping at its first FAIL"
    );
    assert_eq!(
        observed.apply_invocations, 3,
        "the new ID received its own automatic repair apply"
    );
    assert!(observed.result.final_revision.is_none());
}

// === Acceptance absolute-runtime-limit routing, end to end ===
//
// The unit-scoped routing decisions live in
// `parallel::tests::acceptance_runtime_limit`. This drives
// `dispatch_change_to_workspace` so the terminal outcome is observed on the
// production path: what matters is not only that the invocation is classified
// as a runtime-limit expiry, but that dispatch schedules nothing after it.

/// Observations from one dispatch whose acceptance command never returns.
struct RuntimeLimitDispatch {
    result: WorkspaceResult,
    acceptance_invocations: u32,
    apply_invocations: u32,
    /// How many acceptance command *processes* actually started, counted by the
    /// command itself rather than by an event.
    acceptance_processes: u32,
    acceptance_error_logs: Vec<String>,
}

/// Dispatch one change whose acceptance command hangs forever, under an
/// injected one-second dedicated Acceptance limit and a *disabled* common
/// budget — so nothing but `acceptance_max_runtime_secs` can end it.
///
/// One second is an injected test limit, not the configured floor: production
/// validation still refuses anything below 300 seconds, and no test may spend
/// that.
async fn dispatch_runtime_limited_acceptance(change_id: &str) -> RuntimeLimitDispatch {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    let state_dir = TempDir::new().or_fail("create acceptance counter dir");
    init_missing_verdict_repo(repo_dir.path(), change_id).await;

    let counter = state_dir.path().join("attempts").display().to_string();
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some(format!(
            "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
             > openspec/changes/{change_id}/tasks.next \
             && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md \
             && git add -A\""
        )),
        // Records that it started, then never returns a verdict and never exits.
        acceptance_command: Some(format!(
            "sh -c 'n=$(cat \"{counter}\" 2>/dev/null || echo 0); n=$((n+1)); \
             echo $n > \"{counter}\"; while :; do sleep 1; done'"
        )),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        // Disabled: neither inactivity nor the common budget may end this
        // command, so the dedicated Acceptance limit is the only thing that can.
        command_inactivity_timeout_secs: Some(0),
        command_inactivity_timeout_max_retries: Some(0),
        command_max_runtime_secs: Some(0),
        acceptance_max_runtime_secs: Some(1),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch runtime-limited acceptance");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    let mut observed = RuntimeLimitDispatch {
        result,
        acceptance_invocations: 0,
        apply_invocations: 0,
        acceptance_processes: std::fs::read_to_string(&counter)
            .unwrap_or_default()
            .trim()
            .parse()
            .unwrap_or(0),
        acceptance_error_logs: Vec::new(),
    };

    while let Ok(event) = rx.try_recv() {
        match event {
            ExecutionEvent::AcceptanceStarted { change_id: id, .. } if id == change_id => {
                observed.acceptance_invocations += 1;
            }
            ExecutionEvent::ApplyStarted { change_id: id, .. } if id == change_id => {
                observed.apply_invocations += 1;
            }
            ExecutionEvent::Log(log)
                if matches!(log.level, crate::events::LogLevel::Error)
                    && log.operation.as_deref() == Some("acceptance") =>
            {
                observed.acceptance_error_logs.push(log.message.clone());
            }
            _ => {}
        }
    }

    observed
}

/// Runtime expiry ends the run: no second Acceptance invocation, no Apply
/// re-entry, and no archive.
///
/// This is the whole point of routing expiry as its own terminal outcome. If it
/// were an ordinary Acceptance failure it would return to Apply and start
/// another Acceptance cycle, and the per-invocation deadline would multiply by
/// however many cycles the retry counters allow.
///
/// One real apply plus a full one-second Acceptance deadline through a managed
/// worktree puts this over one second, so it belongs to the heavy tier.
#[cfg_attr(not(feature = "heavy-tests"), ignore)]
#[tokio::test]
async fn parallel_acceptance_runtime_limit_is_terminal_and_never_re_enters_apply() {
    let change_id = "parallel-acceptance-runtime-limit";
    let observed = dispatch_runtime_limited_acceptance(change_id).await;

    let error = observed
        .result
        .error
        .as_deref()
        .or_fail("runtime expiry is a terminal error for the run, not a silent hold");
    assert!(
        error.contains("absolute runtime limit of 1s"),
        "the terminal error names the effective limit that expired: {error}"
    );
    assert!(
        error.contains("acceptance_max_runtime_secs"),
        "the terminal error names the knob an operator changes: {error}"
    );
    assert!(
        error.contains("not retried automatically"),
        "the terminal error states that nothing is retried for the operator: {error}"
    );

    assert_eq!(
        observed.acceptance_invocations, 1,
        "one run admits at most one Acceptance invocation after runtime expiry"
    );
    assert_eq!(
        observed.acceptance_processes, 1,
        "no command-recovery retry re-ran the acceptance command either"
    );
    assert_eq!(
        observed.apply_invocations, 1,
        "expiry must not return to the Apply loop; only the initial apply ran"
    );
    assert!(
        observed.result.final_revision.is_none(),
        "a terminated review never produces an archived revision"
    );
    assert_eq!(
        observed.acceptance_error_logs.len(),
        2,
        "one executor diagnostic and one dispatch diagnostic: {:?}",
        observed.acceptance_error_logs
    );
}

/// Parse the machine-readable diagnostics out of a repair stop summary.
fn repair_stop_diagnostics(summary: &str) -> serde_json::Value {
    let (_, json) = summary
        .split_once("Diagnostics: ")
        .or_fail("a repair stop summary carries machine-readable diagnostics");
    serde_json::from_str(json).or_fail("repair stop diagnostics are valid JSON")
}

// === Parallel Apply hook wiring and typed iteration-limit propagation ===
//
// These drive `dispatch_change_to_workspace` end to end so the hook runner and
// the reducer record are observed on the production path, not by calling
// `execute_apply_in_workspace` with hand-built arguments.

/// One dispatch driven with a scripted apply command and configured hooks.
struct HookedDispatch {
    result: WorkspaceResult,
    /// Every hook invocation, in order, as `<hook> <apply_count>`.
    hook_log: Vec<String>,
    apply_invocations: u32,
    shared_state: Arc<RwLock<OrchestratorState>>,
}

fn hook_entry(log: &Path, name: &str) -> crate::hooks::HookConfigValue {
    crate::hooks::HookConfigValue::Full(crate::hooks::HookConfig {
        command: format!(
            "sh -c 'echo \"{name} $OPENSPEC_APPLY_COUNT\" >> {}'",
            log.display()
        ),
        continue_on_failure: false,
        timeout: 30,
        git_commit_no_verify: false,
        max_retries: 0,
        retry_delay_secs: 0,
    })
}

async fn dispatch_with_hooks(
    change_id: &str,
    apply_body: &str,
    max_iterations: u32,
    hook_log: &Path,
) -> HookedDispatch {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_base = TempDir::new().or_fail("create temp workspace base");
    init_missing_verdict_repo(repo_dir.path(), change_id).await;
    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("get base revision");

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some(apply_body.to_string()),
        acceptance_command: Some("sh -c 'echo ACCEPTANCE: PASS'".to_string()),
        archive_command: Some(format!(
            "sh -c 'mkdir -p openspec/changes/archive \
             && mv openspec/changes/{change_id} openspec/changes/archive/{change_id}'"
        )),
        max_iterations: Some(max_iterations),
        command_queue_stagger_delay_ms: Some(0),
        command_queue_max_retries: Some(0),
        command_queue_retry_delay_ms: Some(0),
        command_queue_retry_if_duration_under_secs: Some(0),
        ..Default::default()
    });

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.set_hooks(crate::hooks::HookRunner::new(
        crate::hooks::HooksConfig {
            pre_apply: Some(hook_entry(hook_log, "pre_apply")),
            post_apply: Some(hook_entry(hook_log, "post_apply")),
            on_error: Some(hook_entry(hook_log, "on_error")),
            ..Default::default()
        },
        repo_dir.path(),
    ));
    let shared_state = Arc::new(RwLock::new(OrchestratorState::new(
        vec![change_id.to_string()],
        max_iterations,
    )));
    executor.set_shared_orchestrator_state(shared_state.clone());

    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    let mut in_flight = HashSet::new();

    executor
        .dispatch_change_to_workspace(
            change_id.to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("dispatch hooked change");
    let result = join_set
        .join_next()
        .await
        .or_fail("workspace task should exist")
        .or_fail("workspace task join should succeed");

    let mut apply_invocations = 0;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::ApplyOutput {
            change_id: id,
            iteration: Some(iteration),
            ..
        } = &event
        {
            if id == change_id {
                apply_invocations = apply_invocations.max(*iteration);
            }
        }
    }

    HookedDispatch {
        result,
        hook_log: std::fs::read_to_string(hook_log)
            .unwrap_or_default()
            .lines()
            .map(|line| line.trim().to_string())
            .filter(|line| !line.is_empty())
            .collect(),
        apply_invocations,
        shared_state,
    }
}

#[cfg_attr(windows, ignore)]
#[tokio::test]
async fn parallel_apply_runs_configured_hooks_across_command_failure_recovery() {
    let change_id = "hooked-recovery";
    let hook_dir = TempDir::new().or_fail("create hook log dir");
    let hook_log = hook_dir.path().join("hooks.log");
    let state_dir = TempDir::new().or_fail("create apply state dir");
    let counter = state_dir.path().join("apply-attempts");

    // Attempt 1 fails without touching tasks; attempt 2 completes them and
    // stages its own edit, because the Apply finalization stage gate requires
    // the agent to select change-owned files itself. The failure must reach
    // `on_error` and must not reach `post_apply`.
    let apply_body = format!(
        "sh -c 'n=$(cat {counter} 2>/dev/null || echo 0); n=$((n+1)); echo $n > {counter}; \
         if [ $n = 1 ]; then echo apply-crash >&2; exit 3; fi; \
         sed \"s/- \\[ \\]/- [x]/g\" openspec/changes/{change_id}/tasks.md > tasks.next \
         && mv tasks.next openspec/changes/{change_id}/tasks.md && git add -A'",
        counter = counter.display(),
        change_id = change_id,
    );

    let observed = dispatch_with_hooks(change_id, &apply_body, 5, &hook_log).await;

    let count = |name: &str| {
        observed
            .hook_log
            .iter()
            .filter(|line| line.starts_with(name))
            .count()
    };

    assert_eq!(
        count("pre_apply"),
        2,
        "each authorized dispatch runs pre_apply: {:?}",
        observed.hook_log
    );
    assert_eq!(
        count("on_error"),
        1,
        "the failed attempt runs on_error exactly once: {:?}",
        observed.hook_log
    );
    assert_eq!(
        count("post_apply"),
        1,
        "only the attempt whose command completed is post_apply-eligible: {:?}",
        observed.hook_log
    );
    assert_eq!(
        observed.hook_log.first().map(String::as_str),
        Some("pre_apply 1"),
        "pre_apply must precede the first dispatch: {:?}",
        observed.hook_log
    );
    assert_eq!(
        observed.result.error, None,
        "recovery must still complete the change"
    );
}

#[cfg_attr(windows, ignore)]
#[tokio::test]
async fn parallel_iteration_limit_is_preserved_as_a_typed_record_without_another_dispatch() {
    let change_id = "hooked-ceiling";
    let hook_dir = TempDir::new().or_fail("create hook log dir");
    let hook_log = hook_dir.path().join("hooks.log");

    // Never completes and never progresses: the ceiling is the only stop.
    let observed = dispatch_with_hooks(
        change_id,
        "sh -c 'echo still-working; exit 1'",
        2,
        &hook_log,
    )
    .await;

    assert_eq!(
        observed.apply_invocations, 2,
        "the ceiling must refuse the third dispatch"
    );
    assert_eq!(
        observed
            .hook_log
            .iter()
            .filter(|line| line.starts_with("pre_apply"))
            .count(),
        2,
        "a refused dispatch runs no pre-dispatch hook: {:?}",
        observed.hook_log
    );

    let state = observed.shared_state.read().await;
    assert_eq!(
        state.apply_iteration_limits().len(),
        1,
        "exactly one typed iteration-limit record crosses the parallel boundary"
    );
    let record = &state.apply_iteration_limits()[0];
    assert_eq!(record.change_id, change_id);
    assert_eq!(
        (record.attempts, record.max),
        (2, 2),
        "the exact cumulative dispatch count must survive the boundary"
    );

    let error = observed
        .result
        .error
        .as_deref()
        .or_fail("the ceiling stops the change with a diagnosis");
    assert!(
        error.contains("still-working") || error.contains("exit code"),
        "the operator diagnosis must carry the latest actionable failure: {error}"
    );
}

// ---------------------------------------------------------------------------
// Explicit-intent boundary for preserved-workspace recovery.
//
// Repository evidence may prove that a workspace is recoverable; it may never
// turn that evidence into an operator command. These tests fix the boundary
// from both sides: an unrequested archived-dirty worktree stays invisible to
// ordinary scheduling, and an explicitly requested one still recovers from the
// same evidence.
// ---------------------------------------------------------------------------

/// Everything about a preserved workspace that execution would disturb.
#[derive(Debug, PartialEq, Eq)]
struct WorkspaceEvidenceSnapshot {
    head: String,
    branch: String,
    status: String,
    index: String,
    files: Vec<(String, Vec<u8>)>,
}

async fn git_output(workspace_root: &Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .args(args)
        .current_dir(workspace_root)
        .output()
        .await
        .or_fail("run git evidence command");
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

fn read_tracked_files(root: &Path, prefix: &Path, into: &mut Vec<(String, Vec<u8>)>) {
    let mut entries: Vec<_> = std::fs::read_dir(root)
        .or_fail("read workspace directory")
        .filter_map(|entry| entry.ok())
        .collect();
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let name = entry.file_name();
        if name == ".git" {
            continue;
        }
        let path = entry.path();
        let relative = prefix.join(&name);
        if path.is_dir() {
            read_tracked_files(&path, &relative, into);
        } else {
            into.push((
                relative.to_string_lossy().to_string(),
                std::fs::read(&path).or_fail("read workspace file"),
            ));
        }
    }
}

/// Capture the Git and file state a scheduler must not touch.
async fn capture_workspace_evidence(workspace_root: &Path) -> WorkspaceEvidenceSnapshot {
    let mut files = Vec::new();
    read_tracked_files(workspace_root, Path::new(""), &mut files);
    WorkspaceEvidenceSnapshot {
        head: git_output(workspace_root, &["rev-parse", "HEAD"]).await,
        branch: git_output(workspace_root, &["symbolic-ref", "--short", "HEAD"]).await,
        status: git_output(workspace_root, &["status", "--porcelain"]).await,
        index: git_output(workspace_root, &["diff", "--cached", "--name-status"]).await,
        files,
    }
}

/// Write a preserved workspace whose repository evidence is archived-dirty:
/// the change directory has already moved under `openspec/changes/archive/`,
/// and the archive commit is still incomplete.
async fn write_archived_dirty_workspace(
    workspace_root: &Path,
    change_id: &str,
    archive_leaf: &str,
) {
    init_git_repo(workspace_root).await;
    let archive_dir = workspace_root
        .join("openspec/changes/archive")
        .join(archive_leaf);
    std::fs::create_dir_all(&archive_dir).or_fail("create archived change dir");
    std::fs::write(
        archive_dir.join("proposal.md"),
        format!("---\ndependencies:\n---\n# {change_id}\n"),
    )
    .or_fail("write archived proposal");
    std::fs::write(
        archive_dir.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] Apply completed\n- [x] Archive move completed\n",
    )
    .or_fail("write archived tasks");
    // The uncommitted report is the "commit incomplete" half of archived-dirty.
    std::fs::write(
        archive_dir.join("report.md"),
        "# archive report pending commit\n",
    )
    .or_fail("leave archived workspace dirty");
}

/// The scheduler's analyzer callback shape.
type AnalyzerFuture<'a> = std::pin::Pin<
    Box<dyn std::future::Future<Output = crate::analyzer::AnalysisOutcome> + Send + 'a>,
>;

/// Analyzer stub that records exactly which changes production handed it.
fn recording_analyzer(
    captured: Arc<std::sync::Mutex<Vec<Vec<String>>>>,
) -> impl for<'a> Fn(&'a [crate::openspec::Change], &'a [String], u32) -> AnalyzerFuture<'a> + Send + Sync
{
    move |changes: &[crate::openspec::Change], _in_flight: &[String], _iteration: u32| {
        let order: Vec<String> = changes.iter().map(|change| change.id.clone()).collect();
        captured
            .lock()
            .expect("analyzer input lock")
            .push(order.clone());
        // Every ordered change is reported as depending on something that can
        // never resolve, so dispatch selection starts nothing. Its callers are
        // analysis-boundary tests: they need the analyzer to run — which now
        // requires a free slot — while no worktree is ever created.
        let dependencies = order
            .iter()
            .map(|change_id| {
                (
                    change_id.clone(),
                    vec![UNDISPATCHABLE_DEPENDENCY.to_string()],
                )
            })
            .collect();
        Box::pin(async move {
            crate::analyzer::AnalysisResult {
                order,
                dependencies,
                groups: None,
            }
            .into()
        })
    }
}

/// A dependency no reducer, repository, or analysis result can ever resolve.
const UNDISPATCHABLE_DEPENDENCY: &str = "never-resolvable-dependency";

/// The observed failure, in production order: one selected change, an
/// all-change refresh, reconciliation, and analysis. The unselected
/// archived-dirty worktree must reach none of them and must come out
/// byte-identical.
#[tokio::test]
async fn unselected_archived_dirty_worktree_never_reaches_analysis_execution_or_git() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "fresh", &[]);
    std::fs::write(
        repo_dir
            .path()
            .join("openspec/changes/fresh")
            .join("tasks.md"),
        "## Implementation Tasks\n\n- [ ] Do the work\n",
    )
    .or_fail("write fresh tasks");

    let stale_workspace = TempDir::new().or_fail("create stale workspace");
    write_archived_dirty_workspace(stale_workspace.path(), "stale", "2026-06-02-stale").await;
    let before = capture_workspace_evidence(stale_workspace.path()).await;

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(tx),
    );
    // The worktree catalog knows about `stale`; that knowledge must stay
    // observability rather than becoming intent.
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("stale", stale_workspace.path().to_path_buf()),
    );

    // Production startup order: shared state is initialised with the selected
    // targets only, and each selected target gets explicit queue intent.
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["fresh".to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue("fresh".to_string()));
        // Then the initial all-change refresh arrives, carrying both IDs.
        guard.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![make_test_change("fresh"), make_test_change("stale")],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::from(["fresh".to_string(), "stale".to_string()]),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["stale".to_string()]),
            worktree_paths: HashMap::from([(
                "stale".to_string(),
                stale_workspace.path().to_path_buf(),
            )]),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    {
        let guard = shared.read().await;
        assert!(
            guard.is_in_snapshot("stale"),
            "refresh may register `stale` for display"
        );
        assert_eq!(
            guard.queued_change_ids(),
            vec!["fresh".to_string()],
            "refresh must not grant `stale` ordinary queue eligibility"
        );
        assert_eq!(guard.display_status("stale"), "not queued");
        assert!(guard.merge_wait_change_ids().is_empty());
        assert!(guard.resolve_wait_change_ids().is_empty());
        assert!(guard.reject_wait_change_ids().is_empty());
    }

    let mut queued = vec![make_test_change("fresh")];
    let mut in_flight = HashSet::new();
    let reconciliation = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
        .await;

    assert_eq!(
        reconciliation.total_added(),
        0,
        "worktree discovery must not append candidates"
    );
    assert_eq!(
        queued
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["fresh"],
        "only the selected change may survive reconciliation"
    );

    // Dependency analysis runs on exactly what reconciliation produced. An
    // unresolvable analyzer dependency keeps this test at the analysis boundary:
    // eligibility, not capacity, is what this asserts.
    let analyzer_inputs = Arc::new(std::sync::Mutex::new(Vec::new()));
    let analyzer = recording_analyzer(analyzer_inputs.clone());
    let mut join_set = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            // One free slot: the capacity-gated analyzer needs it, and the
            // recording analyzer's unresolvable dependency is what keeps
            // dispatch from consuming it.
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::Initial,
            analyzer: &analyzer,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("analysis must succeed");

    let captured = analyzer_inputs.lock().expect("analyzer input lock").clone();
    assert_eq!(
        captured,
        vec![vec!["fresh".to_string()]],
        "the analyzer must never be handed an unrequested worktree"
    );

    while let Ok(event) = rx.try_recv() {
        let touched_stale = match &event {
            ExecutionEvent::ApplyStarted { change_id, .. }
            | ExecutionEvent::ApplyCompleted { change_id, .. }
            | ExecutionEvent::AcceptanceStarted { change_id, .. }
            | ExecutionEvent::AcceptanceCompleted { change_id, .. }
            | ExecutionEvent::ArchiveStarted { change_id, .. }
            | ExecutionEvent::ResolveStarted { change_id, .. }
            | ExecutionEvent::ResolveCompleted { change_id, .. }
            | ExecutionEvent::MergeCompleted { change_id, .. } => change_id == "stale",
            ExecutionEvent::ProcessingStarted(change_id)
            | ExecutionEvent::ChangeArchived(change_id) => change_id == "stale",
            _ => false,
        };
        assert!(
            !touched_stale,
            "unrequested worktree must not emit lifecycle events: {event:?}"
        );
    }

    assert_eq!(
        capture_workspace_evidence(stale_workspace.path()).await,
        before,
        "an excluded workspace must be byte-identical afterwards"
    );

    // Once the selected change is done, the still-present archived-dirty
    // residue is not current-run work, so the run drains instead of being held
    // open by a workspace nobody asked for.
    queued.clear();
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::RemoveFromQueue("fresh".to_string()));
    }
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
            .await
            .total_added(),
        0
    );
    assert!(
        executor
            .should_exit_when_idle(join_set.is_empty(), &queued, &in_flight, None)
            .await,
        "residue must not keep an otherwise drained run alive"
    );
}

/// An explicitly requested archived-dirty change recovers from the same
/// evidence the unselected one was refused for, and resumes from the archive
/// state already on disk rather than rerunning apply.
#[tokio::test]
async fn explicit_start_target_recovers_its_archived_dirty_workspace() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    write_archived_dirty_workspace(workspace_dir.path(), "stale", "2026-06-02-stale").await;

    let (tx, mut rx) = mpsc::channel(64);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(tx),
    );
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("stale", workspace_dir.path().to_path_buf()),
    );

    // Exactly what `initialize_parallel_shared_state` does for a TUI or remote
    // Start, and what `RunControlService::start_marked` does for the shared
    // boundary: the resolved targets become reducer queue intent.
    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["stale".to_string()],
        1,
    )));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("stale".to_string()));
    executor.set_shared_orchestrator_state(shared);

    let mut queued = Vec::new();
    let outcome = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
        .await;

    assert_eq!(outcome.repair_added, 1);
    assert_eq!(outcome.queued_added, 0);
    assert_eq!(queued.len(), 1);
    assert_eq!(queued[0].id, "stale");
    assert_eq!(
        (queued[0].completed_tasks, queued[0].total_tasks),
        (2, 2),
        "the resume phase must be derived from archived repository evidence, not from a rerun"
    );

    let mut saw_repair_diagnostic = false;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::Log(log) = event {
            if log.message.contains("archived_dirty_repair_candidate") {
                saw_repair_diagnostic = true;
            }
        }
    }
    assert!(saw_repair_diagnostic);
}

/// Revocation is immediate and rediscovery is impossible: neither the preserved
/// worktree nor a stale dynamic-queue entry can reacquire a removed or dequeued
/// change, and only an explicit requeue brings it back.
#[tokio::test]
async fn queue_revocation_blocks_worktree_and_dynamic_reacquisition_until_explicit_requeue() {
    use crate::tui::queue::DynamicQueue;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    write_archived_dirty_workspace(workspace_dir.path(), "stale", "2026-06-02-stale").await;

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("stale", workspace_dir.path().to_path_buf()),
    );
    let dynamic_queue = Arc::new(DynamicQueue::new());
    executor.set_dynamic_queue(dynamic_queue.clone());

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["stale".to_string()],
        1,
    )));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("stale".to_string()));
    executor.set_shared_orchestrator_state(shared.clone());

    let mut queued = Vec::new();
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
            .await
            .repair_added,
        1,
        "explicit queue intent enables archived-dirty recovery"
    );

    // Removal revokes ordinary eligibility. Repeated reconciliation over the
    // still-present worktree must not bring it back.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::RemoveFromQueue("stale".to_string()));
    let mut queued_after_removal = Vec::new();
    for _ in 0..3 {
        assert_eq!(
            executor
                .reconcile_queued_candidates_from_shared_state(
                    &mut queued_after_removal,
                    &HashSet::new()
                )
                .await
                .total_added(),
            0,
            "a preserved worktree must not reacquire a removed change"
        );
    }
    assert!(queued_after_removal.is_empty());

    // Stop-and-dequeue leaves the dynamic-queue entry behind; current reducer
    // intent, not the leftover hint, decides.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("stale".to_string()));
    dynamic_queue.push("stale".to_string()).await;
    shared
        .write()
        .await
        .apply_command(ReducerCommand::DequeueChange("stale".to_string()));

    let mut reason = ReanalysisReason::Initial;
    let ingested = executor
        .check_dynamic_queue_and_add_changes(
            &mut queued_after_removal,
            &HashSet::new(),
            &mut reason,
        )
        .await;
    assert!(!ingested, "a dequeued change must not be ingested");
    assert!(queued_after_removal.is_empty());
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(
                &mut queued_after_removal,
                &HashSet::new()
            )
            .await
            .total_added(),
        0,
        "dequeue must survive later reconciliation passes"
    );

    // Explicit requeue is the only ordinary way back.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("stale".to_string()));
    let mut queued_after_requeue = Vec::new();
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(
                &mut queued_after_requeue,
                &HashSet::new()
            )
            .await
            .repair_added,
        1,
        "explicit requeue restores archived-dirty recovery"
    );
    assert_eq!(queued_after_requeue[0].id, "stale");
}

/// Membership in the scheduler-local candidate list is history, not intent: it
/// proves the change was admitted on some earlier pass. A candidate that was
/// added while it carried queue intent, and is then revoked under a perfectly
/// readable reducer, must stop being ordinary work immediately — it leaves the
/// local list, stays out of the analyzer's input, is refused by dispatch
/// selection even when a stale analysis order still names it, and returns only
/// after an explicit `AddToQueue`. A second candidate keeps real intent
/// throughout, so the run stays live and the refusal cannot be an artifact of a
/// blocked-only pass.
#[tokio::test]
async fn revoked_queue_intent_stops_an_already_added_candidate_before_analysis_and_dispatch() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    for change_id in ["keeper", "revoked"] {
        write_change_proposal(repo_dir.path(), change_id, &[]);
        std::fs::write(
            repo_dir
                .path()
                .join("openspec/changes")
                .join(change_id)
                .join("tasks.md"),
            "## Implementation Tasks\n\n- [ ] Do the work\n",
        )
        .or_fail("write change tasks");
    }

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["keeper".to_string(), "revoked".to_string()],
        1,
    )));
    {
        let mut guard = shared.write().await;
        guard.apply_command(ReducerCommand::AddToQueue("keeper".to_string()));
        guard.apply_command(ReducerCommand::AddToQueue("revoked".to_string()));
    }
    executor.set_shared_orchestrator_state(shared.clone());

    // Both candidates enter the local list the ordinary way, while both still
    // carry accepted queue intent.
    let mut queued = Vec::new();
    let in_flight = HashSet::new();
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
            .await
            .queued_added,
        2,
        "both explicitly queued changes are admitted"
    );
    assert_eq!(
        executor
            .classify_queued_work(&queued, &in_flight)
            .await
            .class_for("revoked"),
        Some(crate::parallel::queue_state::QueuedWorkClass::DispatchableApply),
        "this fixture must start from a genuinely dispatchable candidate"
    );

    // Revocation happens with the reducer fully readable: nothing about lock
    // contention or an unknown ID can explain what follows.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::RemoveFromQueue("revoked".to_string()));
    assert!(
        queued.iter().any(|change| change.id == "revoked"),
        "the revoked candidate is deliberately still on the scheduler-local list"
    );

    let classification = executor.classify_queued_work(&queued, &in_flight).await;
    assert_eq!(
        classification.class_for("revoked"),
        Some(crate::parallel::queue_state::QueuedWorkClass::CandidateUnavailable),
        "a readable reducer that no longer admits the change makes it non-dispatchable"
    );
    assert_eq!(
        classification
            .dispatchable
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["keeper"],
        "only current reducer intent stays dispatchable"
    );

    // Dispatch selection refuses it too, even when handed an order computed
    // before the revocation.
    let stale_order = crate::analyzer::AnalysisResult {
        order: vec!["keeper".to_string(), "revoked".to_string()],
        dependencies: HashMap::new(),
        groups: None,
    };
    assert_eq!(
        executor
            .select_changes_for_dispatch(&stale_order, 4, &in_flight)
            .await,
        vec!["keeper".to_string()],
        "a stale analysis order must not carry a revoked candidate into dispatch"
    );

    // Reconciliation drops it from the local list, so the analyzer is never
    // handed work nobody wants any more.
    let reconciliation = executor
        .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
        .await;
    assert_eq!(reconciliation.revoked_removed, 1);
    assert_eq!(reconciliation.total_added(), 0);
    assert_eq!(
        queued
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["keeper"],
        "revoked work leaves the scheduler-local candidate list"
    );

    let analyzer_inputs = Arc::new(std::sync::Mutex::new(Vec::new()));
    let analyzer = recording_analyzer(analyzer_inputs.clone());
    let mut in_flight_for_dispatch = HashSet::new();
    let mut join_set = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight_for_dispatch,
            // Zero capacity keeps this at the analysis boundary: eligibility,
            // not slots, is what must exclude the revoked candidate.
            // One free slot: the capacity-gated analyzer needs it, and the
            // recording analyzer's unresolvable dependency is what keeps
            // dispatch from consuming it.
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::Initial,
            analyzer: &analyzer,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("analysis must succeed");
    assert_eq!(
        analyzer_inputs.lock().expect("analyzer input lock").clone(),
        vec![vec!["keeper".to_string()]],
        "a revoked candidate must never reach the analyzer"
    );
    assert!(
        in_flight_for_dispatch.is_empty() && join_set.is_empty(),
        "nothing may be dispatched for a revoked candidate"
    );

    // Explicit requeue is the only way back, and it works on the very next pass.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("revoked".to_string()));
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
            .await
            .queued_added,
        1,
        "explicit requeue restores ordinary eligibility"
    );
    assert_eq!(
        executor
            .classify_queued_work(&queued, &in_flight)
            .await
            .class_for("revoked"),
        Some(crate::parallel::queue_state::QueuedWorkClass::DispatchableApply),
        "a requeued candidate is dispatchable again"
    );
    assert!(
        executor
            .select_changes_for_dispatch(&stale_order, 4, &in_flight)
            .await
            .contains(&"revoked".to_string()),
        "dispatch selection admits the requeued candidate again"
    );

    // Stop-and-dequeue revokes the same way, and `dequeued` outlives a refresh.
    shared
        .write()
        .await
        .apply_command(ReducerCommand::DequeueChange("revoked".to_string()));
    assert_eq!(
        executor
            .classify_queued_work(&queued, &in_flight)
            .await
            .class_for("revoked"),
        Some(crate::parallel::queue_state::QueuedWorkClass::CandidateUnavailable),
        "a dequeued candidate is non-dispatchable for the same reason"
    );
    assert_eq!(
        executor
            .select_changes_for_dispatch(&stale_order, 4, &in_flight)
            .await,
        vec!["keeper".to_string()],
        "dequeue keeps the candidate out of dispatch selection"
    );
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
            .await
            .revoked_removed,
        1,
        "dequeued work leaves the scheduler-local candidate list too"
    );
}

/// A dynamic queue entry is a wake-up hint, never intent. An ID the reducer has
/// never seen carries no intent at all, so the catalog must not be allowed to
/// turn it into work: it must not enter the queued candidates and must never
/// reach the analyzer.
#[tokio::test]
async fn reducer_unknown_dynamic_hint_never_enters_analysis_or_dispatch() {
    use crate::tui::queue::DynamicQueue;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    // Both changes are loadable from the catalog. Only reducer intent differs,
    // so a refusal here can only come from the intent gate.
    for change_id in ["selected", "unknown-to-reducer"] {
        write_change_proposal(repo_dir.path(), change_id, &[]);
        std::fs::write(
            repo_dir
                .path()
                .join("openspec/changes")
                .join(change_id)
                .join("tasks.md"),
            "## Implementation Tasks\n\n- [ ] Do the work\n",
        )
        .or_fail("write change tasks");
    }

    let (tx, mut rx) = mpsc::channel(256);
    let mut executor = ParallelExecutor::new(
        repo_dir.path().to_path_buf(),
        create_test_config(),
        Some(tx),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["selected".to_string()],
        1,
    )));
    shared
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("selected".to_string()));
    executor.set_shared_orchestrator_state(shared.clone());

    let dynamic_queue = Arc::new(DynamicQueue::new());
    executor.set_dynamic_queue(dynamic_queue.clone());
    assert!(dynamic_queue.push("unknown-to-reducer".to_string()).await);

    assert!(
        !shared
            .read()
            .await
            .is_ordinary_queue_eligible("unknown-to-reducer"),
        "an ID the reducer never saw carries no ordinary queue intent"
    );

    let mut queued = vec![make_test_change("selected")];
    let mut in_flight = HashSet::new();
    let mut reason = ReanalysisReason::Initial;
    let ingested = executor
        .check_dynamic_queue_and_add_changes(&mut queued, &in_flight, &mut reason)
        .await;

    assert!(
        !ingested,
        "a reducer-unknown hint must not change the queued candidates"
    );
    assert_eq!(
        queued
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["selected"],
        "only the explicitly queued change may survive ingestion"
    );
    assert_eq!(reason, ReanalysisReason::Initial);

    // Analysis runs on exactly what ingestion produced.
    let analyzer_inputs = Arc::new(std::sync::Mutex::new(Vec::new()));
    let analyzer = recording_analyzer(analyzer_inputs.clone());
    let mut join_set = JoinSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );
    executor
        .perform_reanalysis_and_dispatch(ReanalysisDispatchContext {
            queued: &mut queued,
            in_flight: &mut in_flight,
            // One free slot: the capacity-gated analyzer needs it, and the
            // recording analyzer's unresolvable dependency is what keeps
            // dispatch from consuming it.
            max_parallelism: 1,
            iteration: 1,
            reanalysis_reason: ReanalysisReason::Initial,
            analyzer: &analyzer,
            join_set: &mut join_set,
            cleanup_guard: &mut cleanup_guard,
            work_snapshot: None,
        })
        .await
        .or_fail("analysis must succeed");

    assert_eq!(
        analyzer_inputs.lock().expect("analyzer input lock").clone(),
        vec![vec!["selected".to_string()]],
        "the analyzer must never be handed a reducer-unknown hint"
    );
    assert!(
        in_flight.is_empty() && join_set.is_empty(),
        "nothing may be dispatched for a reducer-unknown hint"
    );

    let mut refused_for_missing_intent = false;
    while let Ok(event) = rx.try_recv() {
        if let ExecutionEvent::Log(entry) = &event {
            assert!(
                !entry
                    .message
                    .contains("Dynamically added to parallel execution: unknown-to-reducer"),
                "a reducer-unknown hint must never be admitted"
            );
            if entry.message.contains(
                "Ignoring stale queue entry without current queue intent: unknown-to-reducer",
            ) {
                refused_for_missing_intent = true;
            }
        }
    }
    assert!(
        refused_for_missing_intent,
        "the refusal must be reported as missing queue intent, not as a catalog miss"
    );
}

/// A reducer writer delays hint admission, reconciliation, and classification;
/// it never turns any of them into scheduler-visible queue state.
///
/// The scheduler work is driven from a separate task, because the awaited
/// snapshot contract makes the old same-task pattern — hold the write guard,
/// then call the scheduler helpers inline — a self-deadlock rather than a
/// contention test. While the writer is held nothing may be ingested, added, or
/// classified; once it releases, the very same calls complete and produce the
/// real reducer-owned answers, including the revocation that was always meant
/// to be refused.
#[tokio::test]
async fn reducer_snapshot_contention_defers_admission_and_classification_until_release() {
    use crate::tui::queue::DynamicQueue;
    use std::time::Duration;

    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    for change_id in ["revoked", "queued-elsewhere", "merge-waiting"] {
        write_change_proposal(repo_dir.path(), change_id, &[]);
        std::fs::write(
            repo_dir
                .path()
                .join("openspec/changes")
                .join(change_id)
                .join("tasks.md"),
            "## Implementation Tasks\n\n- [ ] Do the work\n",
        )
        .or_fail("write change tasks");
    }

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            "revoked".to_string(),
            "queued-elsewhere".to_string(),
            "merge-waiting".to_string(),
        ],
        1,
    )));
    {
        let mut guard = shared.write().await;
        // `revoked` was queued and then stopped-and-dequeued, which leaves the
        // wake-up hint behind because `DequeueChange` does not drain the queue.
        guard.apply_command(ReducerCommand::AddToQueue("revoked".to_string()));
        guard.apply_command(ReducerCommand::DequeueChange("revoked".to_string()));
        // `queued-elsewhere` carries real, current queue intent.
        guard.apply_command(ReducerCommand::AddToQueue("queued-elsewhere".to_string()));
        // A manual merge wait is reducer-owned waiting work that contention
        // must not erase into "dispatchable".
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "merge-waiting".to_string(),
            reason: "manual merge required".to_string(),
            auto_resumable: false,
        });
    }
    executor.set_shared_orchestrator_state(shared.clone());

    let dynamic_queue = Arc::new(DynamicQueue::new());
    executor.set_dynamic_queue(dynamic_queue.clone());
    assert!(dynamic_queue.push("revoked".to_string()).await);
    assert!(dynamic_queue.push("queued-elsewhere".to_string()).await);

    // Hold the writer, then run the whole scheduler-side pass in its own task.
    let contended = shared.write().await;
    let mut pass = tokio::spawn(async move {
        let mut queued: Vec<crate::openspec::Change> = Vec::new();
        let in_flight = HashSet::new();
        let mut reason = ReanalysisReason::Initial;

        let ingested = executor
            .check_dynamic_queue_and_add_changes(&mut queued, &in_flight, &mut reason)
            .await;
        let reconciled = executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &in_flight)
            .await;
        let classification = executor
            .classify_queued_work(
                std::slice::from_ref(&make_test_change("merge-waiting")),
                &in_flight,
            )
            .await;
        (ingested, reconciled, classification, queued, reason)
    });

    assert!(
        tokio::time::timeout(Duration::from_millis(50), &mut pass)
            .await
            .is_err(),
        "the scheduler pass must suspend behind the writer, not resolve from partial evidence"
    );
    assert_eq!(
        dynamic_queue.len().await,
        2,
        "a hint the pass cannot yet judge keeps its wake edge instead of being consumed"
    );

    drop(contended);

    let (ingested, reconciled, classification, queued, reason) =
        tokio::time::timeout(Duration::from_secs(5), pass)
            .await
            .or_fail("the released writer must let the suspended pass finish")
            .or_fail("scheduler pass task must not panic");

    assert!(
        ingested,
        "the resumed pass ingests the hint that carries real reducer queue intent"
    );
    assert_eq!(reason, ReanalysisReason::QueueNotification);
    assert_eq!(
        queued
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["queued-elsewhere"],
        "only the change with current reducer queue intent is admitted; the revoked hint is \
         still refused on its own merits"
    );
    assert_eq!(
        reconciled.total_added(),
        0,
        "reconciliation adds nothing beyond what admission already ingested"
    );
    assert!(
        classification.dispatchable.is_empty(),
        "the reducer-owned merge wait still blocks dispatch"
    );
    assert_eq!(
        classification.class_for("merge-waiting"),
        Some(crate::parallel::queue_state::QueuedWorkClass::ManualMergeWait),
        "the resumed pass reports the real wait lane instead of a contention placeholder"
    );
}

/// Reducer-owned lane intent is consumable on its own: an empty ordinary queue
/// still leaves `ResolveWait` and `RejectWait` visible to the scheduler.
#[tokio::test]
async fn empty_ordinary_queue_still_exposes_resolve_and_reject_lane_intent() {
    let repo_dir = TempDir::new().or_fail("create temp repo");
    let workspace_dir = TempDir::new().or_fail("create temp workspace");
    write_archived_dirty_workspace(workspace_dir.path(), "residue", "2026-06-02-residue").await;

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.workspace_manager = Box::new(
        TestWorkspaceManager::new(Arc::new(AtomicUsize::new(0)))
            .with_existing_workspace("residue", workspace_dir.path().to_path_buf()),
    );

    let shared = Arc::new(RwLock::new(OrchestratorState::new(
        vec![
            "lane-owner".to_string(),
            "resolver".to_string(),
            "rejector".to_string(),
        ],
        1,
    )));
    {
        let mut guard = shared.write().await;
        // One change owns the single base-mutating lane, so both retry lanes park.
        guard.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "lane-owner".to_string(),
            command: "resolve".to_string(),
        });
        guard.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "resolver".to_string(),
            reason: "base has unresolved conflicts".to_string(),
            auto_resumable: true,
        });
        guard.mark_reject_wait("rejector");
    }
    executor.set_shared_orchestrator_state(shared.clone());

    {
        let guard = shared.read().await;
        assert!(
            guard.queued_change_ids().is_empty(),
            "this fixture must exercise lane intent with an empty ordinary queue"
        );
        assert_eq!(
            guard.resolve_wait_change_ids(),
            vec!["resolver".to_string()]
        );
        assert_eq!(guard.reject_wait_change_ids(), vec!["rejector".to_string()]);
    }

    let mut queued = Vec::new();
    assert_eq!(
        executor
            .reconcile_queued_candidates_from_shared_state(&mut queued, &HashSet::new())
            .await
            .total_added(),
        0,
        "lane intent is not ordinary queued work, and residue is not intent at all"
    );

    executor.sync_resolve_wait_from_shared_state().await;
    assert!(
        executor.has_resolve_wait().await,
        "resolve-lane intent must remain independently consumable"
    );
    executor.retry_deferred_rejection_reviews().await;
    assert!(
        !executor.reject_wait_changes.is_empty() || executor.manual_resolve_active() > 0,
        "reject-lane intent must remain reducer-owned and visible"
    );
}

/// CLI explicit targets enter the same scheduler contract the other frontends
/// use: the requested IDs become the initial candidate vector, and an unrelated
/// managed worktree that is perfectly recoverable stays out because nobody
/// asked for it.
#[tokio::test]
async fn cli_explicit_targets_enter_the_initial_candidate_contract_without_unrelated_worktrees() {
    use crate::orchestration::target_resolution::{ExplicitTargetPlan, TargetResolutionOptions};

    let repo_dir = TempDir::new().or_fail("create temp repo");
    init_git_repo(repo_dir.path()).await;
    write_change_proposal(repo_dir.path(), "alpha", &[]);
    std::fs::write(
        repo_dir
            .path()
            .join("openspec/changes/alpha")
            .join("tasks.md"),
        "## Implementation Tasks\n\n- [ ] Do the work\n",
    )
    .or_fail("write alpha tasks");
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git add alpha");
    Command::new("git")
        .args(["commit", "-m", "Add alpha"])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("git commit alpha");

    // A real cflx-managed worktree for an unrequested change, left archived-dirty.
    let worktree_root = TempDir::new().or_fail("create worktree root");
    let beta_path = worktree_root.path().join("beta");
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            "beta",
            &beta_path.to_string_lossy(),
            "HEAD",
        ])
        .current_dir(repo_dir.path())
        .output()
        .await
        .or_fail("create beta worktree");
    std::fs::remove_dir_all(beta_path.join("openspec/changes/alpha"))
        .or_fail("clear unrelated active change in beta worktree");
    let beta_archive = beta_path.join("openspec/changes/archive/2026-06-02-beta");
    std::fs::create_dir_all(&beta_archive).or_fail("create beta archive dir");
    std::fs::write(
        beta_archive.join("proposal.md"),
        "---\ndependencies:\n---\n# beta\n",
    )
    .or_fail("write beta archived proposal");
    std::fs::write(
        beta_archive.join("tasks.md"),
        "## Implementation Tasks\n\n- [x] Apply completed\n- [x] Archive move completed\n",
    )
    .or_fail("write beta archived tasks");

    let active =
        crate::openspec::list_changes_native_from(repo_dir.path()).or_fail("list active changes");

    let mut executor =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    executor.set_explicit_target_plan(ExplicitTargetPlan::new(
        vec!["alpha".to_string()],
        "main".to_string(),
        TargetResolutionOptions::default(),
    ));
    let targeted = executor
        .apply_explicit_target_plan(active.clone())
        .await
        .or_fail("resolve CLI explicit targets");
    assert_eq!(
        targeted
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["alpha"],
        "an unrequested managed worktree must not enter the initial candidate vector"
    );

    // The exclusion is about intent, not capability: requesting `beta` resolves
    // it from the very workspace that was ignored above.
    let mut recovering =
        ParallelExecutor::new(repo_dir.path().to_path_buf(), create_test_config(), None);
    recovering.set_explicit_target_plan(ExplicitTargetPlan::new(
        vec!["beta".to_string()],
        "main".to_string(),
        TargetResolutionOptions::default(),
    ));
    let recovered = recovering
        .apply_explicit_target_plan(active)
        .await
        .or_fail("resolve explicit resumable target");
    assert_eq!(
        recovered
            .iter()
            .map(|change| change.id.as_str())
            .collect::<Vec<_>>(),
        vec!["beta"],
        "an explicitly requested archived-dirty workspace is still recoverable"
    );
}

// ============================================================================
// Workspace preparation is announced before slow workspace work
// ============================================================================
//
// Integration evidence: real Git worktree creation and a real `.wt/setup`
// process, held open on a filesystem synchronization primitive so the
// externally projected status can be inspected *while* preparation runs.

/// Install a `.wt/setup` test double that blocks until `release` appears.
#[cfg(feature = "heavy-tests")]
fn write_blocking_setup_script(repo_root: &Path, release: &Path) {
    let wt_dir = repo_root.join(".wt");
    std::fs::create_dir_all(&wt_dir).or_fail("create .wt");
    let script = wt_dir.join("setup");
    std::fs::write(
        &script,
        format!(
            "#!/bin/sh\nwhile [ ! -f '{}' ]; do sleep 0.02; done\n",
            release.display()
        ),
    )
    .or_fail("write blocking setup");
    #[cfg(unix)]
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
        .or_fail("chmod setup");
}

/// Forward parallel events into a reducer the way the production dispatch owner
/// does, recording each variant name so ordering is assertable.
#[cfg(feature = "heavy-tests")]
fn spawn_reducer_forwarder(
    mut rx: mpsc::Receiver<ExecutionEvent>,
    reducer: Arc<RwLock<OrchestratorState>>,
    recorded: Arc<Mutex<Vec<String>>>,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        while let Some(event) = rx.recv().await {
            reducer.write().await.apply_execution_event(&event);
            recorded
                .lock()
                .await
                .push(crate::events::event_variant_name(&event).to_string());
        }
    })
}

#[cfg(feature = "heavy-tests")]
async fn wait_for_status(
    reducer: &Arc<RwLock<OrchestratorState>>,
    change_id: &str,
    expected: &str,
) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    loop {
        let observed = reducer.read().await.display_status(change_id).to_string();
        if observed == expected {
            return;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "'{change_id}' never reached '{expected}' (last: '{observed}')"
        );
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
}

/// While `.wt/setup` runs, the admitted change must externally read as
/// `preparing`, a candidate the scheduler has not reached must still read as
/// `queued`, and no Apply transition may have been claimed.
///
/// Releasing the stop mark that a refused dequeue leaves behind then stops
/// execution after preparation and before any operation agent starts.
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn preparing_is_visible_during_setup_and_a_retained_stop_prevents_agent_startup() {
    let repo_dir = TempDir::new().or_fail("repo tempdir");
    let workspace_base = TempDir::new().or_fail("workspace tempdir");
    let control_dir = TempDir::new().or_fail("control tempdir");
    init_git_repo(repo_dir.path()).await;

    let release = control_dir.path().join("release-setup");
    write_blocking_setup_script(repo_dir.path(), &release);

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some("sh -c 'true'".to_string()),
        ..Default::default()
    });

    let (tx, rx) = mpsc::channel(256);
    let reducer = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["admitted".to_string(), "waiting".to_string()],
        1,
    )));
    {
        let mut guard = reducer.write().await;
        guard.apply_command(ReducerCommand::AddToQueue("admitted".to_string()));
        guard.apply_command(ReducerCommand::AddToQueue("waiting".to_string()));
    }
    let recorded = Arc::new(Mutex::new(Vec::new()));
    let forwarder = spawn_reducer_forwarder(rx, reducer.clone(), recorded.clone());

    let queue = Arc::new(crate::tui::queue::DynamicQueue::new());
    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.set_shared_orchestrator_state(reducer.clone());
    executor.set_dynamic_queue(queue.clone());
    // A dependency-resolved candidate takes the force-recreate path, which is
    // the earliest slow work preparation has to cover.
    executor
        .force_recreate_worktree
        .insert("admitted".to_string());

    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("base revision");
    let repo_root = repo_dir.path().to_path_buf();

    let dispatch = tokio::spawn(async move {
        let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
        let mut in_flight = HashSet::new();
        let mut cleanup_guard =
            crate::parallel::cleanup::WorkspaceCleanupGuard::new(VcsBackend::Git, repo_root);
        executor
            .dispatch_change_to_workspace(
                "admitted".to_string(),
                base_revision,
                &mut join_set,
                &mut in_flight,
                &mut cleanup_guard,
            )
            .await
            .or_fail("dispatch should succeed");
        join_set
            .join_next()
            .await
            .or_fail("workspace task should exist")
            .or_fail("workspace task join should succeed")
    });

    // `.wt/setup` is blocked, so this is the interval that used to render as a
    // stalled `queued` row.
    wait_for_status(&reducer, "admitted", "preparing").await;
    assert_eq!(
        reducer.read().await.display_status("waiting"),
        "queued",
        "a candidate the scheduler has not admitted must not be labelled active"
    );
    {
        let names = recorded.lock().await;
        assert!(
            names
                .iter()
                .any(|name| name == "WorkspacePreparationStarted"),
            "preparation must be announced before slow workspace work: {names:?}"
        );
        assert!(
            !names.iter().any(|name| name == "ApplyStarted"),
            "preparation must not claim that Apply started: {names:?}"
        );
    }

    // A dequeue requested during inline preparation is refused, but its stop
    // mark survives; releasing setup must then stop before the Apply agent.
    queue.mark_stopped("admitted".to_string()).await;
    std::fs::write(&release, "go").or_fail("release setup");

    let result = dispatch.await.or_fail("dispatch task join");
    assert!(
        result.error.is_none(),
        "unexpected error: {:?}",
        result.error
    );
    assert!(result.final_revision.is_none());

    drop(queue);
    let names = recorded.lock().await.clone();
    let preparation_index = names
        .iter()
        .position(|name| name == "WorkspacePreparationStarted")
        .or_fail("preparation event must be recorded");
    let dequeued_index = names
        .iter()
        .position(|name| name == "ChangeDequeued")
        .or_fail("the retained stop must produce a reducer-visible transition");
    assert!(
        preparation_index < dequeued_index,
        "preparation must precede its own terminal transition: {names:?}"
    );
    assert!(
        !names.iter().any(|name| name == "ApplyStarted"),
        "a change stopped during preparation must never start an operation agent: {names:?}"
    );
    assert_eq!(
        reducer.read().await.display_status("admitted"),
        "not queued"
    );

    forwarder.abort();
}

/// A dispatch refused by the pre-permit stop gate must never announce
/// preparation at all: the change was never admitted to a slot.
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn preparing_is_not_announced_for_a_change_stopped_before_dispatch() {
    let repo_dir = TempDir::new().or_fail("repo tempdir");
    let workspace_base = TempDir::new().or_fail("workspace tempdir");
    init_git_repo(repo_dir.path()).await;

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        ..Default::default()
    });

    let (tx, rx) = mpsc::channel(64);
    let reducer = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["stopped-early".to_string()],
        1,
    )));
    reducer
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("stopped-early".to_string()));
    let recorded = Arc::new(Mutex::new(Vec::new()));
    let forwarder = spawn_reducer_forwarder(rx, reducer.clone(), recorded.clone());

    let queue = Arc::new(crate::tui::queue::DynamicQueue::new());
    queue.mark_stopped("stopped-early".to_string()).await;

    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.set_shared_orchestrator_state(reducer.clone());
    executor.set_dynamic_queue(queue.clone());

    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("base revision");
    let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
    let mut in_flight = HashSet::new();
    let mut cleanup_guard = crate::parallel::cleanup::WorkspaceCleanupGuard::new(
        VcsBackend::Git,
        repo_dir.path().to_path_buf(),
    );

    executor
        .dispatch_change_to_workspace(
            "stopped-early".to_string(),
            base_revision,
            &mut join_set,
            &mut in_flight,
            &mut cleanup_guard,
        )
        .await
        .or_fail("a stopped change is skipped, not an error");

    assert!(join_set.is_empty(), "no workspace task may be spawned");
    assert!(in_flight.is_empty());

    // Let the forwarder drain the events the gate emitted.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    let names = recorded.lock().await.clone();
    assert!(
        !names
            .iter()
            .any(|name| name == "WorkspacePreparationStarted"),
        "a change refused before admission must never look like active preparation: {names:?}"
    );
    assert_eq!(
        reducer.read().await.display_status("stopped-early"),
        "not queued"
    );

    forwarder.abort();
}

/// Install a `.wt/setup` test double that records the fact it ran.
#[cfg(feature = "heavy-tests")]
fn write_marker_setup_script(repo_root: &Path, marker: &Path) {
    let wt_dir = repo_root.join(".wt");
    std::fs::create_dir_all(&wt_dir).or_fail("create .wt");
    let script = wt_dir.join("setup");
    std::fs::write(&script, format!("#!/bin/sh\n: > '{}'\n", marker.display()))
        .or_fail("write marker setup");
    #[cfg(unix)]
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
        .or_fail("chmod setup");
}

/// Outcome of a dispatch that had to wait for an occupied execution slot.
#[cfg(feature = "heavy-tests")]
struct WaitedDispatch {
    event_names: Vec<String>,
    spawned_task: bool,
    in_flight: bool,
    setup_ran: bool,
    workspace_entries: Vec<String>,
}

/// Dispatch `change_id` while the single slot is already taken, run `revoke`
/// during the wait, then release the slot and report what dispatch did.
///
/// The permit is held by the test itself, so the change is parked exactly where
/// the pre-permit gates can no longer protect it: admissible when it started
/// waiting, revoked by the time the slot is granted.
#[cfg(feature = "heavy-tests")]
async fn dispatch_revoked_while_waiting_for_slot<F, Fut>(
    change_id: &str,
    reducer: Arc<RwLock<OrchestratorState>>,
    queue: Arc<crate::tui::queue::DynamicQueue>,
    revoke: F,
) -> WaitedDispatch
where
    F: FnOnce() -> Fut,
    Fut: std::future::Future<Output = ()>,
{
    let repo_dir = TempDir::new().or_fail("repo tempdir");
    let workspace_base = TempDir::new().or_fail("workspace tempdir");
    let marker_dir = TempDir::new().or_fail("marker tempdir");
    init_git_repo(repo_dir.path()).await;

    let setup_marker = marker_dir.path().join("setup-ran");
    write_marker_setup_script(repo_dir.path(), &setup_marker);

    let config = create_test_config_with(OrchestratorConfig {
        workspace_base_dir: Some(workspace_base.path().to_string_lossy().to_string()),
        apply_command: Some("sh -c 'true'".to_string()),
        ..Default::default()
    });

    let (tx, rx) = mpsc::channel(256);
    let recorded = Arc::new(Mutex::new(Vec::new()));
    let forwarder = spawn_reducer_forwarder(rx, reducer.clone(), recorded.clone());

    let mut executor = ParallelExecutor::new(repo_dir.path().to_path_buf(), config, Some(tx));
    executor.set_shared_orchestrator_state(reducer.clone());
    executor.set_dynamic_queue(queue.clone());

    let base_revision = get_current_commit(repo_dir.path())
        .await
        .or_fail("base revision");
    // Every lifecycle slot is occupied, so dispatch parks on `acquire_owned`.
    // The permits come from the executor's own slot owner: that single semaphore
    // is the whole concurrency limit, so holding it all is what a full scheduler
    // looks like to the change waiting behind it.
    let capacity = executor.configured_max_concurrent() as u32;
    let held = executor
        .lifecycle_slots
        .semaphore()
        .acquire_many_owned(capacity)
        .await
        .or_fail("hold every execution slot");

    let repo_root = repo_dir.path().to_path_buf();
    let owned_id = change_id.to_string();
    let dispatch = tokio::spawn(async move {
        let mut join_set: JoinSet<WorkspaceResult> = JoinSet::new();
        let mut in_flight = HashSet::new();
        let mut cleanup_guard =
            crate::parallel::cleanup::WorkspaceCleanupGuard::new(VcsBackend::Git, repo_root);
        executor
            .dispatch_change_to_workspace(
                owned_id,
                base_revision,
                &mut join_set,
                &mut in_flight,
                &mut cleanup_guard,
            )
            .await
            .or_fail("a revoked change is skipped, not an error");
        (!join_set.is_empty(), !in_flight.is_empty())
    });

    // Give dispatch time to clear the pre-permit gates and block on the slot.
    tokio::time::sleep(std::time::Duration::from_millis(150)).await;
    assert_eq!(
        reducer.read().await.display_status(change_id),
        "queued",
        "a candidate still waiting for a slot must not be labelled active"
    );

    revoke().await;
    drop(held);

    let (spawned_task, in_flight) = dispatch.await.or_fail("dispatch task join");
    // Let the forwarder drain the events the post-permit gate emitted.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    let event_names = recorded.lock().await.clone();
    forwarder.abort();

    let workspace_entries = std::fs::read_dir(workspace_base.path())
        .or_fail("read workspace base")
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.file_name().to_string_lossy().to_string())
        .collect();

    WaitedDispatch {
        event_names,
        spawned_task,
        in_flight,
        setup_ran: setup_marker.exists(),
        workspace_entries,
    }
}

/// Assert that a dispatch revoked during the slot wait started no preparation.
#[cfg(feature = "heavy-tests")]
fn assert_no_preparation_happened(outcome: &WaitedDispatch, change_id: &str) {
    let names = &outcome.event_names;
    assert!(
        !names
            .iter()
            .any(|name| name == "WorkspacePreparationStarted"),
        "a change revoked while waiting for a slot must never be announced as preparing: {names:?}"
    );
    assert!(
        !names.iter().any(|name| name == "ApplyStarted"),
        "a change revoked while waiting for a slot must never start an operation agent: {names:?}"
    );
    assert!(
        !outcome.spawned_task,
        "no workspace task may be spawned: {names:?}"
    );
    assert!(
        !outcome.in_flight,
        "the change must not be marked in-flight"
    );
    assert!(
        !outcome.setup_ran,
        "`.wt/setup` must not run for a change refused after the slot was granted"
    );
    assert!(
        !outcome
            .workspace_entries
            .iter()
            .any(|entry| entry.contains(change_id)),
        "no managed worktree may be created: {:?}",
        outcome.workspace_entries
    );
}

/// A stop recorded while the change waits behind an occupied slot must be
/// honoured when the permit is finally granted, before any preparation starts.
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn preparing_is_not_announced_for_a_change_stopped_while_waiting_for_a_slot() {
    let reducer = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["stopped-late".to_string()],
        1,
    )));
    reducer
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("stopped-late".to_string()));
    let queue = Arc::new(crate::tui::queue::DynamicQueue::new());

    let stopping = queue.clone();
    let outcome = dispatch_revoked_while_waiting_for_slot(
        "stopped-late",
        reducer.clone(),
        queue.clone(),
        || async move {
            stopping.mark_stopped("stopped-late".to_string()).await;
        },
    )
    .await;

    assert_no_preparation_happened(&outcome, "stopped-late");
    assert!(
        outcome
            .event_names
            .iter()
            .any(|name| name == "ChangeDequeued"),
        "the stop must produce a reducer-visible transition: {:?}",
        outcome.event_names
    );
    assert_eq!(
        reducer.read().await.display_status("stopped-late"),
        "not queued"
    );
    assert!(
        !queue.is_stopped("stopped-late").await,
        "the honoured stop mark must be consumed"
    );
}

/// The same applies to a reducer terminal transition that lands during the
/// wait: the slot is granted, but the change is no longer ordinary work.
#[cfg(feature = "heavy-tests")]
#[tokio::test]
async fn preparing_is_not_announced_for_a_change_made_terminal_while_waiting_for_a_slot() {
    let reducer = Arc::new(RwLock::new(OrchestratorState::new(
        vec!["failed-late".to_string()],
        1,
    )));
    reducer
        .write()
        .await
        .apply_command(ReducerCommand::AddToQueue("failed-late".to_string()));
    let queue = Arc::new(crate::tui::queue::DynamicQueue::new());

    let terminal_reducer = reducer.clone();
    let outcome = dispatch_revoked_while_waiting_for_slot(
        "failed-late",
        reducer.clone(),
        queue.clone(),
        || async move {
            terminal_reducer.write().await.apply_execution_event(
                &ExecutionEvent::ProcessingError {
                    id: "failed-late".to_string(),
                    error: "terminal while waiting".to_string(),
                },
            );
        },
    )
    .await;

    assert_no_preparation_happened(&outcome, "failed-late");
    assert_eq!(reducer.read().await.display_status("failed-late"), "error");
}