cflx 0.6.322

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
//! Shared state management for orchestration operations.
//!
//! Provides a unified state structure that tracks orchestration progress
//! across every frontend (CLI `run`, TUI, remote control).
//!
//! ## Integration Status
//!
//! - **CLI Orchestrator** (`src/orchestrator.rs`): Fully integrated. The orchestrator
//!   maintains a `shared_state: Arc<RwLock<OrchestratorState>>` instance and updates it
//!   via `apply_execution_event` when processing changes (ProcessingStarted, ApplyStarted,
//!   ApplyCompleted, ChangeArchived). The shared state is wrapped in Arc<RwLock<>> to enable
//!   sharing with TUI and Web monitoring.
//!
//! - **TUI** (`src/tui/state/mod.rs`): Integrated via optional reference. TUI AppState has
//!   a `shared_orchestrator_state` field that can be set via `set_shared_state()`. TUI can
//!   query this for pending/archived status, apply counts, and current change tracking while
//!   maintaining its own UI-specific state for rendering and interaction.
//!
//! - **Web** (`src/web/state.rs`): Integrated via optional reference. WebState has a
//!   `shared_orchestrator_state` field set via `set_shared_state()` (called automatically
//!   by `Orchestrator::set_web_state()`). When generating `OrchestratorStateSnapshot` via
//!   `from_changes_with_shared_state()`, WebState queries shared state to enrich change
//!   metadata with apply counts, pending/archived status, and iteration numbers.
//!
//! ## Usage
//!
//! The shared state provides a single source of truth for tracking:
//! - Pending, completed, and archived changes
//! - Apply counts per change
//! - Current change being processed
//! - Iteration counters and limits
//!
//! ### Integration Pattern
//!
//! 1. **Orchestrator creates and owns shared state:**
//!    ```rust,ignore
//!    let shared_state = Arc::new(RwLock::new(OrchestratorState::new(changes, max_iters)));
//!    ```
//!
//! 2. **Orchestrator updates state via events:**
//!    ```rust,ignore
//!    shared_state.write().await.apply_execution_event(&event);
//!    ```
//!
//! 3. **TUI/Web receive shared state reference:**
//!    ```rust,ignore
//!    app_state.set_shared_state(shared_state.clone());
//!    web_state.set_shared_state(shared_state.clone()).await;
//!    ```
//!
//! 4. **TUI/Web query shared state when needed:**
//!    ```rust,ignore
//!    if let Some(shared) = &app_state.shared_orchestrator_state {
//!        let guard = shared.read().await;
//!        let apply_count = guard.apply_count(change_id);
//!        let is_pending = guard.is_pending(change_id);
//!    }
//!    ```
use std::collections::{HashMap, HashSet};

use crate::error_history::{CircuitBreakerConfig, ErrorHistory};

// ============================================================================
// ChangeRuntimeState types (Phase 1 – reducer-owned state)
// ============================================================================

/// Intent to include or exclude a change from the execution queue.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum QueueIntent {
    /// Not requested to be queued.
    #[default]
    NotQueued,
    /// Requested to be queued for execution.
    Queued,
}

/// Active execution stage for a change.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum ActivityState {
    /// No active execution.
    #[default]
    Idle,
    /// Admitted to an execution slot and preparing its managed workspace.
    ///
    /// Covers force-recreate cleanup, worktree creation/recreation, `.wt/setup`,
    /// and workspace inspection — everything between slot admission and the
    /// first operation agent. It never claims that an agent has started, and it
    /// is discarded on restart: the next action is recomputed from workspace
    /// files, Git state, and base-tree comparison.
    Preparing,
    /// Currently applying.
    Applying,
    /// Currently running acceptance checks.
    Accepting,
    /// Currently running dedicated rejection review.
    Rejecting,
    /// Currently archiving.
    Archiving,
    /// Currently executing a merge resolve.
    Resolving,
}

/// Reason a change is blocked waiting for an external condition.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum WaitState {
    /// Not waiting.
    #[default]
    None,
    /// Waiting for a merge to be attempted (parallel only).
    MergeWait,
    /// Waiting for a resolve sub-task to start (queued resolve intent).
    ResolveWait,
    /// Waiting for rejection review to start once the base-mutating lane is free.
    RejectWait,
    /// Waiting because a dependency has not yet completed.
    DependencyBlocked,
    /// Waiting because the orchestrator validated a non-repository prerequisite
    /// reported by Apply or Acceptance.
    ///
    /// Displays as `blocked` alongside [`WaitState::DependencyBlocked`], but
    /// keeps its own blocker kind so the two waits stay distinguishable and the
    /// external wait never becomes a synthetic proposal dependency edge.
    ExternalBlocked,
    /// Waiting because apply/rejecting reported a resumable hold,
    /// including acceptance gate observations before follow-up routing.
    Stalled,
}

/// Machine-readable reason a change is `blocked`.
///
/// Mirrors [`crate::runtime::proposal::BlockerKind`] on the reducer that owns
/// operator-facing display, so surfaces never re-derive the kind from prose,
/// filenames, or task text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BlockerKind {
    /// The change is not blocked.
    #[default]
    None,
    /// Waiting on an unarchived proposal dependency.
    Dependency,
    /// Waiting on a validated non-repository prerequisite.
    External,
}

impl BlockerKind {
    /// Stable token exposed to TUI, WebSocket/API, and the dashboard.
    pub fn as_str(self) -> Option<&'static str> {
        match self {
            Self::None => None,
            Self::Dependency => Some("dependency"),
            Self::External => Some("external"),
        }
    }
}

/// Operator-facing one-line explanation of a dependency wait.
fn dependency_blocker_detail(dependency_ids: &[String]) -> String {
    if dependency_ids.is_empty() {
        return "waiting for unresolved dependencies".to_string();
    }
    format!("waiting for dependencies: {}", dependency_ids.join(", "))
}

/// Verifiable condition that clears a dependency wait.
fn dependency_unblock_condition(dependency_ids: &[String]) -> String {
    if dependency_ids.is_empty() {
        return "every declared dependency is integrated into the effective dependency base"
            .to_string();
    }
    format!(
        "dependencies {} are integrated into the effective dependency base",
        dependency_ids.join(", ")
    )
}

/// Additional metadata preserved while a change is blocked.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BlockedMetadata {
    /// Machine-readable blocker category.
    pub blocker_reason: Option<String>,
    /// Optional operator-facing unblock guidance.
    pub unblock_metadata: Option<String>,
    /// Optional snapshot of worktree context captured when blocker was recorded.
    pub worktree_snapshot: Option<String>,
    /// True when the hold originated in the Acceptance phase.
    ///
    /// This is the whole Acceptance stall hold. It is reducer-owned in-memory
    /// state for one process lifetime — nothing is written outside the managed
    /// worktree — and it may only suppress ordinary dispatch, drive the
    /// `stalled` presentation, and make an explicit retry eligible. It never
    /// proves PASS, archive readiness, or merge eligibility.
    pub acceptance_stall: bool,
    /// Whether the blocker declared that work can resume once the external
    /// prerequisite is satisfied.
    pub resumable: bool,
    /// Machine-readable blocker kind for a `blocked` change.
    ///
    /// `None` for stalled holds: an execution stop is not a wait on a named
    /// prerequisite, and calling it one would hide why automation gave up.
    pub blocker_kind: BlockerKind,
    /// Verifiable condition that clears a validated external prerequisite wait.
    pub unblock_condition: Option<String>,
    /// Owning team/role or named prerequisite for an external wait.
    pub prerequisite_owner: Option<String>,
    /// Phase that observed a validated external prerequisite.
    pub blocker_origin: Option<String>,
    /// Current unresolved dependency IDs for a dependency wait.
    ///
    /// Structured rather than folded into the detail string: a consumer that
    /// has to decide *which* dependency it is waiting on must not have to parse
    /// operator prose. Empty for every non-dependency hold.
    pub dependency_ids: Vec<String>,
}

/// Reducer-derived operator-facing view of one blocked or stalled change.
///
/// Every surface consumes this instead of inferring lifecycle state itself, so
/// TUI, WebSocket/API, and the dashboard cannot disagree about whether a row is
/// dependency-blocked, externally blocked, or stalled.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockerView {
    /// Reducer display status: `blocked` or `stalled`.
    pub status: &'static str,
    /// Machine-readable blocker kind; `None` for a stalled execution hold.
    pub kind: BlockerKind,
    /// Machine-readable blocker reason/category.
    pub category: Option<String>,
    /// One-line operator-facing explanation.
    pub detail: Option<String>,
    /// Verifiable condition that clears an external wait.
    pub unblock_condition: Option<String>,
    /// Owning team/role for an external wait.
    pub prerequisite_owner: Option<String>,
    /// Phase that observed an external prerequisite.
    pub origin: Option<String>,
    /// Whether work can resume once the prerequisite is satisfied.
    pub resumable: bool,
    /// Current unresolved dependency IDs for a dependency wait; empty otherwise.
    pub dependencies: Vec<String>,
}

/// Terminal outcome for a change (once reached, no further transitions).
#[derive(Debug, Clone, PartialEq, Default)]
pub enum TerminalState {
    /// Not yet in a terminal state.
    #[default]
    None,
    /// Successfully merged to the base branch.
    Merged,
    /// Successfully pushed to a remote branch.
    Pushed,
    /// Rejected after acceptance blocker detection.
    Rejected(String),
    /// Encountered a non-recoverable error.
    Error(String),
    /// Stopped by user request.
    Stopped,
}

/// Repository evidence that decides how a stale deferred resolve retry settles.
///
/// Base-branch tree comparison is the authoritative completion evidence, so an
/// unreadable comparison is kept apart from a comparison that ran and found
/// nothing: only the first is a proof of anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleResolveEvidence {
    /// Base-branch tree comparison proved the change is already integrated.
    Proven,
    /// Base-branch tree comparison ran and the change is not integrated.
    Absent,
    /// Integration evidence could not be read safely.
    Unknown,
}

/// Reducer state a stale deferred resolve retry settled into.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleResolveSettlement {
    /// Terminal `merged` recorded from repository-proven base integration.
    Merged,
    /// Retryable manual `merge wait` retained for an explicit operator retry.
    MergeWaitRetained,
    /// The change already carried an immutable outcome or an explicit dequeue,
    /// so only the consumed retry reservation was released.
    AlreadySettled,
}

/// Observation derived from a workspace refresh scan.
/// Used by `apply_observation()` to reconcile MergeWait without overwriting
/// active activity.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum WorkspaceObservation {
    /// No relevant observation.
    #[default]
    None,
    /// Workspace is in `Archived` state: change may need manual `MergeWait` reconciliation.
    WorkspaceArchived,
    /// Worktree is NOT ahead of base: `MergeWait` can be cleared.
    WorktreeNotAhead,
}

/// Full runtime state for a single change, owned by the reducer.
#[derive(Debug, Clone, Default)]
pub struct ChangeRuntimeState {
    /// Queue intent: whether the change has been requested to run.
    pub queue_intent: QueueIntent,
    /// Active execution stage.
    pub activity: ActivityState,
    /// Wait condition (may co-exist with `Queued` intent).
    pub wait_state: WaitState,
    /// Preserved metadata for blocked states.
    pub blocked_metadata: BlockedMetadata,
    /// Terminal outcome once reached.
    pub terminal: TerminalState,
    /// Latest workspace observation (used for reconcile only).
    pub observation: WorkspaceObservation,
    /// True when a change was explicitly force-stopped and dequeued.
    /// While true, stale in-flight execution events must not re-activate this change.
    pub dequeued: bool,
    /// Ephemeral final-commit presentation: the finalization attempt currently
    /// running, if any.
    ///
    /// Presentation only, and process-local by construction. It never changes
    /// [`Self::display_status`], is never persisted, and must never be read by
    /// scheduler eligibility, resume routing, acceptance, archive, merge, or any
    /// other next-action decision — those are re-derived from the workspace
    /// after a restart, which is exactly when this field is gone.
    pub commit_phase_attempt: Option<u32>,
    /// Ephemeral, process-local permission for one manual resolve retry to
    /// continue this change's own unfinished target merge.
    ///
    /// Set only by an explicit operator resolve intent, and cleared the moment a
    /// dispatch that owns the base lane consumes it. It is never persisted and
    /// never routes work on its own: it only decides whether the single admitted
    /// dispatch uses the scoped merge-continuation evidence check instead of the
    /// generic base-dirty preflight. A restart drops it, and the next action is
    /// re-derived from the workspace exactly as before.
    pub manual_resolve_retry: bool,
}

impl ChangeRuntimeState {
    fn clear_blocked_metadata(&mut self) {
        self.blocked_metadata = BlockedMetadata::default();
    }

    fn set_blocked_metadata(
        &mut self,
        blocker_reason: impl Into<String>,
        unblock_metadata: impl Into<String>,
        worktree_snapshot: impl Into<String>,
    ) {
        self.blocked_metadata = BlockedMetadata {
            blocker_reason: Some(blocker_reason.into()),
            unblock_metadata: Some(unblock_metadata.into()),
            worktree_snapshot: Some(worktree_snapshot.into()),
            acceptance_stall: false,
            resumable: false,
            blocker_kind: BlockerKind::None,
            unblock_condition: None,
            prerequisite_owner: None,
            blocker_origin: None,
            dependency_ids: Vec::new(),
        };
    }

    /// Record — or reconcile — the current unresolved dependency wait.
    ///
    /// This is a *state* write, deliberately separate from the edge-triggered
    /// `DependencyBlocked` diagnostic: the scheduler calls it on every coherent
    /// classification, so a reducer that was replaced, refreshed, or never saw
    /// the original transition still carries the current blocker. It is
    /// idempotent, and it never touches queue intent — a dependency wait is a
    /// dispatch exclusion, not a revocation of admitted work.
    ///
    /// Returns `true` when the projected wait or its dependency set changed.
    fn reconcile_dependency_blocker(&mut self, dependency_ids: &[String]) -> bool {
        let unchanged = matches!(self.wait_state, WaitState::DependencyBlocked)
            && self.blocked_metadata.dependency_ids == dependency_ids;
        if unchanged {
            return false;
        }
        self.wait_state = WaitState::DependencyBlocked;
        self.blocked_metadata = BlockedMetadata {
            blocker_reason: Some("dependency_blocked".to_string()),
            unblock_metadata: Some(dependency_blocker_detail(dependency_ids)),
            worktree_snapshot: Some(
                "worktree snapshot not required for dependency blocker".to_string(),
            ),
            acceptance_stall: false,
            resumable: true,
            blocker_kind: BlockerKind::Dependency,
            unblock_condition: Some(dependency_unblock_condition(dependency_ids)),
            prerequisite_owner: None,
            blocker_origin: Some("scheduler".to_string()),
            dependency_ids: dependency_ids.to_vec(),
        };
        true
    }

    /// Reset transient execution state for non-terminal idle/wait transitions.
    fn clear_activity_wait_and_blocker(&mut self) {
        self.activity = ActivityState::Idle;
        self.wait_state = WaitState::None;
        // The permission only means anything while this row is waiting on the
        // base-mutating lane; losing the wait loses the retry it authorized.
        self.manual_resolve_retry = false;
        self.clear_blocked_metadata();
    }

    /// Set a final terminal outcome and clear transient activity/wait metadata.
    fn transition_to_terminal(&mut self, terminal: TerminalState) {
        self.terminal = terminal;
        self.activity = ActivityState::Idle;
        self.wait_state = WaitState::None;
        self.manual_resolve_retry = false;
        self.clear_blocked_metadata();
    }

    /// Record a recoverable stalled/blocker state with structured operator guidance.
    fn transition_to_stalled(
        &mut self,
        blocker_reason: impl Into<String>,
        unblock_metadata: impl Into<String>,
        worktree_snapshot: impl Into<String>,
    ) {
        self.activity = ActivityState::Idle;
        self.wait_state = WaitState::Stalled;
        self.terminal = TerminalState::None;
        self.set_blocked_metadata(blocker_reason, unblock_metadata, worktree_snapshot);
    }

    /// Record a recoverable stalled state that Acceptance owns.
    ///
    /// Identical to [`Self::transition_to_stalled`] except that it also marks
    /// the hold as Acceptance-owned and carries the blocker's resumability,
    /// which together keep the change out of ordinary dispatch until an
    /// explicit retry of a resumable hold — or a restart — clears it.
    fn transition_to_acceptance_stalled(
        &mut self,
        blocker_reason: impl Into<String>,
        unblock_metadata: impl Into<String>,
        worktree_snapshot: impl Into<String>,
        resumable: bool,
    ) {
        self.transition_to_stalled(blocker_reason, unblock_metadata, worktree_snapshot);
        self.blocked_metadata.acceptance_stall = true;
        self.blocked_metadata.resumable = resumable;
    }

    /// Record a validated external prerequisite wait.
    ///
    /// This is the only way to reach [`WaitState::ExternalBlocked`], and it is
    /// reachable only from the orchestrator's classifier — an agent cannot set
    /// it by choosing a verdict word. The hold is in-memory reducer state for
    /// one process lifetime: it may suppress ordinary dispatch and drive the
    /// `blocked` presentation, and it never establishes completion, Acceptance
    /// PASS, archive readiness, or merge eligibility.
    fn transition_to_external_blocked(
        &mut self,
        blocker: &crate::runtime::proposal::ExternalBlockerInfo,
        worktree_snapshot: impl Into<String>,
    ) {
        self.activity = ActivityState::Idle;
        self.wait_state = WaitState::ExternalBlocked;
        self.terminal = TerminalState::None;
        self.blocked_metadata = BlockedMetadata {
            blocker_reason: Some(format!("external-blocked:{}", blocker.category)),
            unblock_metadata: Some(blocker.summary()),
            worktree_snapshot: Some(worktree_snapshot.into()),
            acceptance_stall: matches!(
                blocker.origin,
                crate::runtime::proposal::BlockerOrigin::Acceptance
            ),
            resumable: blocker.resumable,
            blocker_kind: BlockerKind::External,
            unblock_condition: Some(blocker.unblock_condition.clone()),
            prerequisite_owner: blocker.prerequisite_owner.clone(),
            blocker_origin: Some(blocker.origin.as_str().to_string()),
            dependency_ids: Vec::new(),
        };
    }

    /// Whether an Acceptance-owned in-memory hold currently keeps this change
    /// out of ordinary dispatch.
    ///
    /// Both the execution `stalled` hold and a validated external `blocked` wait
    /// observed by Acceptance qualify: they suppress dispatch identically and
    /// differ only in how they are explained to an operator.
    pub fn is_acceptance_stalled(&self) -> bool {
        matches!(
            self.wait_state,
            WaitState::Stalled | WaitState::ExternalBlocked
        ) && self.blocked_metadata.acceptance_stall
    }

    /// Whether the current Acceptance hold allows an acceptance-only retry.
    ///
    /// A non-resumable hold keeps its blocker evidence instead: retrying past it
    /// would dispatch ambiguous work the operator has not unblocked.
    pub fn is_resumable_acceptance_stall(&self) -> bool {
        self.is_acceptance_stalled() && self.blocked_metadata.resumable
    }

    /// Whether a validated external prerequisite currently blocks this change.
    #[allow(dead_code)] // Consumed by external-blocked lifecycle regression coverage.
    pub fn is_external_blocked(&self) -> bool {
        matches!(self.wait_state, WaitState::ExternalBlocked)
    }

    /// Whether a structured blocker classification currently owns this wait.
    ///
    /// `AcceptanceGated` and `ExecutionBlocked` carry validated facts — category,
    /// origin, prerequisite owner, unblock condition, next action, resumability —
    /// that a generic `WorkspaceStatus::Blocked` observation does not have. A
    /// hold established from those facts therefore outranks the coarse
    /// observation for the same non-terminal change: the observation may confirm
    /// that the change is still held, but it must not rebuild the metadata from
    /// generic strings.
    ///
    /// Only the two holds that own routing qualify. A validated external wait
    /// drives dispatch suppression and blocked-phase retry, and an
    /// Acceptance-owned stall drives the same suppression plus resumability.
    /// An Apply-origin non-external stall carries neither, so the existing
    /// generic fallback keeps owning it.
    pub fn has_structured_blocker_hold(&self) -> bool {
        match self.wait_state {
            WaitState::ExternalBlocked => true,
            WaitState::Stalled => self.blocked_metadata.acceptance_stall,
            _ => false,
        }
    }

    /// Machine-readable blocker kind for a `blocked` change.
    ///
    /// Derived from the wait state, never from the recorded metadata alone, so a
    /// stale metadata field can never make a non-blocked change look blocked.
    pub fn blocker_kind(&self) -> BlockerKind {
        match self.wait_state {
            WaitState::DependencyBlocked => BlockerKind::Dependency,
            WaitState::ExternalBlocked => BlockerKind::External,
            _ => BlockerKind::None,
        }
    }

    /// Operator-facing blocker detail for a blocked or stalled row.
    pub fn blocker_detail(&self) -> Option<&str> {
        self.blocked_metadata.unblock_metadata.as_deref()
    }

    /// Reducer-derived blocker view for a blocked or stalled row.
    ///
    /// Returns `None` for every other status so a surface can never render a
    /// blocker badge on a change that is not actually held.
    pub fn blocker_view(&self) -> Option<BlockerView> {
        let status = self.display_status();
        if !matches!(status, "blocked" | "stalled") {
            return None;
        }
        Some(BlockerView {
            status,
            kind: self.blocker_kind(),
            category: self.blocked_metadata.blocker_reason.clone(),
            detail: self.blocker_detail().map(str::to_string),
            unblock_condition: self.blocked_metadata.unblock_condition.clone(),
            prerequisite_owner: self.blocked_metadata.prerequisite_owner.clone(),
            origin: self.blocked_metadata.blocker_origin.clone(),
            resumable: self.blocked_metadata.resumable,
            // Only a dependency wait publishes IDs; deriving them from the kind
            // rather than from the retained field keeps a stale metadata list
            // from decorating an external or stalled hold.
            dependencies: match self.blocker_kind() {
                BlockerKind::Dependency => self.blocked_metadata.dependency_ids.clone(),
                _ => Vec::new(),
            },
        })
    }

    /// Check whether this runtime state represents active execution
    /// (applying, accepting, archiving, or resolving).
    pub fn is_active(&self) -> bool {
        !matches!(self.activity, ActivityState::Idle)
    }

    /// Check whether the change is in a terminal state.
    pub fn is_terminal(&self) -> bool {
        !matches!(self.terminal, TerminalState::None)
    }

    /// Check whether the entry carries no reducer-owned state at all.
    ///
    /// This is the only shape a workspace refresh observation may fill in.
    /// Any activity, wait, queue intent, terminal outcome, or explicit dequeue
    /// is stronger reducer-owned evidence than a refresh scan, so a startup
    /// reconciliation must leave those entries exactly as they are.
    fn is_fresh_idle(&self) -> bool {
        matches!(self.activity, ActivityState::Idle)
            && matches!(self.wait_state, WaitState::None)
            && matches!(self.queue_intent, QueueIntent::NotQueued)
            && matches!(self.terminal, TerminalState::None)
            && !self.dequeued
    }

    /// Check whether a repository-visible success event may replace the current terminal state.
    ///
    /// Recoverable execution errors are terminal for retry/slot accounting, but later
    /// same-change archive/merge/resolve success events are more authoritative for current
    /// display state. Final outcomes such as rejected, already merged, archived, or stopped
    /// remain immutable.
    fn can_success_supersede_terminal(&self) -> bool {
        matches!(self.terminal, TerminalState::None | TerminalState::Error(_))
    }

    /// Verify invariants. Returns `false` if an invalid combination is detected.
    ///
    /// Forbidden combinations:
    /// - `Merged` terminal + any non-Idle activity
    /// - `ResolveWait` + `Resolving` activity simultaneously
    /// - Any terminal state + active activity
    #[allow(dead_code)]
    pub fn invariants_hold(&self) -> bool {
        // Terminal changes must not have active activity.
        if self.is_terminal() && self.is_active() {
            return false;
        }
        // Base-lane wait states and matching active lane occupancy cannot coexist.
        if matches!(self.wait_state, WaitState::ResolveWait)
            && matches!(self.activity, ActivityState::Resolving)
        {
            return false;
        }
        if matches!(self.wait_state, WaitState::RejectWait)
            && matches!(self.activity, ActivityState::Rejecting)
        {
            return false;
        }
        true
    }

    /// Operation label the Apply lane renders for this change.
    ///
    /// `"commit"` while the ephemeral finalization subphase is active, `"apply"`
    /// otherwise. This is a *rendering* projection layered on top of the
    /// canonical `applying` status, which [`Self::display_status`] keeps
    /// returning unchanged throughout finalization.
    pub fn apply_operation_label(&self) -> &'static str {
        match self.commit_phase_attempt {
            Some(_) => "commit",
            None => "apply",
        }
    }

    /// Derive the display status string used by TUI and Web.
    ///
    /// Returns one of: "not queued", "queued", "blocked", "stalled", "preparing",
    /// "applying", "accepting", "rejecting", "archiving", "resolving", "merge wait",
    /// "resolve pending", "reject pending", "merged", "pushed", "error", "stopped".
    ///
    /// The ephemeral commit subphase deliberately does not appear here: it is
    /// presentation detail, and the canonical lifecycle stays `applying` for the
    /// whole finalization sequence.
    pub fn display_status(&self) -> &'static str {
        // Terminal states take precedence.
        match &self.terminal {
            TerminalState::Merged => return "merged",
            TerminalState::Pushed => return "pushed",
            TerminalState::Rejected(_) => return "rejected",
            TerminalState::Error(_) => return "error",
            TerminalState::Stopped => return "stopped",
            TerminalState::None => {}
        }
        // Active execution stages next.
        match self.activity {
            ActivityState::Preparing => return "preparing",
            ActivityState::Applying => return "applying",
            ActivityState::Accepting => return "accepting",
            ActivityState::Rejecting => return "rejecting",
            ActivityState::Archiving => return "archiving",
            ActivityState::Resolving => return "resolving",
            ActivityState::Idle => {}
        }
        // Wait conditions.
        match self.wait_state {
            WaitState::MergeWait => return "merge wait",
            WaitState::ResolveWait => return "resolve pending",
            WaitState::RejectWait => return "reject pending",
            // Dependency waits and validated external prerequisite waits share
            // the `blocked` word; `blocker_kind()` is what keeps them apart.
            WaitState::DependencyBlocked | WaitState::ExternalBlocked => return "blocked",
            WaitState::Stalled => return "stalled",
            WaitState::None => {}
        }
        // Queue intent.
        match self.queue_intent {
            QueueIntent::Queued => "queued",
            QueueIntent::NotQueued => "not queued",
        }
    }

    /// Derive the display color used by TUI status rendering.
    #[allow(dead_code)]
    pub fn display_color(&self) -> ratatui::style::Color {
        match self.display_status() {
            "not queued" => ratatui::style::Color::DarkGray,
            "queued" => ratatui::style::Color::Yellow,
            "blocked" => ratatui::style::Color::Gray,
            "stalled" => ratatui::style::Color::LightYellow,
            "preparing" => ratatui::style::Color::Green,
            "applying" => ratatui::style::Color::Cyan,
            "accepting" => ratatui::style::Color::LightGreen,
            "rejecting" => ratatui::style::Color::LightYellow,
            "archiving" => ratatui::style::Color::Magenta,
            "merged" => ratatui::style::Color::LightBlue,
            "rejected" => ratatui::style::Color::LightRed,
            "merge wait" => ratatui::style::Color::LightMagenta,
            "resolving" => ratatui::style::Color::LightCyan,
            "resolve pending" => ratatui::style::Color::Magenta,
            "reject pending" => ratatui::style::Color::LightMagenta,
            "error" => ratatui::style::Color::Red,
            "stopped" => ratatui::style::Color::DarkGray,
            _ => ratatui::style::Color::DarkGray,
        }
    }

    /// Returns the terminal error message when in error state.
    #[allow(dead_code)]
    pub fn error_message(&self) -> Option<&str> {
        match &self.terminal {
            TerminalState::Error(message) => Some(message.as_str()),
            _ => None,
        }
    }
}

// ============================================================================
// Reducer API types (Phase 2)
// ============================================================================

/// Commands that express user intent and drive state transitions via the reducer.
#[derive(Debug, Clone)]
pub enum ReducerCommand {
    /// Request a change to be added to the execution queue.
    AddToQueue(String),
    /// Explicitly retry a recoverable terminal-error change.
    RetryError(String),
    /// Request a change to be removed from the execution queue.
    RemoveFromQueue(String),
    /// Request merge resolution for a change in MergeWait or ResolveWait.
    ResolveMerge(String),
    /// Cancel a running or queued change and dequeue it back to not-queued.
    DequeueChange(String),
    /// Settle a change into the terminal `stopped` outcome.
    ///
    /// The difference from [`Self::DequeueChange`] is the row an observer is
    /// left with: a dequeued change is idle work the owner may admit again on
    /// its own, while a stopped change is a settled outcome only a new operator
    /// action can move. Targeted force-stop is the one path that produces it —
    /// killing a proposal outright is an operator verdict on that proposal, not
    /// a return to the queue.
    StopChange(String),
    /// Resume a change whose only terminal evidence is an operator stop.
    ///
    /// The counterpart of [`Self::StopChange`], and deliberately narrow: it is
    /// the *one* transition that may clear `TerminalState::Stopped`, and it
    /// clears nothing else. Only explicit Start intent in process mode
    /// `Stopped` submits it — a mark, a bulk mark, a re-mark, a refresh, or a
    /// mark-settlement deadline never does, because "this change is selected"
    /// is not "run this change again".
    ///
    /// [`Self::AddToQueue`] cannot express it: every terminal row is a no-op
    /// there, and widening that guard would let ordinary queue intent erase
    /// merged, pushed, rejected, or error evidence too.
    ResumeStopped(String),
}

/// Outcome of applying a reducer command.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum ReduceOutcome {
    /// The command produced a state change described by the effect.
    Changed(ReducerEffect),
    /// The command was a no-op (idempotent duplicate or invalid in current state).
    NoOp,
}

/// Side-effects produced by a successful reducer command.
#[derive(Debug, Clone)]
#[allow(clippy::enum_variant_names, dead_code)]
pub enum ReducerEffect {
    /// Queue intent was updated.
    QueueIntentSet {
        change_id: String,
        intent: QueueIntent,
    },
    /// Wait state was updated.
    WaitStateSet { change_id: String, wait: WaitState },
    /// Terminal state was set.
    TerminalStateSet {
        change_id: String,
        terminal: TerminalState,
    },
}

/// Shared state for orchestration operations.
///
/// This structure tracks:
/// - Which changes are pending, completed, or archived
/// - Apply counts per change
/// - Iteration counters and progress
#[derive(Debug, Clone)]
pub struct OrchestratorState {
    /// Change IDs captured at run start (snapshot).
    /// Only changes present in this snapshot will be processed.
    initial_change_ids: HashSet<String>,

    /// Changes that are still pending (not yet archived).
    pending_changes: HashSet<String>,

    /// Changes that have been archived.
    archived_changes: HashSet<String>,

    /// Apply counts per change (how many times each change has been applied).
    apply_counts: HashMap<String, u32>,

    /// Changes marked as stalled (failed due to no progress or blockers).
    stalled_change_ids: HashSet<String>,

    /// Changes skipped because one of their dependencies stalled.
    skipped_change_ids: HashSet<String>,

    /// Task progress per change (completed_tasks, total_tasks).
    task_progress: HashMap<String, (u32, u32)>,

    /// Error history per change for repeated failure detection.
    error_histories: HashMap<String, ErrorHistory>,

    /// Number of changes processed (archived).
    changes_processed: usize,

    /// Total number of changes at run start.
    total_changes: usize,

    /// Maximum iterations limit (0 = no limit).
    max_iterations: u32,

    /// Current iteration number.
    iteration: u32,

    /// Current change ID being processed.
    current_change_id: Option<String>,

    /// Reducer-owned runtime state per change.
    change_runtime: HashMap<String, ChangeRuntimeState>,

    /// Reducer-owned resolve-wait queue (FIFO list of change_ids awaiting resolve).
    resolve_wait_queue: Vec<String>,

    /// Reducer-owned reject-wait queue (FIFO list of change_ids awaiting rejection review).
    reject_wait_queue: Vec<String>,

    /// Changes stopped by the per-change Apply-dispatch ceiling, in observation
    /// order.
    ///
    /// Parallel execution has no return channel for a typed Apply outcome, so
    /// the budget owner's refusal is recorded here with its exact cumulative
    /// count. That keeps `iteration_limit` a typed run-level outcome instead of
    /// something a caller would have to re-derive by parsing an error string.
    /// Active-run memory like the rest of this reducer.
    apply_iteration_limits: Vec<ApplyIterationLimit>,
}

/// One change stopped by the configured Apply-dispatch ceiling.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplyIterationLimit {
    /// The change whose Apply budget was spent.
    pub change_id: String,
    /// Exact cumulative configured Apply dispatches reserved for that change.
    pub attempts: u32,
    /// The configured ceiling that refused the next dispatch.
    pub max: u32,
}

#[allow(dead_code)] // Public API for future use by TUI/Web states
impl OrchestratorState {
    /// Create a new orchestrator state with the given initial changes.
    pub fn new(change_ids: Vec<String>, max_iterations: u32) -> Self {
        let initial_set: HashSet<String> = change_ids.iter().cloned().collect();
        let pending_set = initial_set.clone();
        let total = change_ids.len();

        // Initialise each change with the "not queued + idle + no wait + no terminal" state.
        let change_runtime: HashMap<String, ChangeRuntimeState> = change_ids
            .iter()
            .map(|id| (id.clone(), ChangeRuntimeState::default()))
            .collect();

        Self {
            initial_change_ids: initial_set,
            pending_changes: pending_set,
            archived_changes: HashSet::new(),
            apply_counts: HashMap::new(),
            stalled_change_ids: HashSet::new(),
            skipped_change_ids: HashSet::new(),
            task_progress: HashMap::new(),
            error_histories: HashMap::new(),
            changes_processed: 0,
            total_changes: total,
            max_iterations,
            iteration: 0,
            current_change_id: None,
            change_runtime,
            resolve_wait_queue: Vec::new(),
            reject_wait_queue: Vec::new(),
            apply_iteration_limits: Vec::new(),
        }
    }

    /// Get the initial snapshot of change IDs.
    pub fn initial_change_ids(&self) -> &HashSet<String> {
        &self.initial_change_ids
    }

    /// Get the set of pending changes.
    pub fn pending_changes(&self) -> &HashSet<String> {
        &self.pending_changes
    }

    /// Get the set of archived changes.
    pub fn archived_changes(&self) -> &HashSet<String> {
        &self.archived_changes
    }

    /// Get stalled change IDs.
    pub fn stalled_change_ids(&self) -> &HashSet<String> {
        &self.stalled_change_ids
    }

    /// Get skipped change IDs.
    pub fn skipped_change_ids(&self) -> &HashSet<String> {
        &self.skipped_change_ids
    }

    /// Change IDs currently held by an in-memory Acceptance stall.
    ///
    /// This is the whole hold: nothing is persisted, so a restarted process
    /// returns an empty set and repository evidence alone decides the next
    /// action. Apply-origin and dependency blockers are deliberately excluded —
    /// only an Acceptance-phase blocker observation sets the flag.
    /// Changes held by a validated external prerequisite, whichever phase
    /// observed it.
    ///
    /// Ordinary dispatch must skip these. They are *not* dependency edges: a
    /// dependent proposal keeps its own dependency blocker kind, and unrelated
    /// ready changes stay eligible.
    pub fn externally_blocked_change_ids(&self) -> HashSet<String> {
        self.change_runtime
            .iter()
            .filter(|(_, rt)| rt.is_external_blocked())
            .map(|(id, _)| id.clone())
            .collect()
    }

    pub fn acceptance_stalled_change_ids(&self) -> HashSet<String> {
        self.change_runtime
            .iter()
            .filter(|(_, rt)| rt.is_acceptance_stalled())
            .map(|(change_id, _)| change_id.clone())
            .collect()
    }

    /// Mark a change as stalled.
    pub fn mark_stalled(&mut self, change_id: String) {
        self.stalled_change_ids.insert(change_id);
    }

    /// Record that the Apply-dispatch ceiling refused another dispatch.
    ///
    /// Repeated observations for the same change keep the first record: the
    /// exact count that first hit the ceiling is the one the finish hook
    /// reports.
    pub fn record_apply_iteration_limit(&mut self, change_id: &str, attempts: u32, max: u32) {
        if self
            .apply_iteration_limits
            .iter()
            .any(|record| record.change_id == change_id)
        {
            return;
        }
        self.apply_iteration_limits.push(ApplyIterationLimit {
            change_id: change_id.to_string(),
            attempts,
            max,
        });
    }

    /// Changes stopped by the Apply-dispatch ceiling, in observation order.
    pub fn apply_iteration_limits(&self) -> &[ApplyIterationLimit] {
        &self.apply_iteration_limits
    }

    /// Drop the Apply-dispatch ceiling record for one change.
    ///
    /// Returns true when a record was actually removed. Called from
    /// [`Self::retry_terminal_error`], so the diagnostic is consumed by the same
    /// explicit intent that consumes the terminal error it explains — and by
    /// nothing else.
    pub fn clear_apply_iteration_limit(&mut self, change_id: &str) -> bool {
        let before = self.apply_iteration_limits.len();
        self.apply_iteration_limits
            .retain(|record| record.change_id != change_id);
        self.apply_iteration_limits.len() != before
    }

    /// The typed Apply-dispatch ceiling record for one change, if it has one.
    ///
    /// Diagnostic evidence, never an operator-action gate: it answers why one
    /// invocation stopped, not whether a later explicit command may open a new
    /// one. Retry admission reads the target's own terminal-error evidence
    /// instead, so a record retained under a still-live persistent scheduler
    /// cannot make an explicit retry impossible.
    pub fn apply_iteration_limit(&self, change_id: &str) -> Option<&ApplyIterationLimit> {
        self.apply_iteration_limits
            .iter()
            .find(|record| record.change_id == change_id)
    }

    /// Finish status and Apply count a parallel run reports to `on_finish`.
    ///
    /// Parallel execution has no `LoopControl` return path, so this reducer is
    /// where the typed budget outcome crosses the boundary. Every parallel run
    /// boundary — `cflx run` and the TUI alike — derives the hook's status from
    /// this one observation instead of parsing an error string, so both report
    /// `iteration_limit` with the same exact cumulative count.
    pub fn parallel_finish_report(&self) -> (&'static str, u32) {
        match self.apply_iteration_limits.first() {
            Some(record) => ("iteration_limit", record.attempts),
            None => ("completed", 0),
        }
    }

    /// Mark a change as skipped.
    ///
    /// Returns true when the value was newly inserted.
    pub fn mark_skipped(&mut self, change_id: String) -> bool {
        self.skipped_change_ids.insert(change_id)
    }

    /// Clear transient counters for a stalled change.
    pub fn clear_stalled_change(&mut self, change_id: &str) {
        self.stalled_change_ids.remove(change_id);
        self.skipped_change_ids.remove(change_id);
        self.apply_counts.remove(change_id);
        if self.current_change_id.as_deref() == Some(change_id) {
            self.current_change_id = None;
        }
    }

    /// Get the number of changes processed.
    pub fn changes_processed(&self) -> usize {
        self.changes_processed
    }

    /// Get the total number of changes.
    pub fn total_changes(&self) -> usize {
        self.total_changes
    }

    /// Get the number of remaining changes.
    pub fn remaining_changes(&self) -> usize {
        self.pending_changes.len()
    }

    /// Get the current iteration number.
    pub fn iteration(&self) -> u32 {
        self.iteration
    }

    /// Get the maximum iterations limit.
    pub fn max_iterations(&self) -> u32 {
        self.max_iterations
    }

    /// Get the current change ID being processed.
    pub fn current_change_id(&self) -> Option<&String> {
        self.current_change_id.as_ref()
    }

    /// Get the apply count for a specific change.
    pub fn apply_count(&self, change_id: &str) -> u32 {
        *self.apply_counts.get(change_id).unwrap_or(&0)
    }

    /// Get the task progress for a specific change (completed_tasks, total_tasks).
    pub fn task_progress(&self, change_id: &str) -> (u32, u32) {
        *self.task_progress.get(change_id).unwrap_or(&(0, 0))
    }

    /// Update task progress for a change.
    pub fn set_task_progress(&mut self, change_id: String, completed: u32, total: u32) {
        self.task_progress.insert(change_id, (completed, total));
    }

    /// Check if a change is in the initial snapshot.
    pub fn is_in_snapshot(&self, change_id: &str) -> bool {
        self.initial_change_ids.contains(change_id)
    }

    /// Check if a change is pending.
    pub fn is_pending(&self, change_id: &str) -> bool {
        self.pending_changes.contains(change_id)
    }

    /// Check if a change is archived.
    pub fn is_archived(&self, change_id: &str) -> bool {
        self.archived_changes.contains(change_id)
    }

    /// Check if all changes are done.
    pub fn is_complete(&self) -> bool {
        self.pending_changes.is_empty()
    }

    /// Check if max iterations has been reached.
    pub fn is_iteration_limit_reached(&self) -> bool {
        self.max_iterations > 0 && self.iteration >= self.max_iterations
    }

    /// Check if we're approaching the iteration limit (80%).
    pub fn is_approaching_iteration_limit(&self) -> bool {
        if self.max_iterations == 0 {
            return false;
        }
        let threshold = (self.max_iterations as f32 * 0.8) as u32;
        self.iteration == threshold
    }

    /// Increment the iteration counter.
    pub fn increment_iteration(&mut self) {
        self.iteration += 1;
    }

    /// Set the current change being processed.
    pub fn set_current_change(&mut self, change_id: Option<String>) {
        self.current_change_id = change_id;
    }

    /// Increment the apply count for a change and return the new count.
    pub fn increment_apply_count(&mut self, change_id: &str) -> u32 {
        let count = self.apply_counts.entry(change_id.to_string()).or_insert(0);
        *count += 1;
        *count
    }

    /// Mark a change as archived.
    ///
    /// This:
    /// - Moves the change from pending to archived
    /// - Increments the changes_processed counter
    /// - Clears the current change if it matches
    /// - Removes apply count tracking
    pub fn mark_archived(&mut self, change_id: &str) {
        if self.pending_changes.remove(change_id) {
            self.archived_changes.insert(change_id.to_string());
            self.changes_processed += 1;
            self.apply_counts.remove(change_id);

            if self.current_change_id.as_deref() == Some(change_id) {
                self.current_change_id = None;
            }
        }
    }

    /// Add a new change dynamically (during execution).
    ///
    /// This is used for dynamic queue support in TUI mode.
    pub fn add_dynamic_change(&mut self, change_id: String) {
        if !self.initial_change_ids.contains(&change_id)
            && !self.pending_changes.contains(&change_id)
            && !self.archived_changes.contains(&change_id)
        {
            self.initial_change_ids.insert(change_id.clone());
            self.pending_changes.insert(change_id.clone());
            self.total_changes += 1;
            // Initialise reducer runtime state for newly discovered change.
            self.change_runtime.entry(change_id).or_default();
        }
    }

    // -----------------------------------------------------------------------
    // Reducer-owned runtime state accessors (Phase 1)
    // -----------------------------------------------------------------------

    /// Get the runtime state for a change, creating a default entry if absent.
    fn runtime_entry(&mut self, change_id: &str) -> &mut ChangeRuntimeState {
        self.change_runtime
            .entry(change_id.to_string())
            .or_default()
    }

    /// Every change the reducer currently tracks, sorted for determinism.
    ///
    /// This is the authoritative candidate set for an operation that addresses
    /// "all changes": it is the same map `display_status` answers from, so a
    /// bulk mutation can never classify a row the reducer does not know about.
    pub fn tracked_change_ids(&self) -> Vec<String> {
        let mut ids: Vec<String> = self.change_runtime.keys().cloned().collect();
        ids.sort();
        ids
    }

    /// Read-only access to the runtime state of a change.
    pub fn change_runtime(&self, change_id: &str) -> Option<&ChangeRuntimeState> {
        self.change_runtime.get(change_id)
    }

    /// Whether the reducer tracks this change at all.
    ///
    /// Distinct from `display_status(change_id) == "not queued"`, which is also
    /// what an untracked ID answers: a command that must refuse an unknown
    /// target cannot tell the two apart from the status string alone.
    pub fn is_tracked_change(&self, change_id: &str) -> bool {
        self.change_runtime.contains_key(change_id)
    }

    /// Derive the UI display status string for a change (Phase 1.4).
    pub fn display_status(&self, change_id: &str) -> &'static str {
        match self.change_runtime.get(change_id) {
            Some(rt) => rt.display_status(),
            None => "not queued",
        }
    }

    /// Return true if the change is actively executing (applying/accepting/archiving/resolving).
    /// Used for parallel slot accounting (Phase 1.5).
    pub fn is_active_change(&self, change_id: &str) -> bool {
        self.change_runtime
            .get(change_id)
            .map(|rt| rt.is_active())
            .unwrap_or(false)
    }

    /// Return true when any change is running agent-driven workspace execution.
    ///
    /// Applying, accepting, and archiving are the activities backed by an agent
    /// command process. Resolving and rejecting occupy the base-mutating lane and
    /// are scheduler-owned shutdown work, so they are deliberately excluded here:
    /// they must never justify a force-stopped-process claim.
    pub fn is_agent_execution_active(&self) -> bool {
        self.change_runtime.values().any(|rt| {
            matches!(
                rt.activity,
                ActivityState::Applying | ActivityState::Accepting | ActivityState::Archiving
            ) && !rt.is_terminal()
        })
    }

    /// Return true when any change is currently in resolving activity.
    pub fn is_resolving_active(&self) -> bool {
        self.change_runtime
            .values()
            .any(|rt| matches!(rt.activity, ActivityState::Resolving) && !rt.is_terminal())
    }

    /// Return true when any change is currently in rejecting activity.
    pub fn is_rejecting_active(&self) -> bool {
        self.change_runtime
            .values()
            .any(|rt| matches!(rt.activity, ActivityState::Rejecting) && !rt.is_terminal())
    }

    /// Return true when another change occupies the post-archive merge/reject lane.
    pub fn has_other_post_archive_lane_blocker(&self, change_id: &str) -> bool {
        self.change_runtime.iter().any(|(id, rt)| {
            id != change_id
                && matches!(
                    rt.activity,
                    ActivityState::Resolving | ActivityState::Rejecting
                )
                && !rt.is_terminal()
        })
    }

    /// Return the non-terminal change that occupies the base-mutating lane, if any.
    pub fn base_mutating_lane_occupant(&self) -> Option<String> {
        self.change_runtime.iter().find_map(|(id, rt)| {
            if matches!(
                rt.activity,
                ActivityState::Resolving | ActivityState::Rejecting
            ) && !rt.is_terminal()
            {
                Some(id.clone())
            } else {
                None
            }
        })
    }

    /// Return true if the single base-mutating lane is currently occupied.
    pub fn is_base_mutating_lane_occupied(&self) -> bool {
        self.base_mutating_lane_occupant().is_some()
    }

    /// Verify global reducer invariants that span multiple changes.
    pub fn global_invariants_hold(&self) -> bool {
        let lane_occupants = self
            .change_runtime
            .values()
            .filter(|rt| {
                matches!(
                    rt.activity,
                    ActivityState::Resolving | ActivityState::Rejecting
                ) && !rt.is_terminal()
            })
            .count();
        lane_occupants <= 1
            && self
                .change_runtime
                .values()
                .all(ChangeRuntimeState::invariants_hold)
    }

    /// Return change IDs that are currently waiting for manual merge resolution.
    pub fn merge_wait_change_ids(&self) -> Vec<String> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| {
                if matches!(rt.wait_state, WaitState::MergeWait) && !rt.is_terminal() {
                    Some(id.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Return change IDs that are currently waiting for scheduler-owned resolve/merge retry.
    pub fn resolve_wait_change_ids(&self) -> Vec<String> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| {
                if matches!(rt.wait_state, WaitState::ResolveWait) && !rt.is_terminal() {
                    Some(id.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    fn remove_from_resolve_wait_queue(&mut self, change_id: &str) {
        self.resolve_wait_queue.retain(|id| id != change_id);
    }

    fn remove_from_reject_wait_queue(&mut self, change_id: &str) {
        self.reject_wait_queue.retain(|id| id != change_id);
    }

    fn clear_base_mutating_wait_queues(&mut self, change_id: &str) {
        self.remove_from_resolve_wait_queue(change_id);
        self.remove_from_reject_wait_queue(change_id);
    }

    fn enqueue_unique_resolve_wait(&mut self, change_id: &str) {
        if !self.resolve_wait_queue.iter().any(|id| id == change_id) {
            self.resolve_wait_queue.push(change_id.to_string());
        }
    }

    fn enqueue_unique_reject_wait(&mut self, change_id: &str) {
        if !self.reject_wait_queue.iter().any(|id| id == change_id) {
            self.reject_wait_queue.push(change_id.to_string());
        }
    }

    /// Clear reducer-owned resolve retry intent for a change after repository-visible
    /// merge success or stale already-merged detection.
    ///
    /// Releasing a consumed reservation is bookkeeping, never an outcome.
    /// `ReducerCommand::ResolveMerge` leaves `QueueIntent::NotQueued` behind the
    /// `ResolveWait`, so dropping the wait on its own would expose an idle
    /// `not queued` row for a change that is still archived and unmerged. An
    /// entry with no terminal state, no activity, and no queue intent therefore
    /// falls back to the retryable manual `merge wait` it was promoted from;
    /// a later success event supersedes that safely.
    pub fn clear_resolve_wait_intent(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        if matches!(rt.wait_state, WaitState::ResolveWait) {
            rt.wait_state = if rt.is_terminal()
                || rt.dequeued
                || rt.is_active()
                || matches!(rt.queue_intent, QueueIntent::Queued)
            {
                WaitState::None
            } else {
                WaitState::MergeWait
            };
            rt.clear_blocked_metadata();
        }
        self.remove_from_resolve_wait_queue(change_id);
    }

    /// Settle a stale deferred resolve retry from base-branch tree evidence.
    ///
    /// This is the typed transition the scheduler applies at the stale-retry
    /// boundary. Terminal `merged` is recorded *before* the retry reservation is
    /// dropped, so no reader observes an idle `not queued` gap between accepted
    /// retry intent and the settled outcome. Evidence that is absent or
    /// unreadable fails closed to retryable manual `merge wait`; only proven
    /// base integration may report success.
    ///
    /// Purely a state transition: it reads no repository content and mutates no
    /// index, worktree, or file.
    pub fn settle_stale_resolve_retry(
        &mut self,
        change_id: &str,
        evidence: StaleResolveEvidence,
    ) -> StaleResolveSettlement {
        match evidence {
            StaleResolveEvidence::Proven => {
                if !self
                    .runtime_entry(change_id)
                    .can_success_supersede_terminal()
                {
                    self.clear_base_mutating_wait_queues(change_id);
                    return StaleResolveSettlement::AlreadySettled;
                }
                // Terminal first, membership second.
                self.transition_change_to_merged(change_id);
                StaleResolveSettlement::Merged
            }
            StaleResolveEvidence::Absent | StaleResolveEvidence::Unknown => {
                let rt = self.runtime_entry(change_id);
                if rt.is_terminal() || rt.dequeued {
                    self.clear_base_mutating_wait_queues(change_id);
                    return StaleResolveSettlement::AlreadySettled;
                }
                rt.activity = ActivityState::Idle;
                rt.wait_state = WaitState::MergeWait;
                rt.queue_intent = QueueIntent::NotQueued;
                rt.clear_blocked_metadata();
                self.clear_base_mutating_wait_queues(change_id);
                StaleResolveSettlement::MergeWaitRetained
            }
        }
    }

    /// Return change IDs that are currently waiting for scheduler-owned rejection review.
    pub fn reject_wait_change_ids(&self) -> Vec<String> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| {
                if matches!(rt.wait_state, WaitState::RejectWait) && !rt.is_terminal() {
                    Some(id.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Mark a change as waiting for rejection review after a rejection proposal handoff.
    pub fn mark_reject_wait(&mut self, change_id: &str) {
        let lane_blocked = self.has_other_post_archive_lane_blocker(change_id);
        let rt = self.runtime_entry(change_id);
        if rt.is_terminal() || rt.dequeued {
            return;
        }
        rt.activity = if lane_blocked {
            ActivityState::Idle
        } else {
            ActivityState::Rejecting
        };
        rt.wait_state = if lane_blocked {
            WaitState::RejectWait
        } else {
            WaitState::None
        };
        rt.clear_blocked_metadata();
        self.remove_from_resolve_wait_queue(change_id);
        if lane_blocked {
            self.enqueue_unique_reject_wait(change_id);
        } else {
            self.remove_from_reject_wait_queue(change_id);
        }
    }

    /// Clear reducer-owned rejection-review wait intent.
    pub fn clear_reject_wait_intent(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        if matches!(rt.wait_state, WaitState::RejectWait) {
            rt.wait_state = WaitState::None;
            rt.clear_blocked_metadata();
        }
        self.remove_from_reject_wait_queue(change_id);
    }

    /// Release a promoted base-mutating retry occupant after a non-terminal retry outcome.
    ///
    /// Spawned ResolveWait/RejectWait retries promote a queued waiter by clearing its
    /// wait state and marking it Resolving/Rejecting. If the detached retry then
    /// defers auto-resumably or fails before a terminal reducer event, the lane must
    /// be returned to its reducer-owned wait state so later completion triggers can
    /// promote it again. Terminal entries, non-occupants, and unsupported wait kinds
    /// are left unchanged.
    pub fn release_base_mutating_lane_after_retry(
        &mut self,
        change_id: &str,
        wait_state: WaitState,
    ) -> bool {
        if !matches!(wait_state, WaitState::ResolveWait | WaitState::RejectWait) {
            return false;
        }

        let rt = self.runtime_entry(change_id);
        if rt.is_terminal()
            || !matches!(
                rt.activity,
                ActivityState::Resolving | ActivityState::Rejecting
            )
        {
            return false;
        }

        rt.activity = ActivityState::Idle;
        rt.wait_state = wait_state.clone();
        rt.clear_blocked_metadata();
        self.clear_base_mutating_wait_queues(change_id);
        match wait_state {
            WaitState::ResolveWait => self.enqueue_unique_resolve_wait(change_id),
            WaitState::RejectWait => self.enqueue_unique_reject_wait(change_id),
            _ => unreachable!("wait_state was validated above"),
        }
        true
    }

    /// Abandon a promoted base-mutating retry occupant after a give-up outcome.
    ///
    /// Unlike `release_base_mutating_lane_after_retry`, this does not restore the
    /// original wait state or re-enqueue the change. Give-up paths have determined
    /// there is no live retry work left, so the lane is simply released.
    pub fn abandon_base_mutating_lane_occupant(&mut self, change_id: &str) -> bool {
        let rt = self.runtime_entry(change_id);
        if rt.is_terminal()
            || !matches!(
                rt.activity,
                ActivityState::Resolving | ActivityState::Rejecting
            )
        {
            return false;
        }

        rt.activity = ActivityState::Idle;
        rt.wait_state = WaitState::None;
        rt.clear_blocked_metadata();
        self.clear_base_mutating_wait_queues(change_id);
        true
    }

    /// Promote exactly one pending base-mutating operation when the lane is free.
    /// Resolve waits take priority over reject waits to preserve existing merge retry semantics.
    pub fn promote_next_base_mutating_lane_waiter(&mut self) -> Option<(String, WaitState)> {
        if self.is_base_mutating_lane_occupied() {
            return None;
        }

        while let Some(change_id) = self.resolve_wait_queue.first().cloned() {
            self.resolve_wait_queue.remove(0);
            let rt = self.runtime_entry(&change_id);
            if !rt.is_terminal() && matches!(rt.wait_state, WaitState::ResolveWait) {
                rt.wait_state = WaitState::None;
                rt.activity = ActivityState::Resolving;
                rt.clear_blocked_metadata();
                return Some((change_id, WaitState::ResolveWait));
            }
        }

        while let Some(change_id) = self.reject_wait_queue.first().cloned() {
            self.reject_wait_queue.remove(0);
            let rt = self.runtime_entry(&change_id);
            if !rt.is_terminal() && matches!(rt.wait_state, WaitState::RejectWait) {
                rt.wait_state = WaitState::None;
                rt.activity = ActivityState::Rejecting;
                rt.clear_blocked_metadata();
                return Some((change_id, WaitState::RejectWait));
            }
        }

        None
    }

    /// Whether `change_id` currently carries an unconsumed manual resolve retry
    /// permission.
    ///
    /// Read — never taken — at promotion, so a dispatch that is deferred by
    /// base-lane occupancy leaves the permission for the auto-resumed retry.
    pub fn has_manual_resolve_retry(&self, change_id: &str) -> bool {
        self.change_runtime
            .get(change_id)
            .is_some_and(|rt| rt.manual_resolve_retry)
    }

    /// Consume `change_id`'s manual resolve retry permission.
    ///
    /// Answers what the permission was, and clears it, so the next ordinary
    /// scheduled attempt observes the unchanged generic preflight.
    pub fn consume_manual_resolve_retry(&mut self, change_id: &str) -> bool {
        match self.change_runtime.get_mut(change_id) {
            Some(rt) => std::mem::take(&mut rt.manual_resolve_retry),
            None => false,
        }
    }

    /// Return change IDs that still carry queued intent and are not terminal.
    ///
    /// Scheduler reconciliation uses this as reducer-visible source of truth for
    /// queue intent, then intersects with loadable OpenSpec changes and runtime
    /// active-state checks before dispatch/analysis.
    pub fn queued_change_ids(&self) -> Vec<String> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| {
                if matches!(rt.queue_intent, QueueIntent::Queued) && !rt.is_terminal() {
                    Some(id.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Return change IDs currently considered active by reducer runtime state.
    pub fn active_change_ids(&self) -> Vec<String> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| {
                if rt.is_active() {
                    Some(id.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Return a snapshot of display status strings for all known changes.
    /// Used by the TUI to sync `ChangeState.queue_status` from the reducer.
    pub fn all_display_statuses(&self) -> HashMap<String, &'static str> {
        self.change_runtime
            .iter()
            .map(|(id, rt)| (id.clone(), rt.display_status()))
            .collect()
    }

    /// Ephemeral Apply-lane operation label for every known change.
    ///
    /// `"commit"` only while a finalization subphase is active. Frontends read
    /// this for rendering; nothing in the scheduler, resume router, or gating
    /// logic may consult it.
    pub fn all_apply_operation_labels(&self) -> HashMap<String, &'static str> {
        self.change_runtime
            .iter()
            .map(|(id, rt)| (id.clone(), rt.apply_operation_label()))
            .collect()
    }

    /// Reducer-retained final diagnostics for every change in
    /// [`TerminalState::Error`].
    ///
    /// Sanitized with the same helper the `/api/v2` `error_detail` projection
    /// uses, so the diagnostic a TUI row shows and the one a remote client reads
    /// are the same text rather than two independently derived strings. A change
    /// that is not in error contributes no entry at all — absence is what the
    /// frontends turn into their explicit "unavailable" fallback.
    pub fn all_error_details(&self) -> HashMap<String, String> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| {
                rt.error_message()
                    .map(|message| (id.clone(), crate::events::sanitize_detail(message)))
            })
            .collect()
    }

    /// Reducer-derived blocker views for every change currently blocked or
    /// stalled.
    ///
    /// This is the single source TUI, WebSocket/API, and the dashboard read, so
    /// no surface has to re-derive `blocked` versus `stalled` — or the blocker
    /// kind — from filenames, prose, or task text.
    pub fn all_blocker_views(&self) -> HashMap<String, BlockerView> {
        self.change_runtime
            .iter()
            .filter_map(|(id, rt)| rt.blocker_view().map(|view| (id.clone(), view)))
            .collect()
    }

    /// Reducer-derived blocker view for one change.
    pub fn blocker_view(&self, change_id: &str) -> Option<BlockerView> {
        self.change_runtime
            .get(change_id)
            .and_then(ChangeRuntimeState::blocker_view)
    }

    /// Reconcile the current unresolved dependency set for one change.
    ///
    /// The scheduler calls this on every coherent dependency classification,
    /// whether or not the edge-triggered `DependencyBlocked` diagnostic was
    /// suppressed as a duplicate. Deduplication decides whether an *operator
    /// diagnostic* is worth emitting again; it must never decide whether the
    /// current blocker exists, or a refreshed, replaced, or newly built reducer
    /// would report an unresolved dependency wait as plain `queued`.
    ///
    /// Queue intent is deliberately untouched: a dependency wait excludes a
    /// change from dispatch and never revokes admitted work.
    ///
    /// Returns `true` when the projection changed.
    pub fn reconcile_dependency_blocker(
        &mut self,
        change_id: &str,
        dependency_ids: &[String],
    ) -> bool {
        let rt = self.runtime_entry(change_id);
        // Exactly the guard the `DependencyBlocked` event applies, so the
        // reconciliation path and the transition path can never disagree about
        // which rows may carry a dependency wait.
        if rt.is_terminal() || rt.is_active() {
            return false;
        }
        rt.reconcile_dependency_blocker(dependency_ids)
    }

    /// Clear a dependency wait once classification proved every dependency resolved.
    ///
    /// Only a dependency wait is cleared: an external prerequisite, an
    /// acceptance stall, or a merge wait belongs to another owner, and dropping
    /// it here would let dependency evidence erase an unrelated hold.
    ///
    /// Returns `true` when a dependency wait was actually cleared.
    pub fn clear_dependency_blocker(&mut self, change_id: &str) -> bool {
        let Some(rt) = self.change_runtime.get_mut(change_id) else {
            return false;
        };
        if !matches!(rt.wait_state, WaitState::DependencyBlocked) {
            return false;
        }
        rt.wait_state = WaitState::None;
        rt.clear_blocked_metadata();
        true
    }

    /// Return true if the change has reached a terminal state.
    pub fn is_terminal_change(&self, change_id: &str) -> bool {
        self.change_runtime
            .get(change_id)
            .map(|rt| rt.is_terminal())
            .unwrap_or(false)
    }

    /// Remove a change from pending (e.g., due to failure).
    pub fn remove_from_pending(&mut self, change_id: &str) {
        self.pending_changes.remove(change_id);
        if self.current_change_id.as_deref() == Some(change_id) {
            self.current_change_id = None;
        }
    }

    /// Remove a change from pending and decrement total_changes.
    ///
    /// Returns true when the change was pending and removed.
    pub fn drop_pending_change(&mut self, change_id: &str) -> bool {
        let removed = self.pending_changes.remove(change_id);
        if removed {
            self.total_changes = self.total_changes.saturating_sub(1);
        }
        if self.current_change_id.as_deref() == Some(change_id) {
            self.current_change_id = None;
        }
        removed
    }

    /// Clear all pending changes.
    pub fn clear_pending_changes(&mut self) {
        self.pending_changes.clear();
    }

    /// Record an error and return whether circuit breaker should trip.
    pub fn record_error_and_check_circuit_breaker(
        &mut self,
        change_id: &str,
        error: &str,
        config: CircuitBreakerConfig,
    ) -> bool {
        let history = self
            .error_histories
            .entry(change_id.to_string())
            .or_insert_with(|| ErrorHistory::new(config.clone()));

        history.record_error(error);
        history.detect_same_error()
    }

    /// Return the most recent normalized error for a change.
    pub fn last_error(&self, change_id: &str) -> Option<&str> {
        self.error_histories
            .get(change_id)
            .and_then(ErrorHistory::last_error)
    }

    /// Clear error history for a change.
    pub fn clear_error_history(&mut self, change_id: &str) {
        self.error_histories.remove(change_id);
    }

    /// Return true when a final terminal state must stop ordinary apply/archive dispatch.
    ///
    /// Recoverable terminal errors intentionally remain separate: they are terminal for
    /// slot/accounting purposes, but can only become dispatchable through an explicit
    /// `ReducerCommand::RetryError` transition.
    pub fn is_final_terminal_dispatch_stop(&self, change_id: &str) -> bool {
        self.change_runtime
            .get(change_id)
            .map(|rt| {
                matches!(
                    rt.terminal,
                    TerminalState::Merged | TerminalState::Pushed | TerminalState::Rejected(_)
                )
            })
            .unwrap_or(false)
    }

    /// Return true when current reducer intent still admits `change_id` as ordinary queued work.
    ///
    /// This is the revocation check a scheduler wake-up hint must pass before it
    /// is treated as work. `RemoveFromQueue` and `DequeueChange` clear queue
    /// intent immediately, so a dynamic-queue entry left over from an earlier
    /// accepted addition cannot reacquire the change; an explicit `AddToQueue`
    /// or `RetryError` restores eligibility.
    ///
    /// A change the reducer has never seen carries no execution intent at all, so
    /// it is not eligible either. Every accepted path into ordinary work —
    /// start, `AddToQueue`, `RetryError`, and catalog registration through
    /// `add_dynamic_change` — records reducer runtime state before any scheduler
    /// wake-up hint is published, so "unknown to the reducer" cannot describe
    /// work an operator asked for. Treating unknown as admissible would let any
    /// ID that reaches the wake-up channel be resolved from the catalog and
    /// executed without intent, which is the bypass this predicate exists to
    /// close. Catalog membership alone still is not eligibility: a registered
    /// change stays `QueueIntent::NotQueued` until an explicit command.
    pub fn is_ordinary_queue_eligible(&self, change_id: &str) -> bool {
        match self.change_runtime.get(change_id) {
            None => false,
            Some(rt) => {
                !rt.is_terminal()
                    && !rt.dequeued
                    && (rt.is_active() || matches!(rt.queue_intent, QueueIntent::Queued))
            }
        }
    }

    /// Set form of [`Self::is_ordinary_queue_eligible`].
    ///
    /// A scheduler evaluation decides hint admission, queue reconciliation, and
    /// queue classification for many IDs at once. Capturing the eligible set from
    /// one read keeps every one of those decisions on the same reducer revision;
    /// an ID missing from the set is exactly the `false` the per-ID predicate
    /// returns, including for an ID the reducer has never seen.
    pub fn ordinary_queue_eligible_change_ids(&self) -> HashSet<String> {
        self.change_runtime
            .keys()
            .filter(|id| self.is_ordinary_queue_eligible(id))
            .cloned()
            .collect()
    }

    /// Set form of [`Self::is_final_terminal_dispatch_stop`].
    pub fn final_terminal_dispatch_stop_change_ids(&self) -> HashSet<String> {
        self.change_runtime
            .keys()
            .filter(|id| self.is_final_terminal_dispatch_stop(id))
            .cloned()
            .collect()
    }

    /// Change IDs whose admitted lifecycle has settled.
    ///
    /// The scheduler's concurrency accounting gives one admitted change one slot
    /// from workspace admission through merge and resolve settlement, so it needs
    /// a single vocabulary for "this lifecycle is over": merged, pushed,
    /// rejected, a terminal error awaiting explicit retry, and an explicit
    /// stop/dequeue are all settlements that release the slot.
    ///
    /// Deliberately positive evidence only. Absence of wait or queue intent is
    /// not settlement — a change between archive and background merge carries
    /// neither — so nothing here is derived from what a row is *not*.
    pub fn settled_lifecycle_change_ids(&self) -> HashSet<String> {
        self.change_runtime
            .iter()
            .filter(|(_, rt)| rt.is_terminal())
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Set form of [`Self::is_terminal_error_change`].
    pub fn terminal_error_change_ids(&self) -> HashSet<String> {
        self.change_runtime
            .iter()
            .filter(|(_, rt)| matches!(rt.terminal, TerminalState::Error(_)))
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Active change IDs whose display status is `resolving`.
    pub fn resolving_change_ids(&self) -> HashSet<String> {
        self.active_change_ids()
            .into_iter()
            .filter(|id| self.display_status(id) == "resolving")
            .collect()
    }

    /// Return true when a recoverable terminal error is currently gating ordinary apply dispatch.
    pub fn is_terminal_error_change(&self, change_id: &str) -> bool {
        self.change_runtime
            .get(change_id)
            .map(|rt| matches!(rt.terminal, TerminalState::Error(_)))
            .unwrap_or(false)
    }

    /// Return true when the *only* thing holding `change_id` back is an operator stop.
    ///
    /// Read-only, and the authority Start admission classifies a preserved mark
    /// against. Every clause is a separate refusal rather than a spelling of
    /// `display_status == "stopped"`:
    ///
    /// - the terminal outcome is `Stopped`, so Error, rejected, merged, and
    ///   pushed evidence keeps its own explicit route and is never resumed here;
    /// - queue intent is the `NotQueued` the stop itself produced, so a row an
    ///   unrelated path already re-admitted is not resumed a second time;
    /// - activity is idle and no wait, dependency hold, or stall is recorded
    ///   underneath the stop, so the stop is the whole reason the row is parked.
    ///
    /// A change the reducer has never seen carries no stop evidence either, and
    /// is not resumable.
    pub fn is_resumable_stopped(&self, change_id: &str) -> bool {
        self.change_runtime
            .get(change_id)
            .map(|rt| {
                matches!(rt.terminal, TerminalState::Stopped)
                    && matches!(rt.queue_intent, QueueIntent::NotQueued)
                    && matches!(rt.activity, ActivityState::Idle)
                    && matches!(rt.wait_state, WaitState::None)
            })
            .unwrap_or(false)
    }

    /// Clear an operator stop and restore ordinary queued intent.
    ///
    /// The only reducer-owned transition that may turn `TerminalState::Stopped`
    /// back into ordinary dispatch eligibility, and it moves exactly the state
    /// the stop itself produced: the terminal classification, the dequeue guard
    /// that keeps late events from reactivating the row, and the queue intent
    /// the stop cleared. Any other terminal outcome is refused as a no-op, so a
    /// resume can never erase Error, rejected, merged, or pushed evidence.
    ///
    /// Deliberately narrower than [`Self::retry_terminal_error`]: a stop is not
    /// a failure, so the change's error history and its retained Apply
    /// iteration-limit diagnostic explain something this command did not
    /// consume and are left exactly as they were. Scheduler-owned stall
    /// membership *is* cleared, because it is run-scoped bookkeeping that would
    /// otherwise keep skipping a row the operator just resumed.
    pub fn resume_stopped_change(&mut self, change_id: &str) -> ReduceOutcome {
        if !self.is_resumable_stopped(change_id) {
            return ReduceOutcome::NoOp;
        }
        {
            let rt = self.runtime_entry(change_id);
            rt.terminal = TerminalState::None;
            rt.clear_activity_wait_and_blocker();
            rt.queue_intent = QueueIntent::Queued;
            rt.dequeued = false;
            rt.observation = WorkspaceObservation::None;
            rt.commit_phase_attempt = None;
        }
        self.clear_stalled_change(change_id);
        self.clear_base_mutating_wait_queues(change_id);
        self.add_dynamic_change(change_id.to_string());
        ReduceOutcome::Changed(ReducerEffect::QueueIntentSet {
            change_id: change_id.to_string(),
            intent: QueueIntent::Queued,
        })
    }

    /// Clear a recoverable terminal error and restore ordinary queued retry intent.
    ///
    /// This is the only reducer-owned transition that may turn `TerminalState::Error`
    /// back into apply-dispatch eligibility. Final terminal states remain immutable.
    ///
    /// Reached only from `ReducerCommand::RetryError`, which only explicit retry
    /// intent — individual retry, bulk retry, retry-class Start, or the explicit
    /// per-target terminal-error queue alias — ever submits. That is what makes
    /// this the right place to consume the change's retained Apply
    /// iteration-limit diagnostic: the record stays observable for exactly as
    /// long as the terminal error it explains, and no automatic path can retire
    /// either one.
    pub fn retry_terminal_error(&mut self, change_id: &str) -> ReduceOutcome {
        {
            let rt = self.runtime_entry(change_id);
            if !matches!(rt.terminal, TerminalState::Error(_)) {
                return ReduceOutcome::NoOp;
            }
            rt.terminal = TerminalState::None;
            rt.clear_activity_wait_and_blocker();
            rt.queue_intent = QueueIntent::Queued;
            rt.dequeued = false;
            rt.observation = WorkspaceObservation::None;
        }
        self.clear_apply_iteration_limit(change_id);
        self.clear_stalled_change(change_id);
        self.clear_error_history(change_id);
        self.clear_base_mutating_wait_queues(change_id);
        self.add_dynamic_change(change_id.to_string());
        ReduceOutcome::Changed(ReducerEffect::QueueIntentSet {
            change_id: change_id.to_string(),
            intent: QueueIntent::Queued,
        })
    }

    // -----------------------------------------------------------------------
    // Reducer API (Phase 2)
    // -----------------------------------------------------------------------

    fn transition_change_to_dequeued(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        rt.terminal = TerminalState::None;
        rt.clear_activity_wait_and_blocker();
        rt.queue_intent = QueueIntent::NotQueued;
        rt.dequeued = true;
        // Cancellation can arrive anywhere inside finalization, including
        // before any terminal commit-phase event exists to observe, so the
        // ephemeral `[commit]` presentation is cleared here rather than being
        // left for a sequence that may never complete.
        rt.commit_phase_attempt = None;
        self.clear_base_mutating_wait_queues(change_id);
    }

    /// Reconcile reducer-owned transient state at a run's terminal stop boundary.
    ///
    /// The scheduler has already reached its cancellation-safe barrier by the
    /// time process-level `Stopped` is reduced, so any row still carrying
    /// activity, queue intent, or a wait/hold was interrupted by that stop and
    /// no longer has an owner. Each such row returns to the same non-terminal
    /// idle, not-queued shape an explicit dequeue produces, including the
    /// process-local dequeue guard that keeps a late lifecycle event or a
    /// same-process workspace observation from reactivating it before an
    /// explicit requeue.
    ///
    /// Deliberately *not* a per-change terminal outcome: a process stop is not a
    /// change result. Fresh idle rows were never part of the stopped run, and an
    /// existing terminal outcome — including recoverable `Error` — is a fact the
    /// stop must not erase.
    fn on_run_stopped(&mut self) {
        let interrupted: Vec<String> = self
            .change_runtime
            .iter()
            .filter(|(_, rt)| {
                !rt.is_terminal()
                    && (rt.is_active()
                        || matches!(rt.queue_intent, QueueIntent::Queued)
                        || !matches!(rt.wait_state, WaitState::None))
            })
            .map(|(change_id, _)| change_id.clone())
            .collect();

        for change_id in interrupted {
            self.transition_change_to_dequeued(&change_id);
            // Scheduler-owned stall/skip membership belongs to the run that just
            // ended; the retry budget it gates is re-derived from the workspace.
            self.stalled_change_ids.remove(&change_id);
            self.skipped_change_ids.remove(&change_id);
            if self.current_change_id.as_deref() == Some(change_id.as_str()) {
                self.current_change_id = None;
            }
        }
    }

    fn transition_change_to_stopped(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        rt.transition_to_terminal(TerminalState::Stopped);
        rt.queue_intent = QueueIntent::NotQueued;
        rt.commit_phase_attempt = None;
        self.clear_base_mutating_wait_queues(change_id);
    }

    fn transition_change_to_error(&mut self, change_id: &str, error: String) {
        let rt = self.runtime_entry(change_id);
        if !rt.is_terminal() {
            rt.transition_to_terminal(TerminalState::Error(error));
        }
        // Unconditional: a row that was already terminal must not keep
        // rendering a commit subphase either.
        rt.commit_phase_attempt = None;
        self.clear_base_mutating_wait_queues(change_id);
    }

    fn transition_change_to_merged(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        rt.transition_to_terminal(TerminalState::Merged);
        rt.queue_intent = QueueIntent::NotQueued;
        self.clear_base_mutating_wait_queues(change_id);
    }

    fn transition_change_to_stalled(
        &mut self,
        change_id: &str,
        blocker_reason: impl Into<String>,
        unblock_metadata: impl Into<String>,
        worktree_snapshot: impl Into<String>,
    ) {
        self.runtime_entry(change_id).transition_to_stalled(
            blocker_reason,
            unblock_metadata,
            worktree_snapshot,
        );
    }

    fn clear_recoverable_terminal_for_success(rt: &mut ChangeRuntimeState) -> bool {
        if rt.can_success_supersede_terminal() {
            rt.terminal = TerminalState::None;
            rt.clear_activity_wait_and_blocker();
            true
        } else {
            false
        }
    }

    fn apply_add_to_queue_command(&mut self, change_id: String) -> ReduceOutcome {
        self.clear_stalled_change(&change_id);
        {
            let rt = self.runtime_entry(&change_id);
            if rt.is_terminal() {
                return ReduceOutcome::NoOp;
            }
            // An explicit operator retry always releases a blocked/stalled hold
            // so the held phase can run again. The new execution result — not
            // the preserved metadata — is what reclassifies the change.
            if !rt.dequeued
                && !matches!(
                    rt.wait_state,
                    WaitState::Stalled | WaitState::ExternalBlocked
                )
                && (rt.is_active() || rt.queue_intent == QueueIntent::Queued)
            {
                return ReduceOutcome::NoOp;
            }
            rt.dequeued = false;
            rt.queue_intent = QueueIntent::Queued;
            rt.wait_state = WaitState::None;
            rt.clear_blocked_metadata();
        }
        self.clear_base_mutating_wait_queues(&change_id);
        self.add_dynamic_change(change_id.clone());
        ReduceOutcome::Changed(ReducerEffect::QueueIntentSet {
            change_id,
            intent: QueueIntent::Queued,
        })
    }

    fn apply_remove_from_queue_command(&mut self, change_id: String) -> ReduceOutcome {
        let rt = self.runtime_entry(&change_id);
        if rt.queue_intent == QueueIntent::NotQueued {
            return ReduceOutcome::NoOp;
        }
        rt.queue_intent = QueueIntent::NotQueued;
        ReduceOutcome::Changed(ReducerEffect::QueueIntentSet {
            change_id,
            intent: QueueIntent::NotQueued,
        })
    }

    fn apply_resolve_merge_command(&mut self, change_id: String) -> ReduceOutcome {
        {
            let rt = self.runtime_entry(&change_id);
            if !matches!(rt.wait_state, WaitState::MergeWait | WaitState::ResolveWait) {
                // TUI/manual resolve commands are already gated by a visible
                // `merge wait` row. In the observed stuck case the visible row
                // can be reconstructed from archive-complete workspace evidence
                // while the reducer still shows the row as idle. Treat explicit
                // operator retry there as scheduler-owned merge retry intent, but
                // continue to reject permanent terminal states such as Merged or
                // Rejected so stale clicks cannot reintroduce resolve work.
                if matches!(rt.activity, ActivityState::Idle)
                    && matches!(rt.terminal, TerminalState::None)
                {
                    rt.terminal = TerminalState::None;
                    rt.wait_state = WaitState::MergeWait;
                } else {
                    return ReduceOutcome::NoOp;
                }
            }
            rt.terminal = TerminalState::None;
            rt.activity = ActivityState::Idle;
            rt.wait_state = WaitState::ResolveWait;
            rt.queue_intent = QueueIntent::NotQueued;
            // Explicit operator intent is the only source of this permission.
            // Auto-resumable deferrals re-enter `ResolveWait` without it, so
            // they keep the unchanged generic preflight.
            rt.manual_resolve_retry = true;
            rt.clear_blocked_metadata();
        }
        self.remove_from_reject_wait_queue(&change_id);
        self.enqueue_unique_resolve_wait(&change_id);
        ReduceOutcome::Changed(ReducerEffect::WaitStateSet {
            change_id,
            wait: WaitState::ResolveWait,
        })
    }

    fn apply_dequeue_change_command(&mut self, change_id: String) -> ReduceOutcome {
        let rt = self.runtime_entry(&change_id);
        if matches!(
            rt.terminal,
            TerminalState::Merged | TerminalState::Pushed | TerminalState::Rejected(_)
        ) {
            return ReduceOutcome::NoOp;
        }
        self.transition_change_to_dequeued(&change_id);
        ReduceOutcome::Changed(ReducerEffect::QueueIntentSet {
            change_id,
            intent: QueueIntent::NotQueued,
        })
    }

    fn apply_stop_change_command(&mut self, change_id: String) -> ReduceOutcome {
        let rt = self.runtime_entry(&change_id);
        if rt.is_terminal() {
            return ReduceOutcome::NoOp;
        }
        self.transition_change_to_stopped(&change_id);
        ReduceOutcome::Changed(ReducerEffect::TerminalStateSet {
            change_id,
            terminal: TerminalState::Stopped,
        })
    }

    /// Apply a reducer command that expresses user intent (queue add/remove, resolve, stop).
    ///
    /// Returns the resulting `ReduceOutcome` describing what changed.
    pub fn apply_command(&mut self, cmd: ReducerCommand) -> ReduceOutcome {
        match cmd {
            ReducerCommand::AddToQueue(change_id) => self.apply_add_to_queue_command(change_id),
            ReducerCommand::RetryError(change_id) => self.retry_terminal_error(&change_id),
            ReducerCommand::RemoveFromQueue(change_id) => {
                self.apply_remove_from_queue_command(change_id)
            }
            ReducerCommand::ResolveMerge(change_id) => self.apply_resolve_merge_command(change_id),
            ReducerCommand::DequeueChange(change_id) => {
                self.apply_dequeue_change_command(change_id)
            }
            ReducerCommand::StopChange(change_id) => self.apply_stop_change_command(change_id),
            ReducerCommand::ResumeStopped(change_id) => self.resume_stopped_change(&change_id),
        }
    }

    /// Apply a workspace observation to reconcile wait states without overwriting
    /// active execution (Phase 2.4).
    pub fn apply_observation(&mut self, change_id: &str, obs: WorkspaceObservation) {
        // Scheduler-owned base-lane membership is reducer state the observation
        // must not duplicate, even if the runtime entry itself looks idle.
        let scheduler_pending = self.resolve_wait_queue.iter().any(|id| id == change_id)
            || self.reject_wait_queue.iter().any(|id| id == change_id);
        let rt = self.runtime_entry(change_id);

        // Never overwrite an active execution stage.
        if rt.is_active() {
            return;
        }
        // Never overwrite a terminal state.
        if rt.is_terminal() {
            return;
        }

        match obs {
            WorkspaceObservation::WorkspaceArchived => {
                // Restore MergeWait when the reducer already has explicit manual-wait
                // evidence. A bare archived workspace observation is otherwise only a
                // repository milestone: no-blocker archive completion
                // must remain in active merge handling until MergeCompleted or a concrete
                // MergeDeferred event explains manual wait.
                if matches!(rt.wait_state, WaitState::MergeWait) {
                    rt.observation = WorkspaceObservation::WorkspaceArchived;
                } else if rt.is_fresh_idle() && !scheduler_pending {
                    // Startup reconciliation: a fresh process has no reducer history at
                    // all, so archived-but-not-yet-merged workspace evidence is the only
                    // authority for this row. Restoring MergeWait here is what makes the
                    // reducer agree with the row the refresh scan already displays, and
                    // is what manual resolve admission is then evaluated against.
                    rt.wait_state = WaitState::MergeWait;
                    rt.clear_blocked_metadata();
                    rt.observation = WorkspaceObservation::WorkspaceArchived;
                }
            }
            WorkspaceObservation::WorktreeNotAhead => {
                // Clear MergeWait when worktree is no longer ahead.
                if matches!(rt.wait_state, WaitState::MergeWait) {
                    rt.wait_state = WaitState::None;
                    rt.clear_blocked_metadata();
                }
                rt.observation = WorkspaceObservation::WorktreeNotAhead;
            }
            WorkspaceObservation::None => {
                rt.observation = WorkspaceObservation::None;
            }
        }
    }

    fn on_processing_started(&mut self, change_id: &str) {
        if self.is_terminal_error_change(change_id) {
            return;
        }
        self.set_current_change(Some(change_id.to_string()));
        let rt = self.runtime_entry(change_id);
        if !rt.is_terminal() && !rt.dequeued {
            rt.queue_intent = QueueIntent::Queued;
        }
    }

    fn on_processing_error(&mut self, change_id: &str, error: String) {
        self.remove_from_pending(change_id);
        let rt = self.runtime_entry(change_id);
        // A failure raised between `ApplyCommitPhase::Started` and any terminal
        // commit-phase event — a WIP snapshot error, for instance — surfaces
        // only as a processing error, so this is the only place that can clear
        // the presentation it left behind.
        rt.commit_phase_attempt = None;
        if !rt.is_terminal() && !rt.dequeued {
            rt.transition_to_terminal(TerminalState::Error(error));
        }
    }

    /// Enter the ephemeral workspace-preparation activity.
    ///
    /// Only an idle, non-terminal, non-dequeued change may enter it: a change
    /// that is already running an operation must never be relabelled as if no
    /// agent had started, and a stopped or terminal change must never be
    /// reactivated by a late preparation event.
    fn on_workspace_preparation_started(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        if rt.is_terminal() || rt.dequeued || !matches!(rt.activity, ActivityState::Idle) {
            return;
        }
        rt.activity = ActivityState::Preparing;
        rt.wait_state = WaitState::None;
        rt.clear_blocked_metadata();
    }

    /// Leave workspace preparation without claiming any next phase.
    ///
    /// Deliberately narrow: it only undoes `Preparing`. Once another transition
    /// has taken over — an operation started, an error, a stop — this is a no-op,
    /// so a late or duplicate clear can never regress real state.
    fn on_workspace_preparation_ended(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        if matches!(rt.activity, ActivityState::Preparing) {
            rt.activity = ActivityState::Idle;
        }
    }

    fn on_apply_started(&mut self, change_id: &str) {
        let mut should_start = false;
        {
            let rt = self.runtime_entry(change_id);
            if !rt.is_terminal() && !rt.dequeued {
                rt.activity = ActivityState::Applying;
                rt.wait_state = WaitState::None;
                rt.clear_blocked_metadata();
                should_start = true;
            }
            // A repair iteration always restores apply presentation, including
            // on a row this reducer declined to reactivate: stale `[commit]`
            // must never outlive the finalization that set it.
            rt.commit_phase_attempt = None;
        }
        if should_start {
            self.set_current_change(Some(change_id.to_string()));
        }
    }

    fn on_apply_completed(&mut self, change_id: &str) {
        self.increment_apply_count(change_id);
        let rt = self.runtime_entry(change_id);
        rt.commit_phase_attempt = None;
        if matches!(rt.activity, ActivityState::Applying) {
            rt.activity = ActivityState::Idle;
        }
    }

    /// Record the ephemeral final-commit presentation phase.
    ///
    /// Nothing about the canonical lifecycle moves here: the change stays in
    /// whatever activity it was already in. Only a `Started` phase leaves
    /// presentation active, so completion, failure, and cancellation all clear
    /// it, and a terminal or dequeued row never adopts it at all.
    fn on_apply_commit_phase(
        &mut self,
        change_id: &str,
        phase: crate::events::ApplyCommitPhase,
        attempt: u32,
    ) {
        let rt = self.runtime_entry(change_id);
        rt.commit_phase_attempt = match phase.is_active() && !rt.is_terminal() && !rt.dequeued {
            true => Some(attempt),
            false => None,
        };
    }

    fn on_acceptance_started(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        if !rt.is_terminal() && !rt.dequeued {
            rt.activity = ActivityState::Accepting;
        }
    }

    fn on_acceptance_completed(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        if matches!(rt.activity, ActivityState::Accepting) {
            rt.activity = ActivityState::Idle;
        }
    }

    fn on_change_rejected(&mut self, change_id: &str, reason: String) {
        self.remove_from_pending(change_id);
        self.remove_from_reject_wait_queue(change_id);
        let rt = self.runtime_entry(change_id);
        if !rt.is_terminal() {
            rt.transition_to_terminal(TerminalState::Rejected(reason));
            rt.queue_intent = QueueIntent::NotQueued;
        }
    }

    fn on_rejection_review_completed(
        &mut self,
        change_id: &str,
        outcome: crate::events::RejectionOutcome,
    ) {
        if matches!(outcome, crate::events::RejectionOutcome::Confirm) {
            self.remove_from_pending(change_id);
        }
        self.remove_from_reject_wait_queue(change_id);

        let rt = self.runtime_entry(change_id);
        if rt.is_terminal() || rt.dequeued {
            return;
        }
        match outcome {
            crate::events::RejectionOutcome::Confirm => {
                rt.transition_to_terminal(TerminalState::Rejected(
                    "rejecting review confirmed rejection".to_string(),
                ));
                rt.queue_intent = QueueIntent::NotQueued;
            }
            crate::events::RejectionOutcome::Resume => {
                rt.activity = ActivityState::Applying;
                rt.wait_state = WaitState::None;
                rt.clear_blocked_metadata();
                rt.terminal = TerminalState::None;
            }
            crate::events::RejectionOutcome::Block => {
                rt.transition_to_stalled(
                    "rejection review returned block; unresolved blocker remains",
                    "resolve unresolved blocker tasks in openspec/changes/<change_id>/tasks.md, then trigger explicit resume",
                    "existing worktree and WIP context are preserved for stalled rejection review",
                );
            }
        }
    }

    fn on_rejection_review_failed(&mut self, change_id: &str, error: String) {
        self.remove_from_pending(change_id);
        self.remove_from_reject_wait_queue(change_id);
        let rt = self.runtime_entry(change_id);
        if !rt.is_terminal() && !rt.dequeued {
            rt.transition_to_terminal(TerminalState::Error(error));
        }
    }

    fn on_workspace_status_updated(
        &mut self,
        change_id: &str,
        status: &crate::vcs::WorkspaceStatus,
    ) {
        if !self
            .change_runtime
            .get(change_id)
            .is_some_and(|rt| !rt.is_terminal() && !rt.dequeued)
        {
            return;
        }
        match status {
            // Monotonic blocker precedence: a structured classification already
            // owns this wait, so the lower-fidelity workspace observation is
            // idempotent. Both structured transitions already left the change
            // idle, so confirming "still blocked" requires no mutation at all —
            // and any mutation here would downgrade the wait kind and replace
            // validated metadata with generic strings.
            crate::vcs::WorkspaceStatus::Blocked
                if self
                    .change_runtime
                    .get(change_id)
                    .is_some_and(ChangeRuntimeState::has_structured_blocker_hold) =>
            {
                if let Some(rt) = self.change_runtime.get(change_id) {
                    tracing::debug!(
                        change_id = %change_id,
                        current_status = rt.display_status(),
                        blocker_kind = ?rt.blocker_kind(),
                        "Ignoring generic blocked workspace status because a structured blocker hold owns this wait"
                    );
                }
            }
            crate::vcs::WorkspaceStatus::Blocked if self.stalled_change_ids.contains(change_id) => {
                self.transition_change_to_stalled(
                    change_id,
                    "change stalled with recoverable blocker",
                    "resolve blocker evidence and retry explicitly",
                    "workflow state is preserved in the workspace",
                );
            }
            crate::vcs::WorkspaceStatus::Rejecting => {
                self.mark_reject_wait(change_id);
            }
            crate::vcs::WorkspaceStatus::Applying => {
                self.runtime_entry(change_id).activity = ActivityState::Applying;
            }
            crate::vcs::WorkspaceStatus::Accepting => {
                self.runtime_entry(change_id).activity = ActivityState::Accepting;
            }
            crate::vcs::WorkspaceStatus::Blocked => {
                self.transition_change_to_stalled(
                    change_id,
                    "apply reported recoverable blocker; workspace remains stalled",
                    "resolve implementation blocker section and pending unblock tasks before explicit retry",
                    "existing worktree and WIP context are preserved while stalled",
                );
            }
            crate::vcs::WorkspaceStatus::Archiving => {
                self.runtime_entry(change_id).activity = ActivityState::Archiving;
            }
            crate::vcs::WorkspaceStatus::Resolving => {
                self.on_workspace_status_resolving(change_id);
            }
            crate::vcs::WorkspaceStatus::MergeWait => {
                self.on_workspace_status_merge_wait(change_id);
            }
            _ => {}
        }
    }

    fn on_workspace_status_resolving(&mut self, change_id: &str) {
        let has_other_lane_blocker = self.has_other_post_archive_lane_blocker(change_id);
        let rt = self.runtime_entry(change_id);
        if has_other_lane_blocker {
            rt.activity = ActivityState::Idle;
            rt.wait_state = WaitState::ResolveWait;
            self.enqueue_unique_resolve_wait(change_id);
        } else {
            rt.activity = ActivityState::Resolving;
            rt.wait_state = WaitState::None;
            self.remove_from_resolve_wait_queue(change_id);
        }
    }

    fn on_workspace_status_merge_wait(&mut self, change_id: &str) {
        let rt = self.runtime_entry(change_id);
        // WorkspaceStatus::MergeWait is manual-blocker evidence only when
        // the reducer does not already own a stronger active/pending state.
        // Auto-resumable deferrals are represented by MergeDeferred(true)
        // and scheduler ResolveWait; stale workspace display hints must not
        // downgrade that retry intent to manual merge wait.
        if matches!(
            rt.activity,
            ActivityState::Resolving | ActivityState::Rejecting
        ) || matches!(
            rt.wait_state,
            WaitState::ResolveWait | WaitState::RejectWait
        ) {
            tracing::debug!(
                change_id = %change_id,
                current_status = rt.display_status(),
                "Ignoring workspace MergeWait status because reducer owns stronger post-archive state"
            );
        } else {
            rt.activity = ActivityState::Idle;
            rt.wait_state = WaitState::MergeWait;
            rt.queue_intent = QueueIntent::NotQueued;
            self.remove_from_resolve_wait_queue(change_id);
        }
    }

    /// Apply an ExecutionEvent to update the shared state.
    ///
    /// This is the single source of truth for state mutations driven by execution events.
    ///
    /// ## Current Usage
    ///
    /// - **CLI Orchestrator**: Calls this method in `src/orchestrator.rs` to track:
    ///   - `ProcessingStarted` - When a change begins processing
    ///   - `ApplyStarted` - When apply operation starts
    ///   - `ApplyCompleted` - When apply operation completes (increments apply count)
    ///   - `ChangeArchived` - When a change is successfully archived
    ///
    /// - **TUI/Web**: Currently maintain their own ExecutionEvent-driven state independently.
    ///   Future refactoring can make them query this shared state for unified tracking.
    pub fn apply_execution_event(&mut self, event: &crate::events::ExecutionEvent) {
        use crate::events::ExecutionEvent;

        match event {
            // Processing lifecycle
            ExecutionEvent::ProcessingStarted(change_id) => self.on_processing_started(change_id),
            ExecutionEvent::ProcessingError { id, error } => {
                self.on_processing_error(id, error.clone());
            }

            // Apply events
            ExecutionEvent::ApplyStarted { change_id, .. } => self.on_apply_started(change_id),
            ExecutionEvent::ApplyCompleted { change_id, .. } => self.on_apply_completed(change_id),
            ExecutionEvent::ApplyFailed { change_id, error } => {
                self.runtime_entry(change_id).commit_phase_attempt = None;
                self.remove_from_pending(change_id);
                self.transition_change_to_error(change_id, error.clone());
            }
            ExecutionEvent::ApplyCommitPhase {
                change_id,
                phase,
                attempt,
            } => self.on_apply_commit_phase(change_id, *phase, *attempt),

            // Acceptance events
            ExecutionEvent::AcceptanceStarted { change_id, .. } => {
                self.on_acceptance_started(change_id);
            }
            ExecutionEvent::AcceptanceCompleted { change_id } => {
                self.on_acceptance_completed(change_id);
            }
            ExecutionEvent::AcceptanceFailed { change_id, error } => {
                self.transition_change_to_error(change_id, error.clone());
            }
            ExecutionEvent::ChangeRejected { change_id, reason } => {
                self.on_change_rejected(change_id, reason.clone());
            }
            ExecutionEvent::RejectionReviewCompleted { change_id, outcome } => {
                self.on_rejection_review_completed(change_id, *outcome);
            }
            ExecutionEvent::RejectionReviewFailed { change_id, error } => {
                self.on_rejection_review_failed(change_id, error.clone());
            }

            // Workspace preparation (process-local only)
            ExecutionEvent::WorkspacePreparationStarted { change_id } => {
                self.on_workspace_preparation_started(change_id);
            }
            ExecutionEvent::WorkspacePreparationEnded { change_id } => {
                self.on_workspace_preparation_ended(change_id);
            }

            // Workspace status synchronization events
            ExecutionEvent::WorkspaceStatusUpdated {
                change_id, status, ..
            } => {
                self.on_workspace_status_updated(change_id, status);
            }

            // Archive events
            ExecutionEvent::ArchiveStarted { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.dequeued {
                    rt.activity = ActivityState::Archiving;
                }
            }
            ExecutionEvent::ArchiveResumed { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if matches!(rt.terminal, TerminalState::Error(_)) {
                    rt.terminal = TerminalState::None;
                }
                if !rt.is_terminal() && !rt.dequeued {
                    rt.activity = ActivityState::Archiving;
                    rt.wait_state = WaitState::None;
                    rt.clear_blocked_metadata();
                }
            }
            ExecutionEvent::ArchiveRetryScheduled { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() {
                    rt.activity = ActivityState::Archiving;
                }
            }
            ExecutionEvent::ChangeArchived(change_id) => {
                self.mark_archived(change_id);
                let has_other_resolve_lane_blocker =
                    self.change_runtime.iter().any(|(id, runtime)| {
                        id != change_id
                            && matches!(
                                runtime.activity,
                                ActivityState::Resolving | ActivityState::Rejecting
                            )
                            && !runtime.is_terminal()
                    });
                let rt = self.runtime_entry(change_id);
                if Self::clear_recoverable_terminal_for_success(rt) {
                    // Archive is never terminal on its own: it always enters
                    // post-archive handling.
                    rt.queue_intent = QueueIntent::NotQueued;
                    if has_other_resolve_lane_blocker {
                        // Lane occupied: keep this row scheduler-owned for automatic retry
                        // after the active merge/reject lane clears.
                        rt.activity = ActivityState::Idle;
                        rt.wait_state = WaitState::ResolveWait;
                        self.enqueue_unique_resolve_wait(change_id);
                    } else {
                        // No blocker known yet: make active merge handling truthful in the
                        // reducer. Manual MergeWait is set only by a later concrete
                        // MergeDeferred(auto_resumable=false) event from merge readiness.
                        rt.activity = ActivityState::Resolving;
                        rt.wait_state = WaitState::None;
                        self.remove_from_resolve_wait_queue(change_id);
                    }
                }
            }
            ExecutionEvent::ArchiveFailed {
                change_id, error, ..
            } => {
                self.transition_change_to_error(change_id, error.clone());
            }

            // Merge / resolve events
            ExecutionEvent::MergeDeferred {
                change_id,
                auto_resumable,
                ..
            } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() {
                    if *auto_resumable {
                        // Auto-resumable: will be retried after a preceding merge/resolve
                        // completes. Use ResolveWait so workspace-refresh reconciliation
                        // does not regress it back to MergeWait. Do not interrupt an
                        // already-active merge attempt; that active state remains the
                        // truthful visible state until completion or manual deferral.
                        if !rt.is_active() {
                            rt.wait_state = WaitState::ResolveWait;
                        }
                        self.enqueue_unique_resolve_wait(change_id);
                    } else {
                        // Manual intervention required: the change must remain visible
                        // as merge-wait only, not as ordinary queued work. Manual
                        // deferral can be discovered during active post-archive merge
                        // handling, so clear Resolving and surface the concrete blocker.
                        rt.activity = ActivityState::Idle;
                        rt.wait_state = WaitState::MergeWait;
                        rt.queue_intent = QueueIntent::NotQueued;
                        self.remove_from_resolve_wait_queue(change_id);
                    }
                }
            }
            ExecutionEvent::MergeCompleted { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if rt.can_success_supersede_terminal() {
                    self.transition_change_to_merged(change_id);
                }
            }
            ExecutionEvent::PushStarted { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.dequeued {
                    rt.activity = ActivityState::Resolving;
                    rt.wait_state = WaitState::None;
                }
            }
            ExecutionEvent::PushCompleted { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if rt.can_success_supersede_terminal() {
                    rt.transition_to_terminal(TerminalState::Pushed);
                    rt.queue_intent = QueueIntent::NotQueued;
                    // Confirmed publication ends this change's base-lane work, so
                    // any retry intent recorded while it was publishing must not
                    // survive as ordinary merge/resolve work.
                    self.clear_base_mutating_wait_queues(change_id);
                }
            }
            ExecutionEvent::PushFailed {
                change_id, error, ..
            } => {
                self.transition_change_to_error(change_id, error.clone());
            }
            ExecutionEvent::ResolveStarted { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.dequeued {
                    rt.activity = ActivityState::Resolving;
                    rt.wait_state = WaitState::None;
                }
            }
            ExecutionEvent::ResolveCompleted { change_id, .. } => {
                let rt = self.runtime_entry(change_id);
                if rt.can_success_supersede_terminal()
                    && !rt.dequeued
                    && (matches!(rt.terminal, TerminalState::Error(_))
                        || matches!(rt.activity, ActivityState::Resolving)
                        || matches!(rt.wait_state, WaitState::ResolveWait))
                {
                    // Successful resolve means the change is now merged. Setting terminal
                    // prevents a subsequent ChangesRefreshed from resurrecting ResolveWait
                    // via apply_observation (which skips terminal entries).
                    self.transition_change_to_merged(change_id);
                } else {
                    self.clear_base_mutating_wait_queues(change_id);
                }
            }
            ExecutionEvent::ResolveFailed { change_id, .. } => {
                // Resolve failure does NOT regress a terminal state.
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() {
                    // Reset activity if we were actively resolving.
                    if matches!(rt.activity, ActivityState::Resolving) {
                        rt.activity = ActivityState::Idle;
                    }
                    // Restore MergeWait when the failure happened during Resolving,
                    // or before ResolveStarted was sent (early dirty-base check
                    // while still in ResolveWait from ReducerCommand::ResolveMerge).
                    if matches!(rt.activity, ActivityState::Idle)
                        && matches!(rt.wait_state, WaitState::ResolveWait | WaitState::None)
                    {
                        rt.wait_state = WaitState::MergeWait;
                        self.remove_from_resolve_wait_queue(change_id);
                    }
                }
            }

            // Dependency events
            ExecutionEvent::DependencyBlocked {
                change_id,
                dependency_ids,
            } => {
                let ids = dependency_ids.clone();
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.is_active() {
                    rt.reconcile_dependency_blocker(&ids);
                }
            }
            ExecutionEvent::DependencyResolved { change_id } => {
                let rt = self.runtime_entry(change_id);
                if matches!(rt.wait_state, WaitState::DependencyBlocked) {
                    rt.wait_state = WaitState::None;
                    rt.clear_blocked_metadata();
                }
            }
            ExecutionEvent::AcceptanceGated { change_id, blocker } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.dequeued {
                    // The agent reported facts; the orchestrator decides the
                    // lifecycle. A complete, validated payload becomes external
                    // `blocked`; anything weaker stays an Acceptance-owned
                    // `stalled` hold rather than an inferred external wait.
                    let classification =
                        crate::orchestration::blocker_classification::classify_reported_facts(
                            blocker,
                        );
                    tracing::debug!(
                        change_id = %change_id,
                        reported_category = %blocker.category,
                        classified_as = ?classification.display_status(),
                        "classified acceptance blocker facts"
                    );
                    match classification {
                        crate::orchestration::blocker_classification::LifecycleClassification::ExternalBlocked(info) => {
                            rt.transition_to_external_blocked(&info, blocker.worktree_snapshot());
                        }
                        crate::orchestration::blocker_classification::LifecycleClassification::Stalled { detail, .. } => {
                            rt.transition_to_acceptance_stalled(
                                format!("acceptance-gated:{}", blocker.category),
                                detail,
                                blocker.worktree_snapshot(),
                                blocker.resumable,
                            );
                        }
                        crate::orchestration::blocker_classification::LifecycleClassification::ProtocolCorrection { .. } => {}
                    }
                }
            }
            ExecutionEvent::ExecutionBlocked { change_id, blocker } => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.dequeued {
                    use crate::orchestration::blocker_classification as classification;
                    // A repeated permission/tool-policy denial is an execution
                    // stop, not a wait on a named prerequisite, so it is
                    // classified as one rather than being offered to the
                    // external-claim validator at all.
                    let classified = if classification::is_permission_denial(blocker) {
                        classification::classify_execution_stop(
                            classification::ExecutionStopReason::PermissionDenial,
                            blocker.summary(),
                        )
                    } else {
                        classification::classify_reported_facts(blocker)
                    };
                    let blocker_reason = format!("execution-blocked:{}", blocker.category);
                    match classified {
                        crate::orchestration::blocker_classification::LifecycleClassification::ExternalBlocked(info) => {
                            rt.transition_to_external_blocked(&info, blocker.worktree_snapshot());
                        }
                        // An Acceptance-phase execution hold (for example a
                        // repeated permission denial during acceptance) holds
                        // dispatch the same way a validated acceptance blocker
                        // does. Apply-phase holds keep their own conservative
                        // handling.
                        _ if blocker.phase == "acceptance" => {
                            rt.transition_to_acceptance_stalled(
                                blocker_reason,
                                blocker.summary(),
                                blocker.worktree_snapshot(),
                                blocker.resumable,
                            );
                        }
                        _ => {
                            rt.transition_to_stalled(
                                blocker_reason,
                                blocker.summary(),
                                blocker.worktree_snapshot(),
                            );
                        }
                    }
                }
            }

            // The `on_merged` hook owns the merged transition: while it fails the
            // change is not merged, so the reducer records the merge-wait
            // recovery state an operator has to act on. Recording it here is
            // also what makes the recovery an *edge* — a replayed hook failure
            // finds the row already in merge wait and changes nothing, so it
            // cannot revoke an execution mark the operator set in the meantime.
            ExecutionEvent::HookFailed {
                change_id,
                hook_type,
                ..
            } if hook_type == crate::hooks::HookType::OnMerged.config_key() => {
                let rt = self.runtime_entry(change_id);
                if !rt.is_terminal() && !rt.dequeued {
                    rt.activity = ActivityState::Idle;
                    rt.wait_state = WaitState::MergeWait;
                    rt.queue_intent = QueueIntent::NotQueued;
                    self.remove_from_resolve_wait_queue(change_id);
                }
            }

            // Stop/dequeue events
            ExecutionEvent::ChangeDequeued { change_id }
            | ExecutionEvent::ChangeStopped { change_id } => {
                let rt = self.runtime_entry(change_id);
                // `Stopped` is in the guard for the same reason the others are:
                // it is a settled outcome, and the dequeue edge a targeted
                // force-stop publishes after its own terminal settlement must
                // report that settlement rather than undo it back to an idle
                // `not queued` row an observer would keep waiting on.
                if matches!(
                    rt.terminal,
                    TerminalState::Merged
                        | TerminalState::Pushed
                        | TerminalState::Rejected(_)
                        | TerminalState::Stopped
                ) {
                    return;
                }
                self.transition_change_to_dequeued(change_id);
            }

            // Process-level run boundary: the reducer, not a frontend, owns the
            // transition every interrupted row makes when the run ends.
            ExecutionEvent::Stopped => self.on_run_stopped(),

            // Dynamic queue support
            ExecutionEvent::ChangesRefreshed {
                changes,
                merge_wait_ids,
                rejected_changes: _,
                worktree_not_ahead_ids,
                ..
            } => {
                // Refresh the initial snapshot if new changes appeared
                let new_ids: Vec<String> = changes
                    .iter()
                    .filter(|c| {
                        !self.initial_change_ids.contains(&c.id)
                            && !self.archived_changes.contains(&c.id)
                    })
                    .map(|c| c.id.clone())
                    .collect();
                for id in new_ids {
                    self.add_dynamic_change(id);
                }

                // If a previously rejected change reappears in the active listing,
                // treat it as reactivated and reset runtime state to defaults.
                for change in changes {
                    let rt = self.runtime_entry(&change.id);
                    if matches!(rt.terminal, TerminalState::Rejected(_)) {
                        rt.terminal = TerminalState::None;
                        rt.clear_activity_wait_and_blocker();
                        rt.queue_intent = QueueIntent::NotQueued;
                    }
                }

                // Apply workspace observations via the reconcile path.
                let mw: Vec<String> = merge_wait_ids.iter().cloned().collect();
                let nah: Vec<String> = worktree_not_ahead_ids.iter().cloned().collect();
                for id in mw {
                    self.apply_observation(&id.clone(), WorkspaceObservation::WorkspaceArchived);
                }
                for id in nah {
                    self.apply_observation(&id.clone(), WorkspaceObservation::WorktreeNotAhead);
                }
            }

            // Other events don't affect shared state directly
            _ => {}
        }
    }
}

impl Default for OrchestratorState {
    fn default() -> Self {
        Self::new(Vec::new(), 0)
    }
}

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

    #[test]
    fn test_new_state() {
        let state =
            OrchestratorState::new(vec!["change-a".to_string(), "change-b".to_string()], 10);

        assert_eq!(state.total_changes(), 2);
        assert_eq!(state.remaining_changes(), 2);
        assert_eq!(state.changes_processed(), 0);
        assert_eq!(state.iteration(), 0);
        assert_eq!(state.max_iterations(), 10);
        assert!(state.current_change_id().is_none());
    }

    #[test]
    fn test_is_in_snapshot() {
        let state = OrchestratorState::new(vec!["change-a".to_string()], 0);

        assert!(state.is_in_snapshot("change-a"));
        assert!(!state.is_in_snapshot("change-b"));
    }

    #[test]
    fn test_apply_count_increment() {
        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);

        assert_eq!(state.apply_count("change-a"), 0);
        assert_eq!(state.increment_apply_count("change-a"), 1);
        assert_eq!(state.increment_apply_count("change-a"), 2);
        assert_eq!(state.apply_count("change-a"), 2);
    }

    #[test]
    fn test_mark_archived() {
        let mut state =
            OrchestratorState::new(vec!["change-a".to_string(), "change-b".to_string()], 0);
        state.set_current_change(Some("change-a".to_string()));
        state.increment_apply_count("change-a");

        assert!(state.is_pending("change-a"));
        assert!(!state.is_archived("change-a"));
        assert_eq!(state.remaining_changes(), 2);

        state.mark_archived("change-a");

        assert!(!state.is_pending("change-a"));
        assert!(state.is_archived("change-a"));
        assert_eq!(state.remaining_changes(), 1);
        assert_eq!(state.changes_processed(), 1);
        assert!(state.current_change_id().is_none());
        assert_eq!(state.apply_count("change-a"), 0); // Cleared
    }

    #[test]
    fn test_is_complete() {
        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);

        assert!(!state.is_complete());
        state.mark_archived("change-a");
        assert!(state.is_complete());
    }

    #[test]
    fn test_iteration_limit() {
        let mut state = OrchestratorState::new(vec![], 10);

        assert!(!state.is_iteration_limit_reached());

        for _ in 0..8 {
            state.increment_iteration();
        }
        assert!(state.is_approaching_iteration_limit()); // 80%
        assert!(!state.is_iteration_limit_reached());

        state.increment_iteration(); // 9
        assert!(!state.is_iteration_limit_reached());

        state.increment_iteration(); // 10
        assert!(state.is_iteration_limit_reached());
    }

    #[test]
    fn test_no_iteration_limit() {
        let mut state = OrchestratorState::new(vec![], 0);

        for _ in 0..100 {
            state.increment_iteration();
        }

        assert!(!state.is_iteration_limit_reached());
        assert!(!state.is_approaching_iteration_limit());
    }

    #[test]
    fn test_add_dynamic_change() {
        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);

        assert_eq!(state.total_changes(), 1);
        assert!(!state.is_pending("change-b"));

        state.add_dynamic_change("change-b".to_string());

        assert_eq!(state.total_changes(), 2);
        assert!(state.is_pending("change-b"));
        assert!(state.is_in_snapshot("change-b"));
    }

    #[test]
    fn test_add_dynamic_change_idempotent() {
        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);

        state.add_dynamic_change("change-a".to_string()); // Already exists
        state.add_dynamic_change("change-b".to_string());
        state.add_dynamic_change("change-b".to_string()); // Duplicate

        assert_eq!(state.total_changes(), 2); // Not 3 or 4
    }

    #[test]
    fn test_remove_from_pending() {
        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);
        state.set_current_change(Some("change-a".to_string()));

        assert!(state.is_pending("change-a"));
        assert!(state.current_change_id().is_some());

        state.remove_from_pending("change-a");

        assert!(!state.is_pending("change-a"));
        assert!(!state.is_archived("change-a")); // Not archived, just removed
        assert!(state.current_change_id().is_none());
    }

    #[test]
    fn test_error_history_management_and_circuit_breaker() {
        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);
        let config = CircuitBreakerConfig {
            enabled: true,
            threshold: 2,
        };

        assert!(!state.record_error_and_check_circuit_breaker(
            "change-a",
            "same error",
            config.clone()
        ));
        assert!(state.record_error_and_check_circuit_breaker("change-a", "same error", config));
        assert!(state.last_error("change-a").is_some());

        state.clear_error_history("change-a");
        assert!(state.last_error("change-a").is_none());
    }

    // -----------------------------------------------------------------------
    // Phase 1.2: change_runtime initialisation
    // -----------------------------------------------------------------------

    #[test]
    fn test_orchestrator_state_initializes_change_runtime() {
        let state = OrchestratorState::new(vec!["change-a".to_string(), "change-b".to_string()], 0);

        // Each change must have a runtime entry with the default (not-queued, idle) state.
        let rt_a = state
            .change_runtime("change-a")
            .expect("runtime for change-a");
        assert_eq!(rt_a.queue_intent, QueueIntent::NotQueued);
        assert_eq!(rt_a.activity, ActivityState::Idle);
        assert_eq!(rt_a.wait_state, WaitState::None);
        assert!(matches!(rt_a.terminal, TerminalState::None));

        let rt_b = state
            .change_runtime("change-b")
            .expect("runtime for change-b");
        assert_eq!(rt_b.queue_intent, QueueIntent::NotQueued);
    }

    // -----------------------------------------------------------------------
    // Phase 1.3: invariant helpers
    // -----------------------------------------------------------------------

    #[test]
    fn test_change_runtime_invariants() {
        // Valid: default state.
        let valid = ChangeRuntimeState::default();
        assert!(valid.invariants_hold());

        // Invalid: terminal + active activity.
        let invalid = ChangeRuntimeState {
            terminal: TerminalState::Merged,
            activity: ActivityState::Applying,
            ..Default::default()
        };
        assert!(!invalid.invariants_hold());

        // Invalid: ResolveWait + Resolving.
        let invalid2 = ChangeRuntimeState {
            wait_state: WaitState::ResolveWait,
            activity: ActivityState::Resolving,
            ..Default::default()
        };
        assert!(!invalid2.invariants_hold());

        // Valid: MergeWait + Idle.
        let ok = ChangeRuntimeState {
            wait_state: WaitState::MergeWait,
            ..Default::default()
        };
        assert!(ok.invariants_hold());

        // Rejecting + no terminal outcome is a valid in-flight state while review runs.
        let in_flight_rejecting = ChangeRuntimeState {
            activity: ActivityState::Rejecting,
            terminal: TerminalState::None,
            ..Default::default()
        };
        assert!(in_flight_rejecting.invariants_hold());

        // Invalid: RejectWait + Rejecting.
        let invalid3 = ChangeRuntimeState {
            wait_state: WaitState::RejectWait,
            activity: ActivityState::Rejecting,
            ..Default::default()
        };
        assert!(!invalid3.invariants_hold());
    }

    // -----------------------------------------------------------------------
    // Phase 1.4: display_status derivation
    // -----------------------------------------------------------------------

    #[test]
    fn test_lifecycle_display_distinguishes_rejected_stalled_blocked_and_error() {
        let rejected = ChangeRuntimeState {
            terminal: TerminalState::Rejected("terminal".to_string()),
            ..Default::default()
        };
        assert_eq!(rejected.display_status(), "rejected");

        let stalled = ChangeRuntimeState {
            wait_state: WaitState::Stalled,
            ..Default::default()
        };
        assert_eq!(stalled.display_status(), "stalled");

        let dependency_blocked = ChangeRuntimeState {
            wait_state: WaitState::DependencyBlocked,
            ..Default::default()
        };
        assert_eq!(dependency_blocked.display_status(), "blocked");

        let error = ChangeRuntimeState {
            terminal: TerminalState::Error("repo-fixable failure".to_string()),
            ..Default::default()
        };
        assert_eq!(error.display_status(), "error");
    }

    #[test]
    fn pushed_terminal_status_is_distinct_from_merged() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 1);
        state.apply_execution_event(&crate::events::ExecutionEvent::PushCompleted {
            change_id: "c".to_string(),
            remote: "origin".to_string(),
            branch: "c".to_string(),
        });
        assert_eq!(state.display_status("c"), "pushed");
        assert!(matches!(
            state.runtime_entry("c").terminal,
            TerminalState::Pushed
        ));
    }

    #[test]
    fn test_display_status_derivation() {
        let state = OrchestratorState::new(vec!["c".to_string()], 0);
        // Default is not queued.
        assert_eq!(state.display_status("c"), "not queued");
        assert_eq!(state.display_status("unknown"), "not queued");

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert_eq!(state.display_status("c"), "queued");

        // Applying takes priority over queued.
        let rt = state.runtime_entry("c");
        rt.activity = ActivityState::Applying;
        assert_eq!(state.display_status("c"), "applying");

        // Terminal takes highest priority.
        let rt = state.runtime_entry("c");
        rt.terminal = TerminalState::Merged;
        assert_eq!(state.display_status("c"), "merged");
    }

    #[test]
    fn test_display_color_derivation() {
        let mut rt = ChangeRuntimeState::default();
        assert_eq!(rt.display_color(), ratatui::style::Color::DarkGray);

        rt.queue_intent = QueueIntent::Queued;
        assert_eq!(rt.display_color(), ratatui::style::Color::Yellow);

        rt.wait_state = WaitState::DependencyBlocked;
        assert_eq!(rt.display_color(), ratatui::style::Color::Gray);

        rt.activity = ActivityState::Preparing;
        assert_eq!(rt.display_status(), "preparing");
        assert_eq!(rt.display_color(), ratatui::style::Color::Green);

        rt.activity = ActivityState::Applying;
        assert_eq!(rt.display_color(), ratatui::style::Color::Cyan);

        rt.activity = ActivityState::Accepting;
        assert_eq!(rt.display_color(), ratatui::style::Color::LightGreen);

        rt.activity = ActivityState::Archiving;
        assert_eq!(rt.display_color(), ratatui::style::Color::Magenta);

        rt.activity = ActivityState::Resolving;
        assert_eq!(rt.display_color(), ratatui::style::Color::LightCyan);

        rt.activity = ActivityState::Idle;
        rt.wait_state = WaitState::MergeWait;
        assert_eq!(rt.display_color(), ratatui::style::Color::LightMagenta);

        rt.wait_state = WaitState::ResolveWait;
        assert_eq!(rt.display_color(), ratatui::style::Color::Magenta);

        rt.wait_state = WaitState::RejectWait;
        assert_eq!(rt.display_status(), "reject pending");
        assert_eq!(rt.display_color(), ratatui::style::Color::LightMagenta);

        rt.wait_state = WaitState::None;
        rt.terminal = TerminalState::Merged;
        assert_eq!(rt.display_color(), ratatui::style::Color::LightBlue);

        rt.terminal = TerminalState::Rejected("blocked".to_string());
        assert_eq!(rt.display_color(), ratatui::style::Color::LightRed);

        rt.terminal = TerminalState::Stopped;
        assert_eq!(rt.display_color(), ratatui::style::Color::DarkGray);

        rt.terminal = TerminalState::Error("boom".to_string());
        assert_eq!(rt.display_color(), ratatui::style::Color::Red);
    }

    #[test]
    fn test_error_message_derivation() {
        let rt = ChangeRuntimeState {
            terminal: TerminalState::Error("fatal".to_string()),
            ..Default::default()
        };
        assert_eq!(rt.error_message(), Some("fatal"));

        let rt2 = ChangeRuntimeState {
            terminal: TerminalState::Merged,
            ..Default::default()
        };
        assert_eq!(rt2.error_message(), None);
    }

    // -----------------------------------------------------------------------
    // Phase 1.5: active/inactive classification
    // -----------------------------------------------------------------------

    #[test]
    fn test_runtime_state_active_classification() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Idle → not active.
        assert!(!state.is_active_change("c"));

        // Applying → active.
        state.runtime_entry("c").activity = ActivityState::Applying;
        assert!(state.is_active_change("c"));

        // Terminal → not active (invariant-wise, but is_active_change checks activity).
        state.runtime_entry("c").terminal = TerminalState::Merged;
        state.runtime_entry("c").activity = ActivityState::Idle;
        assert!(!state.is_active_change("c"));
        assert!(state.is_terminal_change("c"));
    }

    // -----------------------------------------------------------------------
    // Phase 2.2: apply_command queue intent
    // -----------------------------------------------------------------------

    #[test]
    fn final_terminal_dispatch_stop_excludes_recoverable_terminal_error() {
        let mut state = OrchestratorState::new(
            vec![
                "merged".to_string(),
                "archived".to_string(),
                "rejected".to_string(),
                "error".to_string(),
            ],
            0,
        );
        state.apply_execution_event(&crate::events::ExecutionEvent::MergeCompleted {
            change_id: "merged".to_string(),
            revision: "rev".to_string(),
        });
        state.runtime_entry("archived").terminal = TerminalState::Pushed;
        state.runtime_entry("rejected").terminal = TerminalState::Rejected("no".to_string());
        state.apply_execution_event(&crate::events::ExecutionEvent::ProcessingError {
            id: "error".to_string(),
            error: "boom".to_string(),
        });

        assert!(state.is_final_terminal_dispatch_stop("merged"));
        assert!(state.is_final_terminal_dispatch_stop("archived"));
        assert!(state.is_final_terminal_dispatch_stop("rejected"));
        assert!(!state.is_final_terminal_dispatch_stop("error"));
        assert!(state.is_terminal_error_change("error"));
        assert!(matches!(
            state.apply_command(ReducerCommand::AddToQueue("error".to_string())),
            ReduceOutcome::NoOp
        ));
        assert!(matches!(
            state.apply_command(ReducerCommand::RetryError("error".to_string())),
            ReduceOutcome::Changed(_)
        ));
        assert_eq!(state.display_status("error"), "queued");
    }

    #[test]
    fn test_apply_command_queue_intent() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // AddToQueue.
        let outcome = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");

        // AddToQueue again → NoOp (idempotent).
        let outcome2 = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome2, ReduceOutcome::NoOp));

        state.mark_stalled("c".to_string());
        state.runtime_entry("c").wait_state = WaitState::Stalled;
        let outcome_from_stalled = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome_from_stalled, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");
        assert!(!state.stalled_change_ids().contains("c"));

        // RemoveFromQueue.
        let outcome3 = state.apply_command(ReducerCommand::RemoveFromQueue("c".to_string()));
        assert!(matches!(outcome3, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "not queued");

        // RemoveFromQueue again → NoOp.
        let outcome4 = state.apply_command(ReducerCommand::RemoveFromQueue("c".to_string()));
        assert!(matches!(outcome4, ReduceOutcome::NoOp));

        // DequeueChange.
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        let outcome5 = state.apply_command(ReducerCommand::DequeueChange("c".to_string()));
        assert!(matches!(outcome5, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "not queued");

        // DequeueChange on already not queued keeps queue-off state.
        let outcome6 = state.apply_command(ReducerCommand::DequeueChange("c".to_string()));
        assert!(matches!(outcome6, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "not queued");

        // Terminal errors require the explicit retry transition, not ordinary queue intent.
        state.runtime_entry("c").terminal = TerminalState::Error("boom".to_string());
        let outcome_error_queue = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome_error_queue, ReduceOutcome::NoOp));
        assert_eq!(state.display_status("c"), "error");
        let outcome_error_retry = state.apply_command(ReducerCommand::RetryError("c".to_string()));
        assert!(matches!(outcome_error_retry, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");

        // Rejected cannot be re-queued until a refresh reactivates the change.
        state.runtime_entry("c").terminal = TerminalState::Rejected("blocked".to_string());
        let outcome7 = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome7, ReduceOutcome::NoOp));
        let outcome_rejected_retry =
            state.apply_command(ReducerCommand::RetryError("c".to_string()));
        assert!(matches!(outcome_rejected_retry, ReduceOutcome::NoOp));

        // Reactivation path: when the change reappears in active listing after

        // REJECTED.md removal, ChangesRefreshed clears rejected terminal state.
        use crate::events::ExecutionEvent;
        use crate::openspec::{Change, ProposalMetadata};
        use std::collections::{HashMap, HashSet};
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![Change {
                id: "c".to_string(),
                completed_tasks: 0,
                total_tasks: 1,
                last_modified: "now".to_string(),
                dependencies: Vec::new(),
                metadata: ProposalMetadata::default(),
            }],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        });
        assert_eq!(state.display_status("c"), "not queued");

        // AddToQueue must be accepted again after reactivation.
        let outcome8 = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome8, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");
    }

    #[test]
    fn retry_terminal_error_clears_error_gate_and_stale_retry_metadata() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        state.apply_execution_event(&crate::events::ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "apply".to_string(),
        });
        state.record_error_and_check_circuit_breaker(
            "c",
            "boom",
            CircuitBreakerConfig {
                enabled: true,
                threshold: 2,
            },
        );
        state.mark_stalled("c".to_string());
        state.apply_execution_event(&crate::events::ExecutionEvent::ProcessingError {
            id: "c".to_string(),
            error: "boom".to_string(),
        });

        assert_eq!(state.display_status("c"), "error");
        assert!(state.queued_change_ids().is_empty());
        assert!(state.last_error("c").is_some());

        let outcome = state.apply_command(ReducerCommand::RetryError("c".to_string()));

        assert!(matches!(outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");
        assert_eq!(state.queued_change_ids(), vec!["c".to_string()]);
        assert!(state.last_error("c").is_none());
        assert!(!state.stalled_change_ids().contains("c"));
        let runtime = state.change_runtime("c").expect("runtime should exist");
        assert!(matches!(runtime.terminal, TerminalState::None));
        assert_eq!(runtime.wait_state, WaitState::None);
        assert_eq!(runtime.blocked_metadata, BlockedMetadata::default());
    }

    #[test]
    fn late_success_supersedes_recoverable_error_without_requeueing_apply() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&crate::events::ExecutionEvent::ApplyFailed {
            change_id: "c".to_string(),
            error: "boom".to_string(),
        });
        assert_eq!(state.display_status("c"), "error");

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });

        assert_eq!(state.display_status("c"), "merged");
        assert!(state.queued_change_ids().is_empty());
        let runtime = state.change_runtime("c").expect("runtime should exist");
        assert_eq!(runtime.queue_intent, QueueIntent::NotQueued);
    }

    #[test]
    fn archive_resumed_clears_recoverable_archive_error_and_restores_archiving_activity() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ArchiveFailed {
            change_id: "c".to_string(),
            error: "Archive commit finalization failed".to_string(),
            reason: Some("verification_failed".to_string()),
            summary: Some("commit incomplete".to_string()),
        });
        assert_eq!(state.display_status("c"), "error");

        state.apply_execution_event(&ExecutionEvent::ArchiveResumed {
            change_id: "c".to_string(),
            reason: Some("archive_commit_incomplete".to_string()),
            summary: Some("resuming archived dirty repair".to_string()),
        });

        assert_eq!(state.display_status("c"), "archiving");
        let runtime = state.change_runtime("c").expect("runtime should exist");
        assert!(matches!(runtime.terminal, TerminalState::None));
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_base_mutating_lane_is_single_occupant_across_resolving_and_rejecting() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("a".to_string()));
        assert_eq!(state.display_status("a"), "resolving");

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "b".to_string(),
            workspace_name: "ws-b".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });

        assert_eq!(state.display_status("b"), "reject pending");
        assert_eq!(state.reject_wait_change_ids(), vec!["b".to_string()]);
        assert!(state.has_other_post_archive_lane_blocker("b"));
        assert!(state.global_invariants_hold());
    }

    /// Only explicit operator intent grants the scoped merge-continuation
    /// permission; an auto-resumable deferral re-enters `ResolveWait` without it
    /// and therefore keeps the unchanged generic dirty preflight.
    #[test]
    fn manual_resolve_permission_is_granted_only_by_explicit_operator_intent() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "merge lane busy".to_string(),
            auto_resumable: true,
        });
        assert!(
            !state.has_manual_resolve_retry("alpha"),
            "an auto-resumable deferral is not operator intent"
        );

        state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
        assert!(state.has_manual_resolve_retry("alpha"));
    }

    /// The permission is consumed by the dispatch that owns the base lane, and a
    /// later ordinary scheduled attempt must not inherit it.
    #[test]
    fn manual_resolve_permission_is_consumed_once_and_is_not_sticky() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "bounded resolve exhausted".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));

        // Promotion only reads the permission: a dispatch deferred by lane
        // occupancy has to find it again.
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("alpha".to_string(), WaitState::ResolveWait))
        );
        assert!(state.has_manual_resolve_retry("alpha"));

        assert!(state.consume_manual_resolve_retry("alpha"));
        assert!(!state.has_manual_resolve_retry("alpha"));
        assert!(
            !state.consume_manual_resolve_retry("alpha"),
            "a second dispatch gets the unchanged generic preflight"
        );
        assert!(!state.consume_manual_resolve_retry("unknown-change"));
    }

    /// Losing the wait loses the retry the permission authorized, so a dequeue
    /// must not leave a live permission behind for a later requeue.
    #[test]
    fn manual_resolve_permission_does_not_survive_dequeue() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "bounded resolve exhausted".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
        assert!(state.has_manual_resolve_retry("alpha"));

        state.apply_command(ReducerCommand::DequeueChange("alpha".to_string()));

        assert!(!state.has_manual_resolve_retry("alpha"));
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn release_base_mutating_lane_after_retry_restores_resolve_wait_uniquely() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "conflict".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("alpha".to_string(), WaitState::ResolveWait))
        );
        assert!(state.is_base_mutating_lane_occupied());

        assert!(state.release_base_mutating_lane_after_retry("alpha", WaitState::ResolveWait));
        assert!(!state.is_base_mutating_lane_occupied());
        assert_eq!(state.display_status("alpha"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["alpha".to_string()]);
        assert!(state.global_invariants_hold());

        assert!(!state.release_base_mutating_lane_after_retry("alpha", WaitState::ResolveWait));
        assert_eq!(state.resolve_wait_queue, vec!["alpha".to_string()]);
        assert!(state.reject_wait_queue.is_empty());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn abandon_base_mutating_lane_occupant_releases_resolve_without_requeueing() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string(), "beta".to_string()], 0);

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "conflict".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("alpha".to_string(), WaitState::ResolveWait))
        );
        state.resolve_wait_queue.push("alpha".to_string());
        state.reject_wait_queue.push("alpha".to_string());
        state
            .runtime_entry("alpha")
            .set_blocked_metadata("reason", "unblock", "snapshot");

        assert!(state.abandon_base_mutating_lane_occupant("alpha"));

        let runtime = state.change_runtime("alpha").expect("runtime for alpha");
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert_eq!(runtime.wait_state, WaitState::None);
        assert_eq!(runtime.blocked_metadata, BlockedMetadata::default());
        assert!(!state
            .resolve_wait_change_ids()
            .contains(&"alpha".to_string()));
        assert!(!state
            .reject_wait_change_ids()
            .contains(&"alpha".to_string()));
        assert!(!state.resolve_wait_queue.contains(&"alpha".to_string()));
        assert!(!state.reject_wait_queue.contains(&"alpha".to_string()));
        assert!(!state.is_base_mutating_lane_occupied());
        assert!(state.global_invariants_hold());

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "beta".to_string(),
            reason: "conflict".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("beta".to_string()));
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("beta".to_string(), WaitState::ResolveWait))
        );
    }

    #[test]
    fn abandon_base_mutating_lane_occupant_releases_reject_and_noops_terminal_or_non_occupant() {
        let mut state = OrchestratorState::new(
            vec![
                "lane".to_string(),
                "reject".to_string(),
                "terminal".to_string(),
            ],
            0,
        );

        state.apply_execution_event(&crate::events::ExecutionEvent::ChangeArchived(
            "lane".to_string(),
        ));
        state.mark_reject_wait("reject");
        state.apply_execution_event(&crate::events::ExecutionEvent::MergeCompleted {
            change_id: "lane".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("reject".to_string(), WaitState::RejectWait))
        );

        assert!(state.abandon_base_mutating_lane_occupant("reject"));
        let runtime = state.change_runtime("reject").expect("runtime for reject");
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert_eq!(runtime.wait_state, WaitState::None);
        assert!(state.reject_wait_change_ids().is_empty());
        assert!(!state.is_base_mutating_lane_occupied());
        assert!(state.global_invariants_hold());

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeCompleted {
            change_id: "terminal".to_string(),
            revision: "rev".to_string(),
        });
        assert!(!state.abandon_base_mutating_lane_occupant("terminal"));
        assert!(!state.abandon_base_mutating_lane_occupant("unknown"));
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn release_base_mutating_lane_after_retry_restores_reject_wait_and_noops_terminal() {
        let mut state = OrchestratorState::new(vec!["lane".to_string(), "reject".to_string()], 0);

        state.apply_execution_event(&crate::events::ExecutionEvent::ChangeArchived(
            "lane".to_string(),
        ));
        state.mark_reject_wait("reject");
        state.apply_execution_event(&crate::events::ExecutionEvent::MergeCompleted {
            change_id: "lane".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("reject".to_string(), WaitState::RejectWait))
        );

        assert!(state.release_base_mutating_lane_after_retry("reject", WaitState::RejectWait));
        assert!(!state.is_base_mutating_lane_occupied());
        assert_eq!(state.display_status("reject"), "reject pending");
        assert_eq!(state.reject_wait_change_ids(), vec!["reject".to_string()]);
        assert!(state.global_invariants_hold());

        state.apply_execution_event(&crate::events::ExecutionEvent::ChangeRejected {
            change_id: "reject".to_string(),
            reason: "confirmed".to_string(),
        });
        assert!(!state.release_base_mutating_lane_after_retry("reject", WaitState::RejectWait));
        assert!(state.reject_wait_change_ids().is_empty());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_reject_wait_queue_membership_and_clear_on_start_completion() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("a".to_string()));
        state.mark_reject_wait("b");

        assert_eq!(state.display_status("b"), "reject pending");
        assert_eq!(state.reject_wait_change_ids(), vec!["b".to_string()]);

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "a".to_string(),
            revision: "rev".to_string(),
        });
        let promoted = state.promote_next_base_mutating_lane_waiter();
        assert_eq!(promoted, Some(("b".to_string(), WaitState::RejectWait)));
        assert_eq!(state.display_status("b"), "rejecting");
        assert!(state.reject_wait_change_ids().is_empty());

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "b".to_string(),
            outcome: RejectionOutcome::Confirm,
        });
        assert_eq!(state.display_status("b"), "rejected");
        assert!(state.reject_wait_change_ids().is_empty());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn command_side_effects_update_terminal_wait_and_base_lane_queues() {
        let mut state = OrchestratorState::new(vec!["c".to_string(), "d".to_string()], 0);

        state.resolve_wait_queue.push("c".to_string());
        state.reject_wait_queue.push("c".to_string());
        let add_outcome = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(add_outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");
        assert!(state.resolve_wait_queue.is_empty());
        assert!(state.reject_wait_queue.is_empty());

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "manual conflict".to_string(),
            auto_resumable: false,
        });
        let resolve_outcome = state.apply_command(ReducerCommand::ResolveMerge("c".to_string()));
        assert!(matches!(
            resolve_outcome,
            ReduceOutcome::Changed(ReducerEffect::WaitStateSet {
                wait: WaitState::ResolveWait,
                ..
            })
        ));
        assert_eq!(state.display_status("c"), "resolve pending");
        assert_eq!(state.resolve_wait_queue, vec!["c".to_string()]);
        assert!(state.reject_wait_queue.is_empty());

        let dequeue_outcome = state.apply_command(ReducerCommand::DequeueChange("c".to_string()));
        assert!(matches!(dequeue_outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "not queued");
        assert!(state.resolve_wait_queue.is_empty());
        assert!(state.reject_wait_queue.is_empty());
        let runtime = state.change_runtime("c").expect("runtime for c");
        assert!(matches!(runtime.terminal, TerminalState::None));
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert_eq!(runtime.wait_state, WaitState::None);
        assert_eq!(runtime.queue_intent, QueueIntent::NotQueued);
        assert!(runtime.dequeued);

        state.apply_command(ReducerCommand::AddToQueue("d".to_string()));
        let stop_outcome = state.apply_command(ReducerCommand::StopChange("d".to_string()));
        assert!(matches!(stop_outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("d"), "stopped");
        let runtime = state.change_runtime("d").expect("runtime for d");
        assert!(matches!(runtime.terminal, TerminalState::Stopped));
        assert_eq!(runtime.queue_intent, QueueIntent::NotQueued);
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn execution_event_side_effects_update_wait_queues_and_blocked_metadata() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(
            vec![
                "resolving".to_string(),
                "archived".to_string(),
                "reject".to_string(),
            ],
            0,
        );

        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "resolving".to_string(),
            command: "resolve".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("archived".to_string()));
        assert_eq!(state.display_status("archived"), "resolve pending");
        assert_eq!(state.resolve_wait_queue, vec!["archived".to_string()]);

        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "archived".to_string(),
            error: "base dirty".to_string(),
        });
        assert_eq!(state.display_status("archived"), "merge wait");
        assert!(state.resolve_wait_queue.is_empty());

        state.mark_reject_wait("reject");
        assert_eq!(state.reject_wait_queue, vec!["reject".to_string()]);
        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "reject".to_string(),
            outcome: RejectionOutcome::Block,
        });
        assert!(state.reject_wait_queue.is_empty());
        let runtime = state.change_runtime("reject").expect("runtime for reject");
        assert_eq!(runtime.wait_state, WaitState::Stalled);
        assert!(runtime.blocked_metadata.blocker_reason.is_some());
        assert!(matches!(runtime.terminal, TerminalState::None));

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "reject".to_string(),
            outcome: RejectionOutcome::Confirm,
        });
        assert_eq!(state.display_status("reject"), "rejected");
        assert!(state.reject_wait_queue.is_empty());
        assert!(state.global_invariants_hold());
    }

    // -----------------------------------------------------------------------
    // Phase 2.3: apply_execution_event transitions
    // -----------------------------------------------------------------------

    // === Ephemeral Apply commit subphase ===

    /// The commit subphase is presentation only: it changes the Apply lane's
    /// rendered operation and nothing else. The canonical lifecycle, the queue
    /// intent, and every routing input stay exactly where they were.
    #[test]
    fn commit_presentation_never_changes_the_canonical_lifecycle() {
        use crate::events::{ApplyCommitPhase, ExecutionEvent};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        let before = state.change_runtime("c").cloned().expect("runtime");

        state.apply_execution_event(&ExecutionEvent::ApplyCommitPhase {
            change_id: "c".to_string(),
            phase: ApplyCommitPhase::Started,
            attempt: 4,
        });

        let during = state.change_runtime("c").expect("runtime");
        assert_eq!(
            state.display_status("c"),
            "applying",
            "the canonical status must not become a commit state"
        );
        assert_eq!(during.apply_operation_label(), "commit");
        assert_eq!(during.commit_phase_attempt, Some(4));
        assert_eq!(during.activity, before.activity);
        assert_eq!(during.wait_state, before.wait_state);
        assert_eq!(during.queue_intent, before.queue_intent);
        assert!(state.global_invariants_hold());
    }

    /// Completion, failure, and a repair `ApplyStarted` all clear presentation,
    /// so no row can be left rendering a `[commit]` that is no longer running.
    #[test]
    fn every_terminal_commit_phase_clears_presentation() {
        use crate::events::{ApplyCommitPhase, ExecutionEvent};

        for closing in [ApplyCommitPhase::Completed, ApplyCommitPhase::Failed] {
            let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
            state.apply_execution_event(&ExecutionEvent::ApplyStarted {
                change_id: "c".to_string(),
                command: "cmd".to_string(),
            });
            state.apply_execution_event(&ExecutionEvent::ApplyCommitPhase {
                change_id: "c".to_string(),
                phase: ApplyCommitPhase::Started,
                attempt: 1,
            });
            state.apply_execution_event(&ExecutionEvent::ApplyCommitPhase {
                change_id: "c".to_string(),
                phase: closing,
                attempt: 1,
            });

            let runtime = state.change_runtime("c").expect("runtime");
            assert_eq!(
                runtime.commit_phase_attempt, None,
                "{closing:?} must clear commit presentation"
            );
            assert_eq!(runtime.apply_operation_label(), "apply");
            assert_eq!(state.display_status("c"), "applying");
        }
    }

    /// Cancellation can land anywhere inside finalization, including before any
    /// terminal commit-phase event was emitted — a WIP snapshot failure between
    /// `Started` and the commit surfaces only as a processing error. Every one
    /// of those routes must clear the ephemeral presentation, or the row keeps
    /// rendering `[commit]` for a sequence that is no longer running.
    #[test]
    fn cancelling_outside_the_commit_sequence_clears_commit_presentation() {
        use crate::events::{ApplyCommitPhase, ExecutionEvent};

        /// Put a change into an active commit phase, then cancel it the way the
        /// named route does.
        fn active_commit_then(cancel: impl Fn(&mut OrchestratorState)) -> Option<u32> {
            let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
            state.apply_execution_event(&ExecutionEvent::ApplyStarted {
                change_id: "c".to_string(),
                command: "cmd".to_string(),
            });
            state.apply_execution_event(&ExecutionEvent::ApplyCommitPhase {
                change_id: "c".to_string(),
                phase: ApplyCommitPhase::Started,
                attempt: 3,
            });
            assert_eq!(
                state
                    .change_runtime("c")
                    .expect("runtime")
                    .commit_phase_attempt,
                Some(3),
                "precondition: the row is presenting an active commit phase"
            );

            cancel(&mut state);
            assert!(state.global_invariants_hold());
            state
                .change_runtime("c")
                .expect("runtime")
                .commit_phase_attempt
        }

        assert_eq!(
            active_commit_then(|state| {
                state.apply_execution_event(&ExecutionEvent::ChangeDequeued {
                    change_id: "c".to_string(),
                });
            }),
            None,
            "ChangeDequeued must clear commit presentation"
        );
        assert_eq!(
            active_commit_then(|state| {
                state.apply_execution_event(&ExecutionEvent::ChangeStopped {
                    change_id: "c".to_string(),
                });
            }),
            None,
            "ChangeStopped must clear commit presentation"
        );
        assert_eq!(
            active_commit_then(|state| {
                state.apply_command(ReducerCommand::DequeueChange("c".to_string()));
            }),
            None,
            "the DequeueChange command must clear commit presentation"
        );
        assert_eq!(
            active_commit_then(|state| {
                state.apply_command(ReducerCommand::StopChange("c".to_string()));
            }),
            None,
            "the StopChange command must clear commit presentation"
        );
        assert_eq!(
            active_commit_then(|state| {
                state.apply_execution_event(&ExecutionEvent::ProcessingError {
                    id: "c".to_string(),
                    error: "WIP snapshot failed".to_string(),
                });
            }),
            None,
            "a processing error must clear commit presentation"
        );
    }

    /// A repair iteration restores `[apply]` even if the closing phase event was
    /// never observed.
    #[test]
    fn a_repair_iteration_restores_apply_presentation() {
        use crate::events::{ApplyCommitPhase, ExecutionEvent};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ApplyCommitPhase {
            change_id: "c".to_string(),
            phase: ApplyCommitPhase::Started,
            attempt: 2,
        });
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });

        assert_eq!(
            state
                .change_runtime("c")
                .expect("runtime")
                .commit_phase_attempt,
            None,
            "ApplyStarted always clears commit presentation"
        );
        assert_eq!(
            state.all_apply_operation_labels().get("c").copied(),
            Some("apply")
        );
    }

    /// A terminal or dequeued row must not adopt commit presentation from a
    /// late in-flight event.
    #[test]
    fn a_terminal_row_never_adopts_commit_presentation() {
        use crate::events::{ApplyCommitPhase, ExecutionEvent};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ApplyFailed {
            change_id: "c".to_string(),
            error: "boom".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ApplyCommitPhase {
            change_id: "c".to_string(),
            phase: ApplyCommitPhase::Started,
            attempt: 1,
        });

        assert_eq!(state.display_status("c"), "error");
        assert_eq!(
            state
                .change_runtime("c")
                .expect("runtime")
                .commit_phase_attempt,
            None
        );
    }

    /// Constitutional law 1: a restart re-derives routing from the workspace, so
    /// commit presentation must simply be absent in a fresh reducer and must not
    /// be reachable from any persisted input.
    #[test]
    fn a_fresh_reducer_has_no_commit_presentation() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        assert_eq!(
            state.all_apply_operation_labels().get("c").copied(),
            Some("apply"),
            "a fresh reducer presents the Apply lane, never a commit subphase"
        );

        state.apply_execution_event(&crate::events::ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(
            state
                .change_runtime("c")
                .expect("runtime")
                .commit_phase_attempt,
            None,
            "process-local commit presentation starts empty"
        );
    }

    #[test]
    fn test_apply_execution_event_transitions() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(state.display_status("c"), "applying");

        state.apply_execution_event(&ExecutionEvent::ApplyCompleted {
            change_id: "c".to_string(),
            revision: "rev1".to_string(),
        });
        assert_eq!(state.display_status("c"), "not queued");

        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(state.display_status("c"), "accepting");

        state.apply_execution_event(&ExecutionEvent::AcceptanceCompleted {
            change_id: "c".to_string(),
        });

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "c".to_string(),
            workspace_name: "ws-c".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });
        assert_eq!(state.display_status("c"), "rejecting");

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "c".to_string(),
            outcome: RejectionOutcome::Resume,
        });
        assert_eq!(state.display_status("c"), "applying");
        assert_ne!(
            state
                .change_runtime("c")
                .expect("runtime for c after rejecting resume")
                .activity,
            ActivityState::Rejecting
        );

        state.apply_execution_event(&ExecutionEvent::RejectionReviewFailed {
            change_id: "c".to_string(),
            error: "rejecting failed".to_string(),
        });
        assert_eq!(state.display_status("c"), "error");
        assert_ne!(
            state
                .change_runtime("c")
                .expect("runtime for c after rejecting failure")
                .activity,
            ActivityState::Rejecting
        );

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ProcessingStarted("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "c".to_string(),
            workspace_name: "ws-c".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });
        assert_eq!(state.display_status("c"), "rejecting");

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "c".to_string(),
            outcome: RejectionOutcome::Confirm,
        });
        assert_eq!(state.display_status("c"), "rejected");
        assert_ne!(
            state
                .change_runtime("c")
                .expect("runtime for c after rejecting confirm")
                .activity,
            ActivityState::Rejecting
        );
    }

    /// The explicit category reaches reducer state verbatim, and prose never
    /// overrides it — the same narrative under a different category must produce
    /// a different external blocker classification.
    #[test]
    fn test_explicit_blocker_categories_reach_blocked_metadata_without_prose_inference() {
        // Every message below contains words the old classifier keyed on
        // (docker, daemon, timeout, credential, still running). None of them may
        // change the category.
        let cases = [
            (
                "credential",
                "docker image pull failed: lookup registry-1.docker.io i/o timeout",
            ),
            ("infrastructure", "missing non-mockable external credential"),
            (
                "human_decision",
                "agent-exec managed verification job still running",
            ),
            ("external_approval", "Cannot connect to the Docker daemon"),
            (
                "schema_incompatibility",
                "package registry timeout fetching crate",
            ),
        ];

        for (idx, (explicit_category, message)) in cases.iter().enumerate() {
            let change_id = format!("c-{idx}");
            let mut state = OrchestratorState::new(vec![change_id.clone()], 0);
            state.apply_execution_event(&crate::events::ExecutionEvent::AcceptanceGated {
                change_id: change_id.clone(),
                blocker: crate::events::StalledBlocker::acceptance_external(
                    *explicit_category,
                    *message,
                ),
            });

            let runtime = state
                .change_runtime(&change_id)
                .expect("runtime after blocker classification");
            // A validated non-repository prerequisite is `blocked`, and its
            // blocker kind says why — never a dependency edge, never a stall.
            assert_eq!(state.display_status(&change_id), "blocked");
            assert_eq!(runtime.blocker_kind(), BlockerKind::External);
            assert!(matches!(runtime.terminal, TerminalState::None));
            assert_eq!(
                runtime.blocked_metadata.blocker_reason.as_deref(),
                Some(format!("external-blocked:{explicit_category}").as_str()),
                "the explicit category must survive verbatim for {message}"
            );
            assert!(
                runtime
                    .blocked_metadata
                    .unblock_metadata
                    .as_deref()
                    .unwrap_or_default()
                    .contains(message),
                "metadata should preserve observed error summary for {message}"
            );
        }
    }

    #[test]
    fn test_execution_blocked_permission_denial_transitions_to_stalled_with_operator_guidance() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let denial = crate::permission::classify_permission_denial(&[Some(
            "Read permission denied for /private/secret.txt",
        )])
        .expect("denial should classify");
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "c".to_string(),
            command: "accept".to_string(),
        });

        state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
            change_id: "c".to_string(),
            blocker: StalledBlocker::permission_denial("acceptance", &denial),
        });

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert_eq!(state.display_status("c"), "stalled");
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert_eq!(runtime.wait_state, WaitState::Stalled);
        assert!(matches!(runtime.terminal, TerminalState::None));
        let metadata = runtime
            .blocked_metadata
            .unblock_metadata
            .as_deref()
            .expect("operator guidance metadata");
        assert!(metadata.contains("permission/tool policy denial"));
        assert!(metadata.contains("operator action"));
        assert!(!metadata.to_ascii_lowercase().contains("dependency blocked"));
    }

    #[test]
    fn test_acceptance_gated_transitions_to_external_blocked_with_structured_metadata() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "c".to_string(),
            command: "accept".to_string(),
        });

        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "c".to_string(),
            blocker: StalledBlocker::acceptance_external(
                "pending_verification",
                "docker image pull failed: lookup registry-1.docker.io i/o timeout",
            ),
        });

        let runtime = state
            .change_runtime("c")
            .expect("runtime for c after acceptance gated");
        assert_eq!(state.display_status("c"), "blocked");
        assert_eq!(runtime.blocker_kind(), BlockerKind::External);
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert_eq!(runtime.wait_state, WaitState::ExternalBlocked);
        assert!(matches!(runtime.terminal, TerminalState::None));
        assert_eq!(
            runtime.blocked_metadata.blocker_reason.as_deref(),
            Some("external-blocked:pending_verification")
        );
        let unblock = runtime
            .blocked_metadata
            .unblock_metadata
            .as_deref()
            .expect("unblock metadata");
        assert!(unblock.contains("external blocker (pending_verification)"));
        assert!(unblock.contains("reported by acceptance"));
        assert!(unblock.contains("unblock when"));
        assert!(unblock.contains("next action"));
        assert!(unblock.contains("docker image pull failed"));
        assert!(runtime.blocked_metadata.unblock_condition.is_some());
        assert_eq!(
            runtime.blocked_metadata.blocker_origin.as_deref(),
            Some("acceptance")
        );
        assert_eq!(
            runtime.blocked_metadata.worktree_snapshot.as_deref(),
            Some("existing worktree and WIP context are preserved while stalled")
        );
    }

    /// Acceptance facts that do not validate as a non-repository prerequisite
    /// stay `stalled`. An unsupported category and a missing unblock condition
    /// must not be promoted into an inferred external wait.
    #[test]
    fn test_unvalidated_acceptance_blocker_facts_remain_stalled() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "c".to_string(),
            blocker: StalledBlocker {
                category: "acceptance_finding".to_string(),
                phase: "acceptance".to_string(),
                gate: "acceptance".to_string(),
                error_summary: "unresolved finding".to_string(),
                evidence: vec!["src/lib.rs:1 missing coverage".to_string()],
                unblock_condition: None,
                prerequisite_owner: None,
                next_action: "resolve the finding and retry".to_string(),
                resumable: true,
                worktree_preserved: true,
            },
        });

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert_eq!(state.display_status("c"), "stalled");
        assert_eq!(runtime.wait_state, WaitState::Stalled);
        assert_eq!(runtime.blocker_kind(), BlockerKind::None);
        assert!(runtime.blocked_metadata.unblock_condition.is_none());
        // The unsupported category is reported first, and the detail keeps the
        // reason so an operator can see exactly what disqualified the claim.
        assert!(runtime
            .blocked_metadata
            .unblock_metadata
            .as_deref()
            .unwrap_or_default()
            .contains("'acceptance_finding' is not one of"));
    }

    /// Dependency waits and external prerequisite waits are both `blocked` and
    /// stay distinguishable, and neither is confused with an execution stall.
    #[test]
    fn test_dependency_and_external_waits_share_blocked_but_keep_their_kind() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(
            vec![
                "dependency-wait".to_string(),
                "external-wait".to_string(),
                "execution-stall".to_string(),
            ],
            0,
        );
        state.apply_execution_event(&ExecutionEvent::DependencyBlocked {
            change_id: "dependency-wait".to_string(),
            dependency_ids: vec!["alpha".to_string()],
        });
        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "external-wait".to_string(),
            blocker: StalledBlocker::acceptance_external("credential", "STAGING_API_KEY is unset"),
        });
        let denial = crate::permission::classify_permission_denial(&[Some(
            "Read permission denied for /private/secret.txt",
        )])
        .expect("denial should classify");
        state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
            change_id: "execution-stall".to_string(),
            blocker: StalledBlocker::permission_denial("acceptance", &denial),
        });

        assert_eq!(state.display_status("dependency-wait"), "blocked");
        assert_eq!(state.display_status("external-wait"), "blocked");
        assert_eq!(state.display_status("execution-stall"), "stalled");

        assert_eq!(
            state
                .change_runtime("dependency-wait")
                .unwrap()
                .blocker_kind(),
            BlockerKind::Dependency
        );
        assert_eq!(
            state
                .change_runtime("external-wait")
                .unwrap()
                .blocker_kind(),
            BlockerKind::External
        );
        assert_eq!(
            state
                .change_runtime("execution-stall")
                .unwrap()
                .blocker_kind(),
            BlockerKind::None
        );

        // Every surface reads one reducer-derived view, so none of them has to
        // re-derive `blocked` versus `stalled` or the blocker kind.
        let views = state.all_blocker_views();
        assert_eq!(views["dependency-wait"].status, "blocked");
        assert_eq!(views["dependency-wait"].kind, BlockerKind::Dependency);
        assert_eq!(views["external-wait"].status, "blocked");
        assert_eq!(views["external-wait"].kind, BlockerKind::External);
        assert_eq!(views["external-wait"].origin.as_deref(), Some("acceptance"));
        assert!(views["external-wait"].unblock_condition.is_some());
        assert_eq!(views["execution-stall"].status, "stalled");
        assert_eq!(views["execution-stall"].kind, BlockerKind::None);
        assert!(views["execution-stall"].unblock_condition.is_none());

        // Only the external wait is suppressed as an external prerequisite hold.
        assert_eq!(
            state.externally_blocked_change_ids(),
            HashSet::from(["external-wait".to_string()])
        );

        // The external wait never becomes a dependency edge.
        assert!(state
            .change_runtime("external-wait")
            .unwrap()
            .blocked_metadata
            .blocker_reason
            .as_deref()
            .unwrap_or_default()
            .starts_with("external-blocked:"));
    }

    /// The whole Acceptance-owned hold is this reducer entry. It suppresses
    /// ordinary dispatch, carries resumability, is dropped by an explicit retry,
    /// and — because it is only in memory — does not exist in a fresh reducer.
    #[test]
    fn acceptance_hold_is_in_memory_only_and_clears_on_retry_or_restart() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "c".to_string(),
            blocker: StalledBlocker::acceptance_external("credential", "STAGING_API_KEY is unset"),
        });

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert!(runtime.is_external_blocked());
        assert!(runtime.is_acceptance_stalled());
        assert!(runtime.is_resumable_acceptance_stall());
        assert_eq!(
            state.acceptance_stalled_change_ids(),
            HashSet::from(["c".to_string()]),
            "the hold must be visible to queue classification"
        );
        assert_eq!(state.display_status("c"), "blocked");

        // An explicit operator retry consumes the hold in the same process, so
        // the blocked phase runs again and its fresh result reclassifies.
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(state.acceptance_stalled_change_ids().is_empty());
        let runtime = state.change_runtime("c").expect("runtime for c");
        assert!(!runtime.is_acceptance_stalled());
        assert!(!runtime.is_external_blocked());
        assert_eq!(runtime.blocker_kind(), BlockerKind::None);
        assert!(runtime.blocked_metadata.unblock_condition.is_none());
        assert_eq!(state.display_status("c"), "queued");

        // A restart is a fresh reducer: no hold survives it, so the change is
        // dispatchable again and repository evidence decides the next action.
        let restarted = OrchestratorState::new(vec!["c".to_string()], 0);
        assert!(restarted.acceptance_stalled_change_ids().is_empty());
        assert!(!restarted
            .change_runtime("c")
            .map(ChangeRuntimeState::is_external_blocked)
            .unwrap_or(false));
    }

    /// Only Acceptance-phase blockers create an Acceptance hold. An apply-origin
    /// blocker still stalls, but must not be mistaken for an acceptance-only
    /// retry candidate.
    #[test]
    fn apply_phase_blocker_stalls_without_creating_an_acceptance_hold() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let denial = crate::permission::classify_permission_denial(&[Some(
            "Read permission denied for /private/secret.txt",
        )])
        .expect("denial should classify");
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
            change_id: "c".to_string(),
            blocker: StalledBlocker::permission_denial("apply", &denial),
        });

        assert_eq!(state.display_status("c"), "stalled");
        assert!(state.acceptance_stalled_change_ids().is_empty());
    }

    /// A non-resumable Acceptance blocker holds dispatch but must not authorize
    /// an acceptance-only retry past evidence the operator still owns.
    #[test]
    fn non_resumable_acceptance_hold_is_not_retry_eligible() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "c".to_string(),
            blocker: StalledBlocker {
                resumable: false,
                ..StalledBlocker::acceptance_external("human_decision", "owner must decide")
            },
        });

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert!(runtime.is_acceptance_stalled());
        assert!(!runtime.is_resumable_acceptance_stall());
        assert_eq!(
            state.acceptance_stalled_change_ids(),
            HashSet::from(["c".to_string()])
        );
    }

    // -----------------------------------------------------------------------
    // Monotonic blocker precedence: a structured classification outranks the
    // generic blocked workspace observation the same producer emits right after
    // it. Every test below applies the exact ordered pair the external-blocker
    // path produces.
    // -----------------------------------------------------------------------

    /// Apply the compatibility workspace status the external-blocker producers
    /// emit immediately after their structured event.
    fn observe_generic_blocked_workspace(state: &mut OrchestratorState, change_id: &str) {
        state.apply_execution_event(&crate::events::ExecutionEvent::WorkspaceStatusUpdated {
            change_id: change_id.to_string(),
            workspace_name: format!("ws-{change_id}"),
            status: crate::vcs::WorkspaceStatus::Blocked,
        });
    }

    /// Reported facts that validate as an Apply-observed external prerequisite.
    fn apply_external_blocker() -> crate::events::StalledBlocker {
        crate::events::StalledBlocker {
            category: "infrastructure".to_string(),
            phase: "apply".to_string(),
            gate: "apply".to_string(),
            error_summary: "the build cache service is unreachable".to_string(),
            evidence: vec!["cargo test: connection refused to cache.internal".to_string()],
            unblock_condition: Some("cache.internal accepts connections again".to_string()),
            prerequisite_owner: Some("platform".to_string()),
            next_action: "restore cache.internal then retry apply".to_string(),
            resumable: true,
            worktree_preserved: true,
        }
    }

    /// An Acceptance-observed external wait keeps every routing-relevant field
    /// after the generic blocked workspace status the same dispatch branch
    /// emits. Before monotonic precedence this second event rebuilt the metadata
    /// as a generic stall: kind `none`, no owner, no unblock condition, and
    /// `resumable: false`.
    #[test]
    fn structured_blocker_metadata_survives_workspace_blocked_for_an_acceptance_external_wait() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "c".to_string(),
            command: "accept".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "c".to_string(),
            blocker: StalledBlocker {
                prerequisite_owner: Some("platform".to_string()),
                ..StalledBlocker::acceptance_external("credential", "STAGING_API_KEY is unset")
            },
        });
        let before = state
            .blocker_view("c")
            .expect("the structured event must establish a blocker view");

        observe_generic_blocked_workspace(&mut state, "c");

        assert_eq!(state.display_status("c"), "blocked");
        let after = state
            .blocker_view("c")
            .expect("the hold must survive the generic observation");
        assert_eq!(
            after, before,
            "a lower-fidelity observation must not change any projected blocker field"
        );
        assert_eq!(after.kind, BlockerKind::External);
        assert_eq!(after.origin.as_deref(), Some("acceptance"));
        assert_eq!(after.prerequisite_owner.as_deref(), Some("platform"));
        assert_eq!(
            after.category.as_deref(),
            Some("external-blocked:credential")
        );
        assert!(after
            .unblock_condition
            .as_deref()
            .unwrap_or_default()
            .contains("STAGING_API_KEY is unset"));
        assert!(after
            .detail
            .as_deref()
            .unwrap_or_default()
            .contains("next action"));
        assert!(after.resumable, "resumability drives explicit retry");

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert_eq!(runtime.wait_state, WaitState::ExternalBlocked);
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert!(matches!(runtime.terminal, TerminalState::None));
        assert!(runtime.blocked_metadata.acceptance_stall);
        assert!(runtime.is_resumable_acceptance_stall());

        // Queue classification and operator routing read these sets.
        assert_eq!(
            state.externally_blocked_change_ids(),
            HashSet::from(["c".to_string()]),
            "dispatch suppression must survive the generic observation"
        );
        assert_eq!(
            state.acceptance_stalled_change_ids(),
            HashSet::from(["c".to_string()])
        );
    }

    /// The same precedence protects an Apply-observed external prerequisite:
    /// origin and every structured field survive, and the wait never degrades
    /// into an Acceptance-owned hold it never was.
    #[test]
    fn structured_blocker_metadata_survives_workspace_blocked_for_an_apply_external_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
            change_id: "c".to_string(),
            blocker: apply_external_blocker(),
        });
        let before = state
            .blocker_view("c")
            .expect("a validated apply claim must establish a blocker view");

        observe_generic_blocked_workspace(&mut state, "c");

        assert_eq!(state.display_status("c"), "blocked");
        let after = state
            .blocker_view("c")
            .expect("the hold must survive the generic observation");
        assert_eq!(after, before);
        assert_eq!(after.kind, BlockerKind::External);
        assert_eq!(after.origin.as_deref(), Some("apply"));
        assert_eq!(after.prerequisite_owner.as_deref(), Some("platform"));
        assert_eq!(
            after.category.as_deref(),
            Some("external-blocked:infrastructure")
        );
        assert_eq!(
            after.unblock_condition.as_deref(),
            Some("cache.internal accepts connections again")
        );
        assert!(after.resumable);

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert_eq!(runtime.wait_state, WaitState::ExternalBlocked);
        assert!(
            !runtime.blocked_metadata.acceptance_stall,
            "an apply-origin external wait is not an Acceptance-owned hold"
        );
        assert_eq!(
            state.externally_blocked_change_ids(),
            HashSet::from(["c".to_string()]),
            "queue suppression uses the external set for either origin"
        );
        assert!(state.acceptance_stalled_change_ids().is_empty());
    }

    /// An Acceptance-owned non-external execution hold stays `stalled` and keeps
    /// its Acceptance ownership and resumability. Losing either would let the
    /// applied workspace be dispatched back through Acceptance automatically.
    #[test]
    fn structured_blocker_metadata_survives_workspace_blocked_for_an_acceptance_owned_stall() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let denial = crate::permission::classify_permission_denial(&[Some(
            "Read permission denied for /private/secret.txt",
        )])
        .expect("denial should classify");
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
            change_id: "c".to_string(),
            blocker: StalledBlocker::permission_denial("acceptance", &denial),
        });
        let before = state
            .blocker_view("c")
            .expect("an acceptance-owned hold must establish a blocker view");

        observe_generic_blocked_workspace(&mut state, "c");

        assert_eq!(state.display_status("c"), "stalled");
        let after = state
            .blocker_view("c")
            .expect("the hold must survive the generic observation");
        assert_eq!(after, before);
        assert_eq!(after.kind, BlockerKind::None);
        assert!(after.resumable);
        assert_eq!(
            after.category.as_deref(),
            Some("execution-blocked:permission:file_read")
        );
        assert!(after
            .detail
            .as_deref()
            .unwrap_or_default()
            .contains("permission"));

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert_eq!(runtime.wait_state, WaitState::Stalled);
        assert!(runtime.blocked_metadata.acceptance_stall);
        assert!(runtime.is_resumable_acceptance_stall());
        assert_eq!(
            state.acceptance_stalled_change_ids(),
            HashSet::from(["c".to_string()]),
            "ordinary dispatch stays suppressed until explicit retry or restart"
        );
        assert!(state.externally_blocked_change_ids().is_empty());
    }

    /// Without a structured classification the generic observation still owns
    /// the wait: the conservative `stalled` fallback that rejection and legacy
    /// apply handoffs depend on is unchanged, and it invents no external facts.
    #[test]
    fn structured_blocker_metadata_survives_workspace_blocked_fallback_stays_generic_without_a_hold(
    ) {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&crate::events::ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "apply".to_string(),
        });

        observe_generic_blocked_workspace(&mut state, "c");

        assert_eq!(state.display_status("c"), "stalled");
        let view = state
            .blocker_view("c")
            .expect("the fallback still records a blocker view");
        assert_eq!(view.kind, BlockerKind::None);
        assert!(view.unblock_condition.is_none());
        assert!(view.prerequisite_owner.is_none());
        assert!(view.origin.is_none());
        assert!(!view.resumable);
        assert_eq!(
            view.category.as_deref(),
            Some("apply reported recoverable blocker; workspace remains stalled")
        );

        let runtime = state.change_runtime("c").expect("runtime for c");
        assert_eq!(runtime.wait_state, WaitState::Stalled);
        assert!(!runtime.blocked_metadata.acceptance_stall);
        assert!(state.acceptance_stalled_change_ids().is_empty());
        assert!(state.externally_blocked_change_ids().is_empty());

        // The `mark_stalled` fallback keeps its own generic message too.
        let mut marked = OrchestratorState::new(vec!["d".to_string()], 0);
        marked.mark_stalled("d".to_string());
        observe_generic_blocked_workspace(&mut marked, "d");
        assert_eq!(marked.display_status("d"), "stalled");
        assert_eq!(
            marked
                .change_runtime("d")
                .unwrap()
                .blocked_metadata
                .blocker_reason
                .as_deref(),
            Some("change stalled with recoverable blocker")
        );
    }

    /// Duplicate and replayed generic observations stay idempotent, and the
    /// existing explicit-retry boundary still releases the hold afterwards.
    #[test]
    fn structured_blocker_metadata_survives_workspace_blocked_under_duplicate_delivery() {
        use crate::events::{ExecutionEvent, StalledBlocker};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "c".to_string(),
            blocker: StalledBlocker::acceptance_external("credential", "STAGING_API_KEY is unset"),
        });
        let before = state.blocker_view("c").expect("blocker view");

        for _ in 0..3 {
            observe_generic_blocked_workspace(&mut state, "c");
        }
        assert_eq!(state.blocker_view("c").as_ref(), Some(&before));
        assert_eq!(state.display_status("c"), "blocked");

        // Precedence protects metadata; it does not make a hold permanent.
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert_eq!(state.display_status("c"), "queued");
        assert!(state.blocker_view("c").is_none());
        assert!(state.externally_blocked_change_ids().is_empty());
    }

    #[test]
    fn test_rejection_review_block_transitions_to_blocked_with_metadata() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ProcessingStarted("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "c".to_string(),
            workspace_name: "ws-c".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });
        assert_eq!(state.display_status("c"), "rejecting");

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "c".to_string(),
            outcome: RejectionOutcome::Block,
        });

        let runtime = state
            .change_runtime("c")
            .expect("runtime for c after rejecting block");
        assert_eq!(state.display_status("c"), "stalled");
        assert_eq!(runtime.activity, ActivityState::Idle);
        assert_eq!(runtime.wait_state, WaitState::Stalled);
        assert!(matches!(runtime.terminal, TerminalState::None));
        assert_eq!(
            runtime.blocked_metadata.blocker_reason.as_deref(),
            Some("rejection review returned block; unresolved blocker remains")
        );
        assert_eq!(
            runtime.blocked_metadata.unblock_metadata.as_deref(),
            Some(
                "resolve unresolved blocker tasks in openspec/changes/<change_id>/tasks.md, then trigger explicit resume"
            )
        );
        assert_eq!(
            runtime.blocked_metadata.worktree_snapshot.as_deref(),
            Some("existing worktree and WIP context are preserved for stalled rejection review")
        );
    }

    #[test]
    fn test_rejection_review_resume_from_archived_workspace_context_sets_applying() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Resume path can start from an archived workspace that re-entered rejecting review.
        state.runtime_entry("c").wait_state = WaitState::MergeWait;
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        assert_eq!(state.display_status("c"), "merge wait");

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "c".to_string(),
            workspace_name: "ws-c".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });
        assert_eq!(state.display_status("c"), "rejecting");

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "c".to_string(),
            outcome: RejectionOutcome::Resume,
        });

        assert_eq!(state.display_status("c"), "applying");
    }

    #[test]
    fn test_rejection_review_block_from_archived_workspace_context_sets_stalled() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.runtime_entry("c").wait_state = WaitState::MergeWait;
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        assert_eq!(state.display_status("c"), "merge wait");

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "c".to_string(),
            workspace_name: "ws-c".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });
        assert_eq!(state.display_status("c"), "rejecting");

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "c".to_string(),
            outcome: RejectionOutcome::Block,
        });

        assert_eq!(state.display_status("c"), "stalled");
    }

    // -----------------------------------------------------------------------
    // Phase 2.4: apply_observation reconcile
    // -----------------------------------------------------------------------

    #[test]
    fn test_apply_observation_reconcile_merge_wait() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // WorkspaceArchived preserves an already-established concrete MergeWait.
        state.runtime_entry("c").wait_state = WaitState::MergeWait;
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        assert_eq!(state.display_status("c"), "merge wait");

        // WorktreeNotAhead → clears MergeWait.
        state.apply_observation("c", WorkspaceObservation::WorktreeNotAhead);
        assert_eq!(state.display_status("c"), "not queued");

        // Active execution prevents observation from overwriting.
        state.runtime_entry("c").activity = ActivityState::Applying;
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        // Still applying (not overwritten).
        assert_eq!(state.display_status("c"), "applying");
    }

    // -----------------------------------------------------------------------
    // Phase 2.5: idempotency and late-event precedence
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // Phase 5.2: changes_refreshed uses reducer observation path
    // -----------------------------------------------------------------------

    #[test]
    fn test_changes_refreshed_uses_reducer_observation_path() {
        use crate::events::ExecutionEvent;
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Simulate a ChangesRefreshed with c in merge_wait_ids after a concrete manual
        // MergeDeferred(auto_resumable=false) had already established MergeWait.
        state.runtime_entry("c").wait_state = WaitState::MergeWait;
        let mut merge_wait_ids = HashSet::new();
        merge_wait_ids.insert("c".to_string());
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids,
        });

        // The reducer should have set MergeWait via apply_observation.
        assert_eq!(state.display_status("c"), "merge wait");
    }

    #[test]
    fn test_change_rejected_clears_only_target_queue_intent() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        state.apply_command(ReducerCommand::AddToQueue("a".to_string()));
        state.apply_command(ReducerCommand::AddToQueue("b".to_string()));
        assert_eq!(state.display_status("a"), "queued");
        assert_eq!(state.display_status("b"), "queued");

        state.apply_execution_event(&ExecutionEvent::ChangeRejected {
            change_id: "a".to_string(),
            reason: "blocked".to_string(),
        });

        assert_eq!(state.display_status("a"), "rejected");
        assert_eq!(state.display_status("b"), "queued");
    }

    #[test]
    fn test_changes_refreshed_reactivates_rejected_change() {
        use crate::events::ExecutionEvent;
        use crate::openspec::{Change, ProposalMetadata};
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Previously rejected and with stale non-default runtime fields.
        let rt = state.runtime_entry("c");
        rt.terminal = TerminalState::Rejected("blocked".to_string());
        rt.activity = ActivityState::Rejecting;
        rt.wait_state = WaitState::MergeWait;
        rt.queue_intent = QueueIntent::Queued;

        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![Change {
                id: "c".to_string(),
                completed_tasks: 0,
                total_tasks: 1,
                last_modified: "now".to_string(),
                dependencies: Vec::new(),
                metadata: ProposalMetadata::default(),
            }],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        });

        let rt = state.change_runtime("c").expect("runtime for c");
        assert!(matches!(rt.terminal, TerminalState::None));
        assert!(matches!(rt.activity, ActivityState::Idle));
        assert!(matches!(rt.wait_state, WaitState::None));
        assert!(matches!(rt.queue_intent, QueueIntent::NotQueued));
        assert_eq!(state.display_status("c"), "not queued");
    }

    // -----------------------------------------------------------------------
    // Phase 5.3: merge wait release after external merge
    // -----------------------------------------------------------------------

    #[test]
    fn test_merge_wait_release_after_external_merge() {
        use crate::events::ExecutionEvent;
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Put into MergeWait.
        state.runtime_entry("c").wait_state = WaitState::MergeWait;
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        assert_eq!(state.display_status("c"), "merge wait");

        // Refreshed with c in worktree_not_ahead_ids → clears MergeWait.
        let mut not_ahead = HashSet::new();
        not_ahead.insert("c".to_string());
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: not_ahead,
            merge_wait_ids: HashSet::new(),
        });
        assert_eq!(state.display_status("c"), "not queued");
    }

    // -----------------------------------------------------------------------
    // Startup reconciliation: archived-but-not-yet-merged workspace evidence
    // -----------------------------------------------------------------------

    /// A `ChangesRefreshed` carrying only archived-but-not-yet-merged evidence.
    fn startup_refresh(merge_wait_ids: &[&str]) -> crate::events::ExecutionEvent {
        use std::collections::{HashMap, HashSet};

        crate::events::ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: merge_wait_ids.iter().map(|id| id.to_string()).collect(),
        }
    }

    #[test]
    fn startup_refresh_restores_merge_wait_for_a_fresh_idle_change() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        assert_eq!(state.display_status("alpha"), "not queued");

        state.apply_execution_event(&startup_refresh(&["alpha"]));

        assert_eq!(state.display_status("alpha"), "merge wait");
        assert!(matches!(
            state.change_runtime("alpha").unwrap().wait_state,
            WaitState::MergeWait
        ));
        assert!(
            state.resolve_wait_change_ids().is_empty(),
            "restoring the wait must not enqueue scheduler-owned resolve work"
        );
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn startup_refresh_merge_wait_restoration_is_idempotent() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&startup_refresh(&["alpha"]));
        state.apply_execution_event(&startup_refresh(&["alpha"]));

        assert_eq!(state.display_status("alpha"), "merge wait");
        assert!(state.resolve_wait_change_ids().is_empty());
    }

    #[test]
    fn startup_refresh_does_not_regress_stronger_reducer_state_to_merge_wait() {
        use crate::events::ExecutionEvent;

        // Drives a fresh state through the reducer transitions a case needs.
        type CaseSetup = Box<dyn Fn(&mut OrchestratorState)>;

        // Each case is set up through the same reducer transitions production uses,
        // then re-observed with the change still reported as archived-but-not-merged.
        let cases: Vec<(&str, &str, CaseSetup)> = vec![
            (
                "resolving",
                "resolving",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_execution_event(&ExecutionEvent::ChangeArchived("x".to_string()));
                }),
            ),
            (
                "resolve pending",
                "resolve pending",
                Box::new(|state: &mut OrchestratorState| {
                    state.runtime_entry("x").wait_state = WaitState::MergeWait;
                    state.apply_command(ReducerCommand::ResolveMerge("x".to_string()));
                }),
            ),
            (
                "rejecting",
                "rejecting",
                Box::new(|state: &mut OrchestratorState| {
                    state.runtime_entry("x").activity = ActivityState::Rejecting;
                }),
            ),
            (
                "reject pending",
                "reject pending",
                Box::new(|state: &mut OrchestratorState| {
                    // Rejection review only waits while another change holds the
                    // single base-mutating lane.
                    state.runtime_entry("lane").activity = ActivityState::Resolving;
                    state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
                        change_id: "x".to_string(),
                        workspace_name: "ws-x".to_string(),
                        status: crate::vcs::WorkspaceStatus::Rejecting,
                    });
                }),
            ),
            (
                "queued",
                "queued",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_command(ReducerCommand::AddToQueue("x".to_string()));
                }),
            ),
            (
                "merged",
                "merged",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_execution_event(&ExecutionEvent::MergeCompleted {
                        change_id: "x".to_string(),
                        revision: "rev-x".to_string(),
                    });
                }),
            ),
            (
                "rejected",
                "rejected",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_execution_event(&ExecutionEvent::ChangeRejected {
                        change_id: "x".to_string(),
                        reason: "blocked".to_string(),
                    });
                }),
            ),
            (
                "error",
                "error",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_execution_event(&ExecutionEvent::ProcessingError {
                        id: "x".to_string(),
                        error: "boom".to_string(),
                    });
                }),
            ),
            (
                "stopped",
                "stopped",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_command(ReducerCommand::StopChange("x".to_string()));
                }),
            ),
            (
                "blocked",
                "blocked",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_execution_event(&ExecutionEvent::DependencyBlocked {
                        change_id: "x".to_string(),
                        dependency_ids: vec!["dep".to_string()],
                    });
                }),
            ),
            (
                "dequeued",
                "not queued",
                Box::new(|state: &mut OrchestratorState| {
                    state.apply_command(ReducerCommand::AddToQueue("x".to_string()));
                    state.apply_command(ReducerCommand::DequeueChange("x".to_string()));
                }),
            ),
        ];

        for (label, expected, setup) in cases {
            // `lane` exists only so a case can occupy the single base-mutating lane.
            let mut state = OrchestratorState::new(vec!["x".to_string(), "lane".to_string()], 0);
            setup(&mut state);
            assert_eq!(state.display_status("x"), expected, "setup for {}", label);
            let resolve_wait_before = state.resolve_wait_change_ids();
            let reject_wait_before = state.reject_wait_change_ids();

            state.apply_execution_event(&startup_refresh(&["x"]));

            assert_eq!(
                state.display_status("x"),
                expected,
                "refresh evidence must not regress {} to merge wait",
                label
            );
            assert_eq!(
                state.resolve_wait_change_ids(),
                resolve_wait_before,
                "refresh must not create a duplicate manual resolve reservation for {}",
                label
            );
            assert_eq!(
                state.reject_wait_change_ids(),
                reject_wait_before,
                "refresh must not disturb reject-wait membership for {}",
                label
            );
            assert!(state.global_invariants_hold(), "invariants for {}", label);
        }
    }

    // -----------------------------------------------------------------------
    // Phase 5.4: WorkspaceState::Archived recovers MergeWait (not ResolveWait)
    // -----------------------------------------------------------------------

    #[test]
    fn test_workspace_archived_recovers_merge_wait() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // WorkspaceArchived observation preserves concrete MergeWait evidence.
        state.runtime_entry("c").wait_state = WaitState::MergeWait;
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        assert_eq!(state.display_status("c"), "merge wait");
        assert!(
            matches!(
                state.change_runtime("c").unwrap().wait_state,
                WaitState::MergeWait
            ),
            "observation should set MergeWait, not ResolveWait"
        );
    }

    // -----------------------------------------------------------------------
    // Phase 5.5: queue-added change not overwritten by MergeWait refresh
    // -----------------------------------------------------------------------

    #[test]
    fn test_queue_add_not_overwritten_by_merge_wait_refresh() {
        use crate::events::ExecutionEvent;
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Queue the change.
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert_eq!(state.display_status("c"), "queued");

        // A bare archived workspace observation is only a milestone and must not
        // create MergeWait without concrete MergeDeferred(auto_resumable=false) evidence.
        state.apply_observation("c", WorkspaceObservation::WorkspaceArchived);
        assert_eq!(state.display_status("c"), "queued");

        // WorktreeNotAhead remains idempotent when no MergeWait exists.
        let mut not_ahead = HashSet::new();
        not_ahead.insert("c".to_string());
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: not_ahead,
            merge_wait_ids: HashSet::new(),
        });
        // After clearing MergeWait, the queue intent (Queued) is visible again.
        assert_eq!(state.display_status("c"), "queued");
    }

    #[test]
    fn test_base_mutating_lane_exclusivity_and_wait_membership() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(
            vec![
                "resolving-a".to_string(),
                "rejecting-b".to_string(),
                "archive-c".to_string(),
            ],
            0,
        );

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "resolving-a".to_string(),
            workspace_name: "ws-a".to_string(),
            status: crate::vcs::WorkspaceStatus::Resolving,
        });
        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "rejecting-b".to_string(),
            workspace_name: "ws-b".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });

        assert_eq!(state.display_status("resolving-a"), "resolving");
        assert_eq!(state.display_status("rejecting-b"), "reject pending");
        assert_eq!(
            state.reject_wait_change_ids(),
            vec!["rejecting-b".to_string()]
        );
        assert!(state.resolve_wait_change_ids().is_empty());
        assert!(state.has_other_post_archive_lane_blocker("archive-c"));
        assert!(state.global_invariants_hold());

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("archive-c".to_string()));
        assert_eq!(state.display_status("archive-c"), "resolve pending");
        assert_eq!(
            state.resolve_wait_change_ids(),
            vec!["archive-c".to_string()]
        );
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_reject_wait_clear_and_deterministic_single_promotion() {
        use crate::events::{ExecutionEvent, RejectionOutcome};

        let mut state = OrchestratorState::new(
            vec![
                "lane-a".to_string(),
                "resolve-b".to_string(),
                "reject-c".to_string(),
            ],
            0,
        );

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "lane-a".to_string(),
            workspace_name: "ws-a".to_string(),
            status: crate::vcs::WorkspaceStatus::Resolving,
        });
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("resolve-b".to_string()));
        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "reject-c".to_string(),
            workspace_name: "ws-c".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });

        assert_eq!(state.display_status("resolve-b"), "resolve pending");
        assert_eq!(state.display_status("reject-c"), "reject pending");

        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "lane-a".to_string(),
            error: "manual blocker".to_string(),
        });
        let promoted = state.promote_next_base_mutating_lane_waiter();
        assert_eq!(
            promoted,
            Some(("resolve-b".to_string(), WaitState::ResolveWait))
        );
        assert_eq!(state.display_status("resolve-b"), "resolving");
        assert_eq!(state.display_status("reject-c"), "reject pending");
        assert!(state.global_invariants_hold());

        assert_eq!(state.promote_next_base_mutating_lane_waiter(), None);
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "resolve-b".to_string(),
            revision: "rev-b".to_string(),
        });
        let promoted = state.promote_next_base_mutating_lane_waiter();
        assert_eq!(
            promoted,
            Some(("reject-c".to_string(), WaitState::RejectWait))
        );
        assert_eq!(state.display_status("reject-c"), "rejecting");
        assert!(state.reject_wait_change_ids().is_empty());
        assert!(state.global_invariants_hold());

        state.apply_execution_event(&ExecutionEvent::RejectionReviewCompleted {
            change_id: "reject-c".to_string(),
            outcome: RejectionOutcome::Resume,
        });
        assert!(state.reject_wait_change_ids().is_empty());
        assert_eq!(state.display_status("reject-c"), "applying");
    }

    // -----------------------------------------------------------------------
    // Phase 4.3: parallel merge events drive reducer wait states
    // -----------------------------------------------------------------------

    #[test]
    fn test_parallel_change_archived_no_blocker_enters_resolving_not_merge_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));

        assert_eq!(state.display_status("c"), "resolving");
        assert!(
            state.resolve_wait_change_ids().is_empty(),
            "no-blocker archive completion must enter immediate merge handling, not resolve wait"
        );
        assert!(
            state.queued_change_ids().is_empty(),
            "no-blocker archive completion must not be reintroduced as ordinary queued work"
        );
    }

    #[test]
    fn test_no_blocker_merge_wait_to_merged_vibration_regression() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        assert_eq!(state.display_status("c"), "resolving");

        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["c".to_string()]),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::from(["c".to_string()]),
        });
        assert_eq!(
            state.display_status("c"),
            "resolving",
            "workspace refresh must not turn active no-blocker merge handling into merge wait"
        );

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");
    }

    #[test]
    fn test_merged_archived_vibration_regression() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        assert_eq!(state.display_status("c"), "merged");

        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["c".to_string()]),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::from(["c".to_string()]),
        });
        assert_eq!(state.display_status("c"), "merged");
    }

    #[test]
    fn test_manual_merge_deferred_clears_normal_queue_intent() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert_eq!(state.queued_change_ids(), vec!["c".to_string()]);

        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });

        assert_eq!(state.display_status("c"), "merge wait");
        assert!(
            state.queued_change_ids().is_empty(),
            "manual merge deferral must consume ordinary queue intent"
        );
        assert!(
            state.resolve_wait_change_ids().is_empty(),
            "manual merge deferral must not remain scheduler-owned resolve retry intent"
        );
    }

    #[test]
    fn test_manual_merge_deferred_clears_existing_resolve_wait_queue_membership() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "another merge is in progress".to_string(),
            auto_resumable: true,
        });
        assert_eq!(state.display_status("c"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["c".to_string()]);

        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });

        assert_eq!(state.display_status("c"), "merge wait");
        assert!(state.queued_change_ids().is_empty());
        assert!(state.resolve_wait_change_ids().is_empty());
    }

    #[test]
    fn test_manual_merge_deferred_resolve_merge_explicit_retry_sets_resolve_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("c"), "merge wait");
        assert!(state.queued_change_ids().is_empty());

        let outcome = state.apply_command(ReducerCommand::ResolveMerge("c".to_string()));

        assert!(matches!(outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["c".to_string()]);
        assert!(
            state.queued_change_ids().is_empty(),
            "explicit merge retry must use resolve-wait intent, not normal queue intent"
        );
    }

    /// Archive is never terminal on its own: it enters active post-archive
    /// handling, so an explicit manual retry there changes nothing, while a
    /// concrete manual wait is still admitted as scheduler-consumable intent.
    #[test]
    fn test_archived_change_enters_active_merge_handling_before_manual_retry() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&crate::events::ExecutionEvent::ChangeArchived(
            "alpha".to_string(),
        ));
        assert_eq!(
            state.display_status("alpha"),
            "resolving",
            "archive alone must never be terminal"
        );

        assert!(
            matches!(
                state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string())),
                ReduceOutcome::NoOp
            ),
            "a row already in active merge handling needs no manual retry"
        );
        assert_eq!(state.display_status("alpha"), "resolving");

        // A concrete manual deferral is what makes the retry meaningful.
        state.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "manual resolution required".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("alpha"), "merge wait");

        let outcome = state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));

        assert!(
            matches!(outcome, ReduceOutcome::Changed(_)),
            "explicit manual retry for a merge-wait row must not be dropped"
        );
        assert_eq!(state.display_status("alpha"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["alpha".to_string()]);
        assert!(state.queued_change_ids().is_empty());
    }

    #[test]
    fn test_merged_manual_retry_remains_noop() {
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&crate::events::ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "rev-alpha".to_string(),
        });

        let outcome = state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));

        assert!(matches!(outcome, ReduceOutcome::NoOp));
        assert_eq!(state.display_status("alpha"), "merged");
        assert!(state.resolve_wait_change_ids().is_empty());
    }

    #[test]
    fn test_auto_resumable_merge_deferred_keeps_scheduler_retry_intent() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "another merge is in progress".to_string(),
            auto_resumable: true,
        });

        assert_eq!(state.display_status("c"), "resolve pending");
        assert_eq!(state.queued_change_ids(), vec!["c".to_string()]);
        assert_eq!(state.resolve_wait_change_ids(), vec!["c".to_string()]);
    }

    #[test]
    fn test_archive_merge_defers_to_resolve_pending_when_rejecting_active() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "a".to_string(),
            workspace_name: "ws-a".to_string(),
            status: crate::vcs::WorkspaceStatus::Rejecting,
        });
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("b".to_string()));

        assert_eq!(state.display_status("a"), "rejecting");
        assert_eq!(state.display_status("b"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["b".to_string()]);
        assert!(state.reject_wait_change_ids().is_empty());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_active_applying_does_not_create_resolve_pending_on_archive() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "a".to_string(),
            command: "apply".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("b".to_string()));

        assert_eq!(state.display_status("a"), "applying");
        assert_eq!(state.display_status("b"), "resolving");
        assert!(state.resolve_wait_change_ids().is_empty());
    }

    #[test]
    fn test_parallel_merge_events_drive_reducer_wait_states() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // MergeDeferred (manual, not auto-resumable) → MergeWait
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("c"), "merge wait");

        // ResolveStarted → Resolving (clears MergeWait)
        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "c".to_string(),
            command: "resolve".to_string(),
        });
        assert_eq!(state.display_status("c"), "resolving");

        // ResolveCompleted → Merged (terminal): successful resolve means the change is merged.
        state.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "c".to_string(),
            worktree_change_ids: None,
        });
        assert_eq!(state.display_status("c"), "merged");

        // MergeCompleted is idempotent once already terminal (parallel orchestrator path).
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        // ResolveFailed after Merged must NOT regress.
        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "c".to_string(),
            error: "late".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");
    }

    // -----------------------------------------------------------------------
    // Regression: stale ResolveWait must not survive ResolveCompleted + refresh
    // -----------------------------------------------------------------------
    //
    // Scenario: base dirtiness caused MergeWait, user triggered manual resolve
    // (ResolveMerge command → ResolveWait), resolve succeeded, but the row was
    // previously stuck at "resolve pending" because ResolveCompleted was not
    // applied to the shared reducer before the next ChangesRefreshed.

    #[test]
    fn test_merge_completed_ignores_later_stale_manual_merge_deferred() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "rev-alpha".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "Archive incomplete for 'alpha': worktree may be dirty".to_string(),
            auto_resumable: false,
        });

        assert_eq!(state.display_status("alpha"), "merged");
        assert!(state.queued_change_ids().is_empty());
        assert!(state.resolve_wait_change_ids().is_empty());
    }

    #[test]
    fn test_merge_completed_clears_resolve_wait_intent() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "Resolve in progress for another change".to_string(),
            auto_resumable: true,
        });
        assert_eq!(state.resolve_wait_change_ids(), vec!["alpha".to_string()]);

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "rev-alpha".to_string(),
        });

        assert_eq!(state.display_status("alpha"), "merged");
        assert!(
            state.resolve_wait_change_ids().is_empty(),
            "MergeCompleted must clear reducer-owned ResolveWait retry intent"
        );
    }

    #[test]
    fn test_clear_resolve_wait_intent_removes_retry_without_terminal_transition() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "Resolve in progress for another change".to_string(),
            auto_resumable: true,
        });
        assert_eq!(state.resolve_wait_change_ids(), vec!["alpha".to_string()]);

        state.clear_resolve_wait_intent("alpha");

        assert!(state.resolve_wait_change_ids().is_empty());
        // Releasing the reservation records no outcome, so the change falls back
        // to the retryable manual wait instead of an idle `not queued` row.
        assert_eq!(state.display_status("alpha"), "merge wait");
        assert!(!state.is_terminal_change("alpha"));
    }

    /// Reducer settlement table for a stale deferred resolve retry.
    ///
    /// The failure this guards is concrete: `ReducerCommand::ResolveMerge` leaves
    /// `QueueIntent::NotQueued` behind the `ResolveWait`, so clearing the wait on
    /// its own used to display `not queued` for a change the base tree already
    /// contains.
    fn manual_resolve_retry_state(change_id: &str) -> OrchestratorState {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec![change_id.to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: change_id.to_string(),
            reason: "manual conflict".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status(change_id), "merge wait");
        state.apply_command(ReducerCommand::ResolveMerge(change_id.to_string()));
        assert_eq!(state.display_status(change_id), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec![change_id.to_string()]);
        state
    }

    #[test]
    fn stale_deferred_merge_retry_with_proven_base_integration_settles_merged() {
        let mut state = manual_resolve_retry_state("alpha");

        let settlement = state.settle_stale_resolve_retry("alpha", StaleResolveEvidence::Proven);

        assert_eq!(settlement, StaleResolveSettlement::Merged);
        assert_eq!(state.display_status("alpha"), "merged");
        assert_ne!(state.display_status("alpha"), "not queued");
        assert!(state.is_terminal_change("alpha"));
        assert!(state.resolve_wait_change_ids().is_empty());
        assert!(state.resolve_wait_queue.is_empty());
        assert!(!state.is_base_mutating_lane_occupied());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn stale_deferred_merge_retry_without_proven_integration_retains_merge_wait() {
        for evidence in [StaleResolveEvidence::Absent, StaleResolveEvidence::Unknown] {
            let mut state = manual_resolve_retry_state("alpha");

            let settlement = state.settle_stale_resolve_retry("alpha", evidence);

            assert_eq!(
                settlement,
                StaleResolveSettlement::MergeWaitRetained,
                "{evidence:?} proves nothing and must stay retryable"
            );
            assert_eq!(
                state.display_status("alpha"),
                "merge wait",
                "{evidence:?} must not expose not queued or merged"
            );
            assert!(!state.is_terminal_change("alpha"));
            assert!(state.resolve_wait_change_ids().is_empty());
            assert!(state.resolve_wait_queue.is_empty());
            assert!(state.global_invariants_hold());

            // The operator can still retry explicitly from the retained state.
            state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string()));
            assert_eq!(state.display_status("alpha"), "resolve pending");
        }
    }

    #[test]
    fn stale_deferred_merge_retry_settles_promoted_lane_occupant() {
        let mut state = manual_resolve_retry_state("alpha");
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("alpha".to_string(), WaitState::ResolveWait))
        );
        assert!(state.is_base_mutating_lane_occupied());

        let settlement = state.settle_stale_resolve_retry("alpha", StaleResolveEvidence::Absent);

        assert_eq!(settlement, StaleResolveSettlement::MergeWaitRetained);
        assert_eq!(state.display_status("alpha"), "merge wait");
        assert!(
            !state.is_base_mutating_lane_occupied(),
            "settlement releases base-lane ownership once the reducer state agrees"
        );
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn stale_deferred_merge_retry_preserves_immutable_terminal_outcomes() {
        let mut state = manual_resolve_retry_state("alpha");
        state.apply_command(ReducerCommand::StopChange("alpha".to_string()));
        assert_eq!(state.display_status("alpha"), "stopped");

        let settlement = state.settle_stale_resolve_retry("alpha", StaleResolveEvidence::Proven);

        assert_eq!(settlement, StaleResolveSettlement::AlreadySettled);
        assert_eq!(state.display_status("alpha"), "stopped");
        assert!(state.resolve_wait_change_ids().is_empty());
        assert!(state.resolve_wait_queue.is_empty());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn stale_deferred_merge_retry_keeps_bounded_resolve_failure_in_merge_wait() {
        use crate::events::ExecutionEvent;

        let mut state = manual_resolve_retry_state("alpha");
        assert_eq!(
            state.promote_next_base_mutating_lane_waiter(),
            Some(("alpha".to_string(), WaitState::ResolveWait))
        );

        // Ordinary bounded exhaustion is unchanged by stale settlement: one
        // change-scoped ResolveFailed returns the change to manual merge wait.
        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: "bounded resolve exhausted".to_string(),
        });

        assert_eq!(state.display_status("alpha"), "merge wait");
        assert!(!state.is_terminal_change("alpha"));
        assert!(state.resolve_wait_change_ids().is_empty());
        assert!(!state.is_base_mutating_lane_occupied());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_resolve_completed_clears_resolve_wait_and_survives_refresh() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Step 1: concrete manual merge blocker -> enters MergeWait.
        // A bare ChangeArchived event now truthfully enters active post-archive
        // merge handling; only MergeDeferred(auto_resumable=false) represents
        // operator-owned manual merge wait.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("c"), "merge wait");

        // Step 2: user triggers manual resolve → reducer transitions to ResolveWait.
        state.apply_command(ReducerCommand::ResolveMerge("c".to_string()));
        assert_eq!(state.display_status("c"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["c".to_string()]);

        // Step 3: a refresh still sees merge_wait/worktree branch and emits observations.
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: std::collections::HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: std::collections::HashSet::new(),
            worktree_change_ids: std::collections::HashSet::from(["c".to_string()]),
            worktree_paths: std::collections::HashMap::new(),
            worktree_not_ahead_ids: std::collections::HashSet::new(),
            merge_wait_ids: std::collections::HashSet::from(["c".to_string()]),
        });
        assert_eq!(state.display_status("c"), "resolve pending");

        // Step 4: resolve succeeds → must transition to merged, not stall at resolve pending.
        state.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "c".to_string(),
            worktree_change_ids: None,
        });
        assert_eq!(state.display_status("c"), "merged");
        assert!(
            state.resolve_wait_change_ids().is_empty(),
            "resolve completion must clear queued resolve intent"
        );

        // Step 5: another refresh still seeing stale merge_wait/worktree signals
        // must NOT regress the row back to "resolve pending" or "merge wait".
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: std::collections::HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: std::collections::HashSet::new(),
            worktree_change_ids: std::collections::HashSet::from(["c".to_string()]),
            worktree_paths: std::collections::HashMap::new(),
            worktree_not_ahead_ids: std::collections::HashSet::new(),
            merge_wait_ids: std::collections::HashSet::from(["c".to_string()]),
        });
        assert_eq!(state.display_status("c"), "merged");
        assert_ne!(
            state.display_status("c"),
            "resolve pending",
            "row must not regress to resolve pending after successful resolve + refresh"
        );
    }

    #[test]
    fn test_resolve_wait_manual_merge_deferred_demotes_to_merge_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["change-a".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "change-a".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("change-a".to_string()));
        assert_eq!(state.display_status("change-a"), "resolve pending");
        assert_eq!(
            state.resolve_wait_change_ids(),
            vec!["change-a".to_string()]
        );

        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "change-a".to_string(),
            reason: "Working tree has uncommitted changes".to_string(),
            auto_resumable: false,
        });

        assert_eq!(state.display_status("change-a"), "merge wait");
        assert!(
            state.resolve_wait_change_ids().is_empty(),
            "manual retry deferral must remove reducer-owned ResolveWait membership"
        );
        assert!(state.queued_change_ids().is_empty());
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_resolve_wait_clean_lane_promotion_promotes_exactly_one_waiter() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["alpha".to_string(), "beta".to_string()], 0);

        for change_id in ["alpha", "beta"] {
            state.apply_execution_event(&ExecutionEvent::MergeDeferred {
                change_id: change_id.to_string(),
                reason: "base dirty".to_string(),
                auto_resumable: false,
            });
            state.apply_command(ReducerCommand::ResolveMerge(change_id.to_string()));
        }

        let promoted = state.promote_next_base_mutating_lane_waiter();

        assert_eq!(
            promoted,
            Some(("alpha".to_string(), WaitState::ResolveWait))
        );
        assert_eq!(state.display_status("alpha"), "resolving");
        assert_eq!(state.display_status("beta"), "resolve pending");
        assert_eq!(state.resolve_wait_change_ids(), vec!["beta".to_string()]);
        assert_eq!(state.promote_next_base_mutating_lane_waiter(), None);
        assert!(state.global_invariants_hold());
    }

    #[test]
    fn test_resolve_failed_restores_merge_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Reach MergeWait via manual-intervention deferral, then promote to ResolveWait.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        state.apply_command(ReducerCommand::ResolveMerge("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "c".to_string(),
            command: "resolve".to_string(),
        });

        // Resolve fails → must return to merge wait, not stay queued/idle.
        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "c".to_string(),
            error: "conflict".to_string(),
        });
        assert_eq!(state.display_status("c"), "merge wait");

        // A subsequent RefreshFailed-after-terminal must not regress a Merged entry.
        let mut state2 = OrchestratorState::new(vec!["c".to_string()], 0);
        state2.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        state2.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "c".to_string(),
            error: "late".to_string(),
        });
        assert_eq!(state2.display_status("c"), "merged");
    }

    // -----------------------------------------------------------------------
    // Phase 4.4: late events after stop do not regress state
    // -----------------------------------------------------------------------

    #[test]
    fn test_workspace_status_update_targets_explicit_change_id() {
        use crate::events::ExecutionEvent;
        use crate::vcs::WorkspaceStatus;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "a".to_string(),
            command: "apply-a".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "b".to_string(),
            command: "apply-b".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "b".to_string(),
            workspace_name: "ws-b".to_string(),
            status: WorkspaceStatus::Rejecting,
        });

        assert_eq!(state.display_status("a"), "applying");
        assert_eq!(state.display_status("b"), "rejecting");
    }

    #[test]
    fn test_late_events_after_stop_do_not_regress_state() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Dequeue the change.
        state.apply_execution_event(&ExecutionEvent::ChangeDequeued {
            change_id: "c".to_string(),
        });
        assert_eq!(state.display_status("c"), "not queued");

        // Late ApplyStarted must not regress from dequeued state.
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(state.display_status("c"), "not queued");

        // Late AcceptanceStarted must not regress from dequeued state.
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(state.display_status("c"), "not queued");

        // Late ProcessingError must not regress from dequeued state.
        state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "c".to_string(),
            error: "late error".to_string(),
        });
        assert_eq!(state.display_status("c"), "not queued");
    }

    // -----------------------------------------------------------------------
    // Phase 2.5: idempotency and late-event precedence
    // -----------------------------------------------------------------------

    #[test]
    fn test_reducer_idempotency_and_precedence() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Archive, then complete the post-archive merge that terminates it.
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        assert_eq!(state.display_status("c"), "resolving");
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        // Late ResolveFailed must NOT regress the terminal state.
        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "c".to_string(),
            error: "late".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        // Duplicate ApplyStarted on a terminal change must be no-op.
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        // Terminal wins: still merged.
        assert_eq!(state.display_status("c"), "merged");
    }

    /// Phase 7.2: reducer runtime state and legacy aggregates (pending_changes, archived_changes,
    /// current_change_id, apply_count) must agree on the canonical status of each change
    /// after a representative lifecycle sequence.
    #[test]
    fn test_reducer_runtime_and_legacy_aggregates_stay_consistent() {
        use crate::events::ExecutionEvent;

        let mut state =
            OrchestratorState::new(vec!["a".to_string(), "b".to_string(), "c".to_string()], 5);

        // ── Initial state ──────────────────────────────────────────────────
        // All changes start in pending_changes (from new()), but reducer says "not queued"
        // because no AddToQueue command has been issued yet.
        assert_eq!(state.display_status("a"), "not queued");
        assert_eq!(state.display_status("b"), "not queued");
        assert_eq!(state.display_status("c"), "not queued");
        assert!(state.is_pending("a"));
        assert!(state.is_pending("b"));
        assert!(state.is_pending("c"));

        // ── Queue a and b via reducer ──────────────────────────────────────
        state.apply_command(ReducerCommand::AddToQueue("a".to_string()));
        state.apply_command(ReducerCommand::AddToQueue("b".to_string()));

        assert_eq!(state.display_status("a"), "queued");
        assert_eq!(state.display_status("b"), "queued");
        assert!(state.is_pending("a"));
        assert!(state.is_pending("b"));

        // ── Start applying 'a' ─────────────────────────────────────────────
        state.set_current_change(Some("a".to_string()));
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "a".to_string(),
            command: "cmd".to_string(),
        });
        state.increment_apply_count("a");

        assert_eq!(state.display_status("a"), "applying");
        assert_eq!(state.current_change_id(), Some(&"a".to_string()));
        assert_eq!(state.apply_count("a"), 1);

        // ── Archive 'a' ────────────────────────────────────────────────────
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("a".to_string()));
        state.mark_archived("a");

        // Archive enters post-archive handling; the legacy archived set agrees
        // that the archive itself happened.
        assert_eq!(state.display_status("a"), "resolving");
        assert!(state.is_archived("a"));
        assert!(!state.is_pending("a"));

        // ── Dequeue 'b' ────────────────────────────────────────────────────
        state.apply_command(ReducerCommand::DequeueChange("b".to_string()));

        // Reducer returns b to not queued; legacy pending membership is unchanged.
        assert_eq!(state.display_status("b"), "not queued");
        // 'c' (never explicitly queued in reducer) is still "not queued" in reducer.
        assert_eq!(state.display_status("c"), "not queued");
        assert!(state.is_pending("c")); // legacy: still in pending set
        assert!(!state.is_archived("c"));
    }

    // -----------------------------------------------------------------------
    // Archive-to-post-archive transitions (the sole execution path)
    // -----------------------------------------------------------------------

    #[test]
    fn test_parallel_mode_change_archived_transitions_to_resolving_without_blocker() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Apply → Archive
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ApplyCompleted {
            change_id: "c".to_string(),
            revision: "rev1".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ArchiveStarted {
            change_id: "c".to_string(),
            command: "archive".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));

        // ChangeArchived is a merge-routing milestone, not a
        // stable terminal display. With no lane blocker or manual deferral
        // evidence, the reducer must show active merge handling immediately.
        assert_eq!(
            state.display_status("c"),
            "resolving",
            "Parallel: no-blocker ChangeArchived must transition to active merge handling, not merge wait"
        );
        assert!(
            !state.is_terminal_change("c"),
            "Parallel: change must not be terminal after archive"
        );

        // MergeCompleted should now succeed.
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "merge-rev".to_string(),
        });
        assert_eq!(
            state.display_status("c"),
            "merged",
            "Parallel: MergeCompleted must transition to merged terminal"
        );
        assert!(state.is_terminal_change("c"));
    }

    #[test]
    fn test_parallel_mode_archive_success_clears_prior_acceptance_error() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::AcceptanceFailed {
            change_id: "alpha".to_string(),
            error: "transient acceptance failure".to_string(),
        });
        assert_eq!(state.display_status("alpha"), "error");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("alpha".to_string()));

        assert_eq!(
            state.display_status("alpha"),
            "resolving",
            "same-change archive success must supersede a recoverable acceptance error and enter active no-blocker merge handling"
        );
        assert!(!state.is_terminal_change("alpha"));

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "merge-rev".to_string(),
        });
        assert_eq!(state.display_status("alpha"), "merged");
        assert!(state.is_terminal_change("alpha"));
    }

    #[test]
    fn test_parallel_mode_acceptance_error_archive_then_merge_finishes_merged() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["add-skill-secret-ingestion".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::AcceptanceFailed {
            change_id: "add-skill-secret-ingestion".to_string(),
            error: "acceptance failed before fix".to_string(),
        });
        assert_eq!(state.display_status("add-skill-secret-ingestion"), "error");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived(
            "add-skill-secret-ingestion".to_string(),
        ));
        assert_ne!(state.display_status("add-skill-secret-ingestion"), "error");

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "add-skill-secret-ingestion".to_string(),
            revision: "merge-rev".to_string(),
        });

        assert_eq!(state.display_status("add-skill-secret-ingestion"), "merged");
        assert!(state.is_terminal_change("add-skill-secret-ingestion"));
    }

    #[test]
    fn test_merge_and_resolve_success_clear_prior_processing_error_but_not_rejected() {
        use crate::events::ExecutionEvent;

        let mut merge_state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        merge_state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "alpha".to_string(),
            error: "recoverable process failure".to_string(),
        });
        assert_eq!(merge_state.display_status("alpha"), "error");
        merge_state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "merge-rev".to_string(),
        });
        assert_eq!(merge_state.display_status("alpha"), "merged");

        let mut resolve_state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        resolve_state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "alpha".to_string(),
            error: "recoverable process failure".to_string(),
        });
        assert_eq!(resolve_state.display_status("alpha"), "error");
        resolve_state.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "alpha".to_string(),
            worktree_change_ids: None,
        });
        assert_eq!(resolve_state.display_status("alpha"), "merged");

        let mut rejected_state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        rejected_state.apply_execution_event(&ExecutionEvent::ChangeRejected {
            change_id: "alpha".to_string(),
            reason: "final rejection".to_string(),
        });
        rejected_state.apply_execution_event(&ExecutionEvent::ChangeArchived("alpha".to_string()));
        rejected_state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "stale-merge-rev".to_string(),
        });
        rejected_state.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "alpha".to_string(),
            worktree_change_ids: None,
        });
        assert_eq!(rejected_state.display_status("alpha"), "rejected");
    }

    #[test]
    fn test_parallel_mode_change_archived_uses_resolve_pending_when_other_change_is_resolving() {
        use crate::events::ExecutionEvent;

        let mut state =
            OrchestratorState::new(vec!["resolving".to_string(), "archived".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "resolving".to_string(),
            command: "resolve resolving".to_string(),
        });
        assert_eq!(state.display_status("resolving"), "resolving");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("archived".to_string()));
        assert_eq!(
            state.display_status("archived"),
            "resolve pending",
            "Parallel: ChangeArchived must transition to resolve pending while another change is resolving"
        );
        assert!(!state.is_terminal_change("archived"));
    }

    #[test]
    fn test_parallel_mode_change_archived_uses_resolve_pending_when_other_change_is_rejecting() {
        use crate::events::ExecutionEvent;
        use crate::vcs::WorkspaceStatus;

        let mut state =
            OrchestratorState::new(vec!["rejecting".to_string(), "archived".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
            change_id: "rejecting".to_string(),
            workspace_name: "ws-rejecting".to_string(),
            status: WorkspaceStatus::Rejecting,
        });
        assert_eq!(state.display_status("rejecting"), "rejecting");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("archived".to_string()));
        assert_eq!(
            state.display_status("archived"),
            "resolve pending",
            "Parallel: ChangeArchived must transition to resolve pending while another change is rejecting"
        );
        assert!(!state.is_terminal_change("archived"));
    }

    #[test]
    fn test_parallel_mode_change_archived_enters_resolving_when_other_change_is_accepting() {
        use crate::events::ExecutionEvent;

        let mut state =
            OrchestratorState::new(vec!["accepting".to_string(), "archived".to_string()], 0);

        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "accepting".to_string(),
            command: "accept accepting".to_string(),
        });
        assert_eq!(state.display_status("accepting"), "accepting");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("archived".to_string()));
        assert_eq!(
            state.display_status("archived"),
            "resolving",
            "Parallel: accepting activity is not a merge/resolve lane blocker, so no-blocker archive handling must enter resolving instead of merge wait or resolve pending"
        );
    }

    #[test]
    fn test_parallel_mode_full_lifecycle() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        // Queue and process 'a'
        state.apply_command(ReducerCommand::AddToQueue("a".to_string()));
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "a".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(state.display_status("a"), "applying");

        state.apply_execution_event(&ExecutionEvent::ChangeArchived("a".to_string()));
        assert_eq!(
            state.display_status("a"),
            "resolving",
            "Parallel: no-blocker archive completion must enter active resolving before merged"
        );
        assert!(!state.is_terminal_change("a"));

        // Merge 'a'
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "a".to_string(),
            revision: "rev-a".to_string(),
        });
        assert_eq!(state.display_status("a"), "merged");
        assert!(state.is_terminal_change("a"));

        // 'b' is still not queued
        assert_eq!(state.display_status("b"), "not queued");
        assert!(!state.is_terminal_change("b"));
    }

    #[test]
    fn test_parallel_mode_merge_deferred_then_completed() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Archive completion without a concrete blocker enters active merge handling.
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        assert_eq!(
            state.display_status("c"),
            "resolving",
            "Parallel: ChangeArchived alone must not imply merge wait before manual blocker evidence exists"
        );

        // Merge deferred (manual, not auto-resumable)
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        // Manual deferral: stays in merge wait.
        assert_eq!(state.display_status("c"), "merge wait");

        // Eventually merge succeeds
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");
        assert!(state.is_terminal_change("c"));
    }

    #[test]
    fn test_parallel_mode_late_events_do_not_regress_merged() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Full lifecycle to merged
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        // Late events must not regress
        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "c".to_string(),
            error: "late".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "cmd".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");
    }

    // -----------------------------------------------------------------------
    // Regression: auto-resumable MergeDeferred must not stay in MergeWait
    // -----------------------------------------------------------------------

    /// `MergeDeferred(auto_resumable=true)` must set ResolveWait, not MergeWait.
    /// This prevents the "stuck after prior merge" scenario where a change
    /// appears to need manual M-press even though it can be resolved automatically.
    #[test]
    fn test_auto_resumable_merge_deferred_sets_resolve_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["b".to_string()], 0);

        // change-b gets a MergeDeferred that is auto-resumable (dirty base caused by
        // change-a's merge being in progress).
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "b".to_string(),
            reason: "Merge in progress (MERGE_HEAD exists)".to_string(),
            auto_resumable: true,
        });

        // Must NOT land in merge wait (which would require manual M press).
        assert_eq!(
            state.display_status("b"),
            "resolve pending",
            "auto-resumable deferred change must enter ResolveWait, not MergeWait"
        );
    }

    /// Workspace refresh after auto-resumable deferral must not regress to MergeWait.
    #[test]
    fn test_auto_resumable_deferred_survives_workspace_refresh() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["b".to_string()], 0);

        // Auto-resumable deferral → ResolveWait.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "b".to_string(),
            reason: "Working tree has uncommitted changes".to_string(),
            auto_resumable: true,
        });
        assert_eq!(state.display_status("b"), "resolve pending");

        // Subsequent ChangesRefreshed sees the workspace as archived (still waiting).
        // It must NOT regress the auto-resolve intent back to merge wait.
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: Default::default(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: Default::default(),
            worktree_change_ids: Default::default(),
            worktree_paths: Default::default(),
            worktree_not_ahead_ids: Default::default(),
            merge_wait_ids: ["b".to_string()].into_iter().collect(),
        });

        assert_eq!(
            state.display_status("b"),
            "resolve pending",
            "workspace refresh must not regress auto-resumable deferred change to merge wait"
        );
    }

    /// After auto-resumable deferral, MergeCompleted (from retry) drives change to Merged.
    #[test]
    fn test_auto_resumable_deferred_then_merge_completed() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["b".to_string()], 0);

        // Auto-resumable deferral.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "b".to_string(),
            reason: "Merge in progress (MERGE_HEAD exists)".to_string(),
            auto_resumable: true,
        });
        assert_eq!(state.display_status("b"), "resolve pending");

        // Scheduler retries and merge succeeds.
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "b".to_string(),
            revision: "abc123".to_string(),
        });
        assert_eq!(state.display_status("b"), "merged");
        assert!(state.is_terminal_change("b"));
    }

    // -----------------------------------------------------------------------
    // Fix: manual resolve dirty-base classification (fix-resolve-dirty-base-transition)
    // -----------------------------------------------------------------------

    /// Manual resolve blocked by another merge in progress → MergeDeferred(auto_resumable=true)
    /// → ResolveWait ("resolve pending"), eligible for automatic retry.
    #[test]
    fn test_manual_resolve_blocked_by_merge_in_progress_becomes_resolve_pending() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Change starts in MergeWait.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("c"), "merge wait");

        // User requests resolve → ResolveWait.
        state.apply_command(ReducerCommand::ResolveMerge("c".to_string()));
        assert_eq!(state.display_status("c"), "resolve pending");

        // Dirty-base check discovers MERGE_HEAD → auto-resumable MergeDeferred.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "Merge in progress (MERGE_HEAD exists)".to_string(),
            auto_resumable: true,
        });
        assert_eq!(
            state.display_status("c"),
            "resolve pending",
            "auto-resumable dirty base must stay as resolve pending"
        );
    }

    /// Manual resolve blocked by uncommitted changes → ResolveFailed → MergeWait.
    #[test]
    fn test_manual_resolve_blocked_by_uncommitted_changes_stays_merge_wait() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Change starts in MergeWait.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "c".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("c"), "merge wait");

        // User requests resolve → ResolveWait.
        state.apply_command(ReducerCommand::ResolveMerge("c".to_string()));
        assert_eq!(state.display_status("c"), "resolve pending");

        // Dirty-base check discovers uncommitted changes → ResolveFailed.
        // Note: No ResolveStarted was sent (early exit).
        state.apply_execution_event(&ExecutionEvent::ResolveFailed {
            change_id: "c".to_string(),
            error: "Base is dirty: Working tree has uncommitted changes".to_string(),
        });
        assert_eq!(
            state.display_status("c"),
            "merge wait",
            "uncommitted-changes dirty base must revert to merge wait"
        );
    }

    /// After auto-resumable deferral from manual resolve, a preceding resolve
    /// completes (ResolveCompleted for another change) → the deferred change is
    /// retried via retry_deferred_merges → MergeCompleted → Merged.
    #[test]
    fn test_auto_resumable_deferred_resolve_auto_retries_after_preceding_completes() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["a".to_string(), "b".to_string()], 0);

        // change-a is being resolved actively.
        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "a".to_string(),
            command: "resolve a".to_string(),
        });
        assert_eq!(state.display_status("a"), "resolving");

        // change-b tries manual resolve → blocked by MERGE_HEAD → auto-resumable.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "b".to_string(),
            reason: "Merge in progress (MERGE_HEAD exists)".to_string(),
            auto_resumable: true,
        });
        assert_eq!(state.display_status("b"), "resolve pending");

        // change-a resolve completes.
        state.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "a".to_string(),
            worktree_change_ids: None,
        });
        assert_eq!(state.display_status("a"), "merged");

        // retry_deferred_merges retries change-b and succeeds → MergeCompleted.
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "b".to_string(),
            revision: "rev-b".to_string(),
        });
        assert_eq!(state.display_status("b"), "merged");
        assert!(state.is_terminal_change("b"));
    }

    // -----------------------------------------------------------------------
    // Fix: parallel TUI queued/blocked state regression – reducer unit tests
    // -----------------------------------------------------------------------

    /// Explicit RetryError on a change in Error terminal state must clear the terminal and
    /// set queue_intent = Queued so that the TUI retry path works correctly.
    #[test]
    fn test_explicit_retry_retries_error_terminal() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Drive the change to an error terminal state.
        state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "c".to_string(),
            error: "apply failed".to_string(),
        });
        assert_eq!(state.display_status("c"), "error");
        assert!(state.is_terminal_change("c"));

        // Ordinary AddToQueue must not clear the error terminal.
        let ordinary_outcome = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(ordinary_outcome, ReduceOutcome::NoOp));
        assert_eq!(state.display_status("c"), "error");

        // Explicit RetryError must clear the error terminal.
        let outcome = state.apply_command(ReducerCommand::RetryError("c".to_string()));
        assert!(
            matches!(outcome, ReduceOutcome::Changed(_)),
            "RetryError on error change must be Changed, not NoOp"
        );
        assert_eq!(
            state.display_status("c"),
            "queued",
            "after retry, change must display as queued"
        );
        assert!(
            !state.is_terminal_change("c"),
            "error terminal must be cleared by AddToQueue"
        );
    }

    /// DequeueChange should clear runtime state to a non-terminal not-queued idle state.
    #[test]
    fn test_dequeue_change_resets_to_not_queued_idle() {
        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);

        // Start in queued/active-ish flow, then dequeue.
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        let outcome = state.apply_command(ReducerCommand::DequeueChange("c".to_string()));
        assert!(matches!(outcome, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "not queued");
        assert!(!state.is_terminal_change("c"));

        // Explicit re-queue remains possible only by user action.
        let outcome2 = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(matches!(outcome2, ReduceOutcome::Changed(_)));
        assert_eq!(state.display_status("c"), "queued");
    }

    /// AddToQueue on a change that reached its post-archive terminal state must
    /// be a no-op: archive alone is not terminal, the merge that follows it is.
    #[test]
    fn test_add_to_queue_noop_on_merged() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("c".to_string()));
        assert_eq!(
            state.display_status("c"),
            "resolving",
            "archive enters post-archive handling instead of terminating"
        );

        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "c".to_string(),
            revision: "rev".to_string(),
        });
        assert_eq!(state.display_status("c"), "merged");

        let outcome = state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert!(
            matches!(outcome, ReduceOutcome::NoOp),
            "AddToQueue on a merged change must be NoOp"
        );
        assert_eq!(state.display_status("c"), "merged");
    }

    /// After AddToQueue + DependencyBlocked + DependencyResolved, the display must
    /// return to "queued" (queue_intent is preserved through the block/resolve cycle).
    #[test]
    fn test_dependency_resolved_restores_queued_after_block() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert_eq!(state.display_status("c"), "queued");

        state.apply_execution_event(&ExecutionEvent::DependencyBlocked {
            change_id: "c".to_string(),
            dependency_ids: vec!["dep".to_string()],
        });
        assert_eq!(state.display_status("c"), "blocked");

        state.apply_execution_event(&ExecutionEvent::DependencyResolved {
            change_id: "c".to_string(),
        });
        assert_eq!(
            state.display_status("c"),
            "queued",
            "DependencyResolved must restore queued (not not-queued)"
        );
    }

    #[test]
    fn test_dependency_blocked_and_resolved_preserve_queue_intent_until_user_dequeue() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));

        state.apply_execution_event(&ExecutionEvent::DependencyBlocked {
            change_id: "c".to_string(),
            dependency_ids: vec!["dep-a".to_string()],
        });
        assert_eq!(state.display_status("c"), "blocked");

        state.apply_execution_event(&ExecutionEvent::DependencyResolved {
            change_id: "c".to_string(),
        });
        assert_eq!(state.display_status("c"), "queued");

        state.apply_command(ReducerCommand::RemoveFromQueue("c".to_string()));
        assert_eq!(
            state.display_status("c"),
            "not queued",
            "queue intent should only clear on explicit dequeue command"
        );
    }

    /// ChangesRefreshed must not overwrite queue_intent = Queued with "not queued".
    #[test]
    fn test_changes_refreshed_preserves_queue_intent() {
        use crate::events::ExecutionEvent;
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["c".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("c".to_string()));
        assert_eq!(state.display_status("c"), "queued");

        // Simulate initial parallel ChangesRefreshed with no special observations.
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: HashSet::new(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        });

        assert_eq!(
            state.display_status("c"),
            "queued",
            "ChangesRefreshed must not overwrite queue_intent = Queued"
        );
    }

    /// Fast-forward resolve: terminal Merged set via ResolveCompleted must survive
    /// a subsequent ChangesRefreshed that still reports the workspace as archived
    /// (the workspace scan may lag behind the actual merge).
    #[test]
    fn test_fast_forward_merged_survives_archived_observation() {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec!["ff".to_string()], 0);

        // Change is archived and deferred to merge wait (manual, not auto-resumable).
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "ff".to_string(),
            reason: "base dirty".to_string(),
            auto_resumable: false,
        });
        assert_eq!(state.display_status("ff"), "merge wait");

        // Resolve starts.
        state.apply_command(ReducerCommand::ResolveMerge("ff".to_string()));
        assert_eq!(state.display_status("ff"), "resolve pending");
        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: "ff".to_string(),
            command: "resolve-cmd".to_string(),
        });
        assert_eq!(state.display_status("ff"), "resolving");

        // Resolve succeeds (fast-forward merge detected by the caller).
        state.apply_execution_event(&ExecutionEvent::ResolveCompleted {
            change_id: "ff".to_string(),
            worktree_change_ids: None,
        });
        assert_eq!(state.display_status("ff"), "merged");

        // Refresh still sees the worktree as archived (workspace scan lag).
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![],
            committed_change_ids: Default::default(),
            rejected_changes: Vec::new(),
            uncommitted_file_change_ids: Default::default(),
            worktree_change_ids: Default::default(),
            worktree_paths: Default::default(),
            worktree_not_ahead_ids: Default::default(),
            merge_wait_ids: ["ff".to_string()].into_iter().collect(),
        });
        assert_eq!(
            state.display_status("ff"),
            "merged",
            "Terminal Merged from fast-forward resolve must not regress to merge wait"
        );
    }

    // ── Opted-in per-change upstream publication ────────────────────────────

    /// Set a parallel change up to the point where its archived result has just
    /// been integrated into cumulative base.
    fn per_change_upstream_state(change_id: &str) -> OrchestratorState {
        use crate::events::ExecutionEvent;

        let mut state = OrchestratorState::new(vec![change_id.to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::ChangeArchived(change_id.to_string()));
        state
    }

    fn per_change_upstream_push_started(change_id: &str) -> crate::events::ExecutionEvent {
        crate::events::ExecutionEvent::PushStarted {
            change_id: change_id.to_string(),
            remote: "origin".to_string(),
            branch: "main".to_string(),
        }
    }

    fn per_change_upstream_push_completed(change_id: &str) -> crate::events::ExecutionEvent {
        crate::events::ExecutionEvent::PushCompleted {
            change_id: change_id.to_string(),
            remote: "origin".to_string(),
            branch: "main".to_string(),
        }
    }

    fn per_change_upstream_push_failed(change_id: &str) -> crate::events::ExecutionEvent {
        crate::events::ExecutionEvent::PushFailed {
            change_id: change_id.to_string(),
            remote: "origin".to_string(),
            branch: "main".to_string(),
            error: "upstream publication incomplete: verification failed".to_string(),
        }
    }

    #[test]
    fn per_change_upstream_disabled_cumulative_merge_stays_merged() {
        use crate::events::ExecutionEvent;

        // Without the option the execution path still emits MergeCompleted, and
        // that must keep its existing terminal meaning.
        let mut state = per_change_upstream_state("alpha");
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "alpha".to_string(),
            revision: "merge-rev".to_string(),
        });

        assert_eq!(state.display_status("alpha"), "merged");
        assert!(state.is_terminal_change("alpha"));
    }

    #[test]
    fn per_change_upstream_local_integration_is_not_terminal_merged() {
        // With the option enabled the execution path suppresses MergeCompleted
        // and reports publication progress instead, so nothing can observe a
        // final `merged` while publication is still owed.
        let mut state = per_change_upstream_state("alpha");
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));

        assert_ne!(state.display_status("alpha"), "merged");
        assert!(
            !state.is_terminal_change("alpha"),
            "publication progress must remain non-terminal"
        );
        assert!(
            !state.queued_change_ids().contains(&"alpha".to_string()),
            "a publishing change must not be ordinary queued apply work"
        );
    }

    /// Replay the events a *fresh* opted-in cumulative integration actually
    /// emits, in order, up to the point where publication takes over.
    ///
    /// The git-backed merge path emits `MergeStarted` and `ResolveStarted`, then
    /// the conflict resolver reports `ConflictResolutionStarted` /
    /// `ConflictResolutionCompleted`. It must *not* emit the per-change
    /// `ResolveCompleted`, because that finalizes the reducer as terminal
    /// `merged` before anything has been published.
    fn per_change_upstream_apply_fresh_integration(state: &mut OrchestratorState, change_id: &str) {
        use crate::events::ExecutionEvent;

        state.apply_execution_event(&ExecutionEvent::MergeStarted {
            revisions: vec!["ws-alpha".to_string()],
        });
        state.apply_execution_event(&ExecutionEvent::ResolveStarted {
            change_id: change_id.to_string(),
            command: "merge archived change into base branch (1 revision(s))".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ConflictResolutionStarted);
        state.apply_execution_event(&ExecutionEvent::ConflictResolutionCompleted);
    }

    #[test]
    fn per_change_upstream_fresh_integration_never_displays_merged() {
        let mut state = per_change_upstream_state("alpha");
        per_change_upstream_apply_fresh_integration(&mut state, "alpha");

        assert_ne!(
            state.display_status("alpha"),
            "merged",
            "local integration must not finalize an opted-in change"
        );
        assert!(
            !state.is_terminal_change("alpha"),
            "publication is still owed, so nothing is terminal yet"
        );

        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        assert_ne!(state.display_status("alpha"), "merged");
        assert!(!state.is_terminal_change("alpha"));

        state.apply_execution_event(&per_change_upstream_push_completed("alpha"));
        assert_eq!(
            state.display_status("alpha"),
            "pushed",
            "remote confirmation is the opted-in terminal state"
        );
        assert!(state.is_terminal_change("alpha"));
    }

    #[test]
    fn per_change_upstream_fresh_integration_failure_stays_recoverable() {
        // Same fresh sequence, but publication fails. A terminal `merged` here
        // would swallow PushFailed and leave no recoverable Error for F5 retry.
        let mut state = per_change_upstream_state("alpha");
        per_change_upstream_apply_fresh_integration(&mut state, "alpha");
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        state.apply_execution_event(&per_change_upstream_push_failed("alpha"));

        assert_eq!(
            state.display_status("alpha"),
            "error",
            "a failed publication after a fresh integration must surface as recoverable error"
        );
        assert!(
            state.is_terminal_error_change("alpha"),
            "explicit F5 retry needs a recoverable error to act on"
        );
        assert!(matches!(
            state.apply_command(ReducerCommand::RetryError("alpha".to_string())),
            ReduceOutcome::Changed(_)
        ));

        // Retry succeeds: the recoverable error is superseded by confirmation.
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        state.apply_execution_event(&per_change_upstream_push_completed("alpha"));
        assert_eq!(state.display_status("alpha"), "pushed");
    }

    #[test]
    fn per_change_upstream_remote_confirmation_becomes_pushed_terminal() {
        let mut state = per_change_upstream_state("alpha");
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        state.apply_execution_event(&per_change_upstream_push_completed("alpha"));

        assert_eq!(state.display_status("alpha"), "pushed");
        assert!(state.is_terminal_change("alpha"));
        assert_ne!(state.display_status("alpha"), "merged");
    }

    #[test]
    fn per_change_upstream_publication_failure_is_recoverable_not_merged() {
        let mut state = per_change_upstream_state("alpha");
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        state.apply_execution_event(&per_change_upstream_push_failed("alpha"));

        assert_eq!(
            state.display_status("alpha"),
            "error",
            "a failed publication projects into the existing recoverable error flow"
        );
        assert!(
            state.is_terminal_error_change("alpha"),
            "the recoverable error must gate ordinary apply dispatch"
        );

        // Explicit retry (F5 or the equivalent local web control) is accepted.
        let outcome = state.apply_command(ReducerCommand::RetryError("alpha".to_string()));
        assert!(matches!(outcome, ReduceOutcome::Changed(_)));
    }

    #[test]
    fn per_change_upstream_late_confirmation_supersedes_publication_failure() {
        let mut state = per_change_upstream_state("alpha");
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        state.apply_execution_event(&per_change_upstream_push_failed("alpha"));
        assert_eq!(state.display_status("alpha"), "error");

        state.apply_execution_event(&per_change_upstream_push_completed("alpha"));

        assert_eq!(state.display_status("alpha"), "pushed");
        assert!(
            !state.queued_change_ids().contains(&"alpha".to_string()),
            "confirmed publication must not leave ordinary apply dispatch behind"
        );
    }

    #[test]
    fn per_change_upstream_pushed_terminal_is_not_retryable() {
        let mut state = per_change_upstream_state("alpha");
        state.apply_execution_event(&per_change_upstream_push_started("alpha"));
        state.apply_execution_event(&per_change_upstream_push_completed("alpha"));

        assert!(matches!(
            state.apply_command(ReducerCommand::RetryError("alpha".to_string())),
            ReduceOutcome::NoOp
        ));
        assert_eq!(state.display_status("alpha"), "pushed");

        // Nor may it be reintroduced as merge/resolve work.
        assert!(matches!(
            state.apply_command(ReducerCommand::ResolveMerge("alpha".to_string())),
            ReduceOutcome::NoOp
        ));
        assert_eq!(state.display_status("alpha"), "pushed");
    }

    #[test]
    fn per_change_upstream_confirmation_clears_base_lane_retry_intent() {
        use crate::events::ExecutionEvent;

        let mut state = per_change_upstream_state("alpha");
        // A publication that had to wait behind the lane records resolve-wait
        // retry intent; confirmation must clear it rather than leave it as
        // ordinary merge work. The first deferral makes the change idle, which
        // is the state an auto-resumable lane wait is recorded from.
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "base lane busy".to_string(),
            auto_resumable: false,
        });
        state.apply_execution_event(&ExecutionEvent::MergeDeferred {
            change_id: "alpha".to_string(),
            reason: "waiting for publication of beta".to_string(),
            auto_resumable: true,
        });
        assert!(state
            .resolve_wait_change_ids()
            .contains(&"alpha".to_string()));

        state.apply_execution_event(&per_change_upstream_push_completed("alpha"));

        assert_eq!(state.display_status("alpha"), "pushed");
        assert!(
            !state
                .resolve_wait_change_ids()
                .contains(&"alpha".to_string()),
            "confirmed publication must clear base-lane retry intent"
        );
    }

    // ------------------------------------------------------------------
    // Explicit-intent boundary
    // ------------------------------------------------------------------

    /// Catalog refresh is registration, not intent: an all-change refresh may
    /// make an unselected change visible but must leave every execution lane
    /// clear for it.
    #[test]
    fn changes_refreshed_registers_without_creating_queue_or_lane_eligibility() {
        use crate::events::ExecutionEvent;
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["fresh".to_string()], 1);
        state.apply_command(ReducerCommand::AddToQueue("fresh".to_string()));

        let change = |id: &str| 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(),
        };

        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![change("fresh"), 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::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        });

        assert!(
            state.is_in_snapshot("stale"),
            "refresh may register a newly observed change"
        );
        assert_eq!(state.display_status("stale"), "not queued");
        assert_eq!(
            state
                .change_runtime("stale")
                .expect("refresh registers runtime state")
                .queue_intent,
            QueueIntent::NotQueued
        );
        assert_eq!(state.queued_change_ids(), vec!["fresh".to_string()]);
        assert!(state.merge_wait_change_ids().is_empty());
        assert!(state.resolve_wait_change_ids().is_empty());
        assert!(state.reject_wait_change_ids().is_empty());
        assert!(state.active_change_ids().is_empty());
        assert!(
            !state.is_ordinary_queue_eligible("stale"),
            "a registered but unqueued change must not be dispatchable"
        );
    }

    /// Revocation is immediate, and a later refresh cannot undo it.
    #[test]
    fn removal_and_dequeue_revoke_ordinary_eligibility_until_explicit_requeue() {
        use crate::events::ExecutionEvent;
        use std::collections::{HashMap, HashSet};

        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 1);
        state.apply_command(ReducerCommand::AddToQueue("alpha".to_string()));
        assert!(state.is_ordinary_queue_eligible("alpha"));

        state.apply_command(ReducerCommand::RemoveFromQueue("alpha".to_string()));
        assert!(!state.is_ordinary_queue_eligible("alpha"));
        assert!(state.queued_change_ids().is_empty());

        // A refresh that re-observes the change and its worktree must not
        // resurrect eligibility.
        state.apply_execution_event(&ExecutionEvent::ChangesRefreshed {
            changes: vec![crate::openspec::Change {
                id: "alpha".to_string(),
                completed_tasks: 0,
                total_tasks: 1,
                last_modified: "now".to_string(),
                dependencies: Vec::new(),
                metadata: crate::openspec::ProposalMetadata::default(),
            }],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::from(["alpha".to_string()]),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["alpha".to_string()]),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        });
        assert!(!state.is_ordinary_queue_eligible("alpha"));

        state.apply_command(ReducerCommand::AddToQueue("alpha".to_string()));
        state.apply_command(ReducerCommand::DequeueChange("alpha".to_string()));
        assert!(
            !state.is_ordinary_queue_eligible("alpha"),
            "stop-and-dequeue revokes ordinary eligibility"
        );

        state.apply_command(ReducerCommand::AddToQueue("alpha".to_string()));
        assert!(
            state.is_ordinary_queue_eligible("alpha"),
            "explicit requeue restores eligibility"
        );
        assert_eq!(state.queued_change_ids(), vec!["alpha".to_string()]);
    }

    // -----------------------------------------------------------------------
    // Ephemeral workspace preparation
    // -----------------------------------------------------------------------

    /// A queued change admitted to a slot, ready to receive preparation events.
    fn queued_state(change_id: &str) -> OrchestratorState {
        let mut state = OrchestratorState::new(vec![change_id.to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
        assert_eq!(state.display_status(change_id), "queued");
        state
    }

    fn prepare(state: &mut OrchestratorState, change_id: &str) {
        state.apply_execution_event(
            &crate::events::ExecutionEvent::WorkspacePreparationStarted {
                change_id: change_id.to_string(),
            },
        );
    }

    fn end_preparation(state: &mut OrchestratorState, change_id: &str) {
        state.apply_execution_event(&crate::events::ExecutionEvent::WorkspacePreparationEnded {
            change_id: change_id.to_string(),
        });
    }

    #[test]
    fn preparing_replaces_queued_and_then_yields_to_the_repository_derived_phase() {
        use crate::events::ExecutionEvent;

        // Apply route: queued -> preparing -> applying.
        let mut state = queued_state("c");
        prepare(&mut state, "c");
        assert_eq!(state.display_status("c"), "preparing");
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "apply".to_string(),
        });
        assert_eq!(state.display_status("c"), "applying");

        // A resumed workspace routes straight to acceptance, and preparation
        // must not have manufactured an Apply transition on the way.
        let mut state = queued_state("c");
        prepare(&mut state, "c");
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "c".to_string(),
            command: "accept".to_string(),
        });
        assert_eq!(state.display_status("c"), "accepting");
        assert_eq!(state.apply_count("c"), 0);

        // Archive resume.
        let mut state = queued_state("c");
        prepare(&mut state, "c");
        state.apply_execution_event(&ExecutionEvent::ArchiveStarted {
            change_id: "c".to_string(),
            command: "archive".to_string(),
        });
        assert_eq!(state.display_status("c"), "archiving");
    }

    #[test]
    fn preparing_failure_becomes_error_with_the_preparation_diagnostic() {
        use crate::events::ExecutionEvent;

        let mut state = queued_state("c");
        prepare(&mut state, "c");
        state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "c".to_string(),
            error: "Worktree setup failed after 1.0s: .wt/setup exited with code 3".to_string(),
        });

        assert_eq!(state.display_status("c"), "error");
        let rt = state.change_runtime("c").expect("runtime entry");
        assert!(matches!(rt.activity, ActivityState::Idle));
        assert!(rt
            .error_message()
            .is_some_and(|message| message.contains(".wt/setup")));
    }

    #[test]
    fn preparing_is_cleared_by_a_pre_operation_exit() {
        let mut state = queued_state("c");
        prepare(&mut state, "c");
        assert_eq!(state.display_status("c"), "preparing");

        // Global cancellation or a terminal resume route ends dispatch without
        // any operation-started event.
        end_preparation(&mut state, "c");
        assert_eq!(
            state.display_status("c"),
            "queued",
            "preparation must not outlive the dispatch that announced it"
        );
    }

    #[test]
    fn preparing_leaves_through_a_stop_before_an_operation_agent_starts() {
        use crate::events::ExecutionEvent;

        let mut state = queued_state("c");
        prepare(&mut state, "c");
        state.apply_execution_event(&ExecutionEvent::ChangeDequeued {
            change_id: "c".to_string(),
        });

        assert_eq!(state.display_status("c"), "not queued");
        let rt = state.change_runtime("c").expect("runtime entry");
        assert!(matches!(rt.activity, ActivityState::Idle));

        // A clear that arrives after the stop cannot resurrect anything.
        end_preparation(&mut state, "c");
        assert_eq!(state.display_status("c"), "not queued");
    }

    #[test]
    fn preparing_never_overwrites_a_running_operation_or_a_terminal_change() {
        use crate::events::ExecutionEvent;

        // A late preparation event must not relabel a running Apply as if no
        // agent had started.
        let mut state = queued_state("c");
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "apply".to_string(),
        });
        prepare(&mut state, "c");
        assert_eq!(state.display_status("c"), "applying");

        // Nor may it reactivate a terminal change.
        let mut state = queued_state("c");
        state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "c".to_string(),
            error: "boom".to_string(),
        });
        prepare(&mut state, "c");
        assert_eq!(state.display_status("c"), "error");

        // Nor a change an operator force-stopped.
        let mut state = queued_state("c");
        state.apply_command(ReducerCommand::DequeueChange("c".to_string()));
        prepare(&mut state, "c");
        assert_eq!(state.display_status("c"), "not queued");
    }

    #[test]
    fn preparing_clearing_is_narrow_and_idempotent() {
        use crate::events::ExecutionEvent;

        // Clearing a change that is applying leaves the operation alone: the
        // completion funnel emits it for every task, including ones that did
        // reach a real phase.
        let mut state = queued_state("c");
        state.apply_execution_event(&ExecutionEvent::ApplyStarted {
            change_id: "c".to_string(),
            command: "apply".to_string(),
        });
        end_preparation(&mut state, "c");
        assert_eq!(state.display_status("c"), "applying");

        // Repeating the clear on an already-cleared change changes nothing.
        let mut state = queued_state("c");
        prepare(&mut state, "c");
        end_preparation(&mut state, "c");
        end_preparation(&mut state, "c");
        assert_eq!(state.display_status("c"), "queued");
    }

    #[test]
    fn preparing_counts_as_active_execution_but_not_as_a_running_agent() {
        let mut state = queued_state("c");
        prepare(&mut state, "c");

        assert!(
            state.is_active_change("c"),
            "an admitted change mutating its worktree is active execution"
        );
        assert!(
            !state.is_agent_execution_active(),
            "preparation must never justify a force-stopped-process claim"
        );
        assert!(
            crate::orchestration::operator_command::is_active_status(state.display_status("c")),
            "every operator surface must treat preparing as active"
        );
    }

    #[test]
    fn preparing_is_not_durable_routing_state() {
        let mut state = queued_state("c");
        prepare(&mut state, "c");
        assert_eq!(state.display_status("c"), "preparing");

        // A restart rebuilds the reducer from the same workspace contents. The
        // ephemeral preparation observation is gone, and nothing about the next
        // action was derived from it.
        let restarted = OrchestratorState::new(vec!["c".to_string()], 0);
        assert_eq!(restarted.display_status("c"), "not queued");
        assert!(!restarted.is_active_change("c"));
    }

    // -----------------------------------------------------------------------
    // Process-level stop: reducer-owned run-boundary reconciliation
    // -----------------------------------------------------------------------

    /// Drive one change into a named reducer state through ordinary events.
    fn enter_runtime_family(state: &mut OrchestratorState, change_id: &str, family: &str) {
        use crate::events::ExecutionEvent;
        use crate::vcs::WorkspaceStatus;

        match family {
            "queued" => {
                state.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
            }
            "preparing" => {
                state.apply_command(ReducerCommand::AddToQueue(change_id.to_string()));
                state.apply_execution_event(&ExecutionEvent::WorkspacePreparationStarted {
                    change_id: change_id.to_string(),
                });
            }
            "applying" => {
                state.apply_execution_event(&ExecutionEvent::ApplyStarted {
                    change_id: change_id.to_string(),
                    command: "apply".to_string(),
                });
            }
            "accepting" => {
                state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
                    change_id: change_id.to_string(),
                    command: "accept".to_string(),
                });
            }
            "archiving" => {
                state.apply_execution_event(&ExecutionEvent::ArchiveStarted {
                    change_id: change_id.to_string(),
                    command: "archive".to_string(),
                });
            }
            "resolving" => {
                state.apply_execution_event(&ExecutionEvent::ResolveStarted {
                    change_id: change_id.to_string(),
                    command: "resolve".to_string(),
                });
            }
            "rejecting" => {
                state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
                    change_id: change_id.to_string(),
                    workspace_name: format!("ws-{change_id}"),
                    status: WorkspaceStatus::Rejecting,
                });
            }
            "merge wait" => {
                state.apply_execution_event(&ExecutionEvent::MergeDeferred {
                    change_id: change_id.to_string(),
                    reason: "base branch is dirty".to_string(),
                    auto_resumable: false,
                });
            }
            "resolve pending" => {
                state.apply_execution_event(&ExecutionEvent::MergeDeferred {
                    change_id: change_id.to_string(),
                    reason: "another merge is in progress".to_string(),
                    auto_resumable: true,
                });
            }
            "reject pending" => {
                // Rejection review is a base-mutating lane: an occupied lane is
                // what produces the queued `reject pending` wait.
                state.apply_execution_event(&ExecutionEvent::ResolveStarted {
                    change_id: "lane-occupant".to_string(),
                    command: "resolve".to_string(),
                });
                state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
                    change_id: change_id.to_string(),
                    workspace_name: format!("ws-{change_id}"),
                    status: WorkspaceStatus::Rejecting,
                });
            }
            "blocked (dependency)" => {
                state.apply_execution_event(&ExecutionEvent::DependencyBlocked {
                    change_id: change_id.to_string(),
                    dependency_ids: vec!["dep".to_string()],
                });
            }
            "blocked (external)" => {
                state.apply_execution_event(&ExecutionEvent::AcceptanceGated {
                    change_id: change_id.to_string(),
                    blocker: crate::events::StalledBlocker::acceptance_external(
                        "credential",
                        "STAGING_API_KEY is unset",
                    ),
                });
            }
            "stalled" => {
                state.mark_stalled(change_id.to_string());
                state.apply_execution_event(&ExecutionEvent::ExecutionBlocked {
                    change_id: change_id.to_string(),
                    blocker: crate::events::StalledBlocker {
                        category: "no_progress".to_string(),
                        phase: "apply".to_string(),
                        gate: "apply".to_string(),
                        error_summary: "no semantic progress".to_string(),
                        evidence: vec!["tasks.md unchanged".to_string()],
                        unblock_condition: None,
                        prerequisite_owner: None,
                        next_action: "operator review".to_string(),
                        resumable: true,
                        worktree_preserved: true,
                    },
                });
            }
            other => panic!("unknown runtime family: {other}"),
        }
    }

    /// A terminal process stop returns every interrupted row to resumable
    /// `not queued`, and touches nothing it did not own.
    ///
    /// The regression: `ExecutionEvent::Stopped` was a reducer no-op, so a row
    /// the operator had just stopped stayed `accepting` in the one state both
    /// frontends read back.
    #[test]
    fn global_stopped_reconciles_interrupted_runtime() {
        use crate::events::ExecutionEvent;

        // ── Every interrupted activity and wait family returns to not queued ──
        let families = [
            "queued",
            "preparing",
            "applying",
            "accepting",
            "archiving",
            "resolving",
            "rejecting",
            "merge wait",
            "resolve pending",
            "reject pending",
            "blocked (dependency)",
            "blocked (external)",
            "stalled",
        ];

        for family in families {
            let mut state =
                OrchestratorState::new(vec!["target".to_string(), "lane-occupant".to_string()], 0);
            enter_runtime_family(&mut state, "target", family);
            assert_ne!(
                state.display_status("target"),
                "not queued",
                "{family} setup did not produce interrupted runtime state"
            );

            state.apply_execution_event(&ExecutionEvent::Stopped);

            assert_eq!(
                state.display_status("target"),
                "not queued",
                "{family} was not reconciled by the run-boundary stop"
            );
            let rt = state.change_runtime.get("target").expect("runtime entry");
            assert_eq!(rt.activity, ActivityState::Idle, "{family} stayed active");
            assert_eq!(rt.wait_state, WaitState::None, "{family} stayed waiting");
            assert_eq!(
                rt.queue_intent,
                QueueIntent::NotQueued,
                "{family} kept queue intent"
            );
            assert_eq!(
                rt.terminal,
                TerminalState::None,
                "{family} was given a terminal outcome by a process stop"
            );
            assert_eq!(rt.blocked_metadata, BlockedMetadata::default());
            assert!(rt.commit_phase_attempt.is_none());
            assert!(rt.dequeued, "{family} did not get the reactivation guard");
            assert!(
                state.resolve_wait_change_ids().is_empty(),
                "{family} left scheduler resolve membership behind"
            );
            assert!(
                state.reject_wait_change_ids().is_empty(),
                "{family} left scheduler reject membership behind"
            );
            assert!(
                !state.stalled_change_ids().contains("target"),
                "{family} left stall membership behind"
            );
            assert!(
                !state.is_ordinary_queue_eligible("target"),
                "{family} remained dispatchable after the run ended"
            );
        }

        // ── Terminal outcomes and fresh idle rows are not the stop's to change ──
        let mut state = OrchestratorState::new(
            vec![
                "err".to_string(),
                "merged".to_string(),
                "pushed".to_string(),
                "rejected".to_string(),
                "fresh".to_string(),
            ],
            0,
        );
        state.apply_execution_event(&ExecutionEvent::ProcessingError {
            id: "err".to_string(),
            error: "apply exited 1".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ChangeArchived("merged".to_string()));
        state.apply_execution_event(&ExecutionEvent::MergeCompleted {
            change_id: "merged".to_string(),
            revision: "rev".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::PushCompleted {
            change_id: "pushed".to_string(),
            remote: "origin".to_string(),
            branch: "main".to_string(),
        });
        state.apply_execution_event(&ExecutionEvent::ChangeRejected {
            change_id: "rejected".to_string(),
            reason: "acceptance confirmed rejection".to_string(),
        });

        state.apply_execution_event(&ExecutionEvent::Stopped);

        assert_eq!(state.display_status("err"), "error");
        assert_eq!(state.display_status("merged"), "merged");
        assert_eq!(state.display_status("pushed"), "pushed");
        assert_eq!(state.display_status("rejected"), "rejected");
        assert_eq!(state.display_status("fresh"), "not queued");
        assert!(
            !state
                .change_runtime
                .get("fresh")
                .expect("fresh runtime entry")
                .dequeued,
            "an unrelated idle row must not be claimed by the stopped run"
        );

        // ── Duplicate stop, late lifecycle events, and same-process refresh ──
        let mut state = OrchestratorState::new(vec!["alpha".to_string()], 0);
        state.apply_execution_event(&ExecutionEvent::AcceptanceStarted {
            change_id: "alpha".to_string(),
            command: "accept".to_string(),
        });
        assert_eq!(state.display_status("alpha"), "accepting");

        state.apply_execution_event(&ExecutionEvent::Stopped);
        let after_first_stop = format!("{:?}", state.change_runtime.get("alpha"));
        state.apply_execution_event(&ExecutionEvent::Stopped);
        assert_eq!(
            format!("{:?}", state.change_runtime.get("alpha")),
            after_first_stop,
            "a duplicate stop must not change reconciled state"
        );
        assert_eq!(state.display_status("alpha"), "not queued");

        for late in [
            ExecutionEvent::AcceptanceStarted {
                change_id: "alpha".to_string(),
                command: "accept".to_string(),
            },
            ExecutionEvent::ArchiveStarted {
                change_id: "alpha".to_string(),
                command: "archive".to_string(),
            },
            ExecutionEvent::ResolveStarted {
                change_id: "alpha".to_string(),
                command: "resolve".to_string(),
            },
            ExecutionEvent::WorkspacePreparationStarted {
                change_id: "alpha".to_string(),
            },
        ] {
            state.apply_execution_event(&late);
            assert_eq!(
                state.display_status("alpha"),
                "not queued",
                "a late event from the stopped run reactivated the row"
            );
        }

        // A same-process refresh observes the archived workspace the stopped run
        // released; the guard is what keeps it from restoring `merge wait`.
        state.apply_execution_event(&stop_refresh_event("alpha"));
        assert_eq!(
            state.display_status("alpha"),
            "not queued",
            "a same-process workspace observation resurrected stopped work"
        );

        // ── Explicit requeue releases the guard ──────────────────────────────
        state.apply_command(ReducerCommand::AddToQueue("alpha".to_string()));
        assert_eq!(state.display_status("alpha"), "queued");
        assert!(
            !state
                .change_runtime
                .get("alpha")
                .expect("runtime entry")
                .dequeued,
            "an explicit requeue must release the reactivation guard"
        );
        assert!(state.is_ordinary_queue_eligible("alpha"));

        // ── The guard is process-local, never restart-routing evidence ───────
        let mut restarted = OrchestratorState::new(vec!["alpha".to_string()], 0);
        restarted.apply_execution_event(&stop_refresh_event("alpha"));
        assert_eq!(
            restarted.display_status("alpha"),
            "merge wait",
            "a restarted process must re-derive routing from workspace evidence alone"
        );
    }

    /// A refresh whose workspace observation would restore `merge wait`.
    fn stop_refresh_event(change_id: &str) -> crate::events::ExecutionEvent {
        crate::events::ExecutionEvent::ChangesRefreshed {
            changes: Vec::new(),
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::from([change_id.to_string()]),
        }
    }

    // =======================================================================
    // Dependency blocker projection
    //
    // Unit scope on purpose: the reducer is in-memory, so these exercise the
    // state contract itself with no Git, filesystem, process, or clock
    // involved. The scheduler-side reconciliation call and the deduplicated
    // diagnostics around it are covered by the parallel-executor regression.
    // =======================================================================

    /// An admitted change with an unresolved dependency is blocked from the
    /// first coherent classification, with the complete typed contract.
    #[test]
    fn dependency_blocker_projection_initial() {
        let mut state = OrchestratorState::new(vec!["beta".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("beta".to_string()));

        assert!(
            state.reconcile_dependency_blocker("beta", &["alpha".to_string()]),
            "the first classification must publish the wait"
        );

        let rt = state.change_runtime("beta").expect("runtime entry");
        assert_eq!(state.display_status("beta"), "blocked");
        assert_eq!(
            rt.queue_intent,
            QueueIntent::Queued,
            "a dependency wait excludes dispatch and never revokes admitted work"
        );
        assert_eq!(rt.wait_state, WaitState::DependencyBlocked);
        assert!(!rt.is_active(), "no execution episode has started");

        let view = state.blocker_view("beta").expect("structured blocker");
        assert_eq!(view.status, "blocked");
        assert_eq!(view.kind, BlockerKind::Dependency);
        assert_eq!(view.dependencies, vec!["alpha".to_string()]);
        assert_eq!(view.category.as_deref(), Some("dependency_blocked"));
        assert!(view
            .detail
            .as_deref()
            .is_some_and(|detail| detail.contains("alpha")));

        // The typed execution state is the retained admission, not a new
        // episode: the change is queued behind evidence, not running.
        assert_eq!(
            crate::orchestration::execution_facts::project_execution_state(
                rt,
                crate::orchestration::execution_facts::ExecutionPhase::None,
                false,
            ),
            crate::orchestration::execution_facts::ChangeExecutionState::Queued
        );
    }

    /// The bug this change repairs: diagnostic deduplication must not be able
    /// to erase or withhold the current blocker, and a reducer that never saw
    /// the original transition must still report it.
    #[test]
    fn dependency_blocker_projection_rebuild() {
        let mut state = OrchestratorState::new(vec!["beta".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("beta".to_string()));
        state.reconcile_dependency_blocker("beta", &["alpha".to_string()]);

        // Same unresolved set, reclassified: no state churn, and no revision of
        // the projection either.
        assert!(
            !state.reconcile_dependency_blocker("beta", &["alpha".to_string()]),
            "an unchanged fingerprint must settle as a no-op, not a rewrite"
        );
        assert_eq!(state.display_status("beta"), "blocked");

        // A changed blocker set is still reconciled, not suppressed.
        assert!(
            state.reconcile_dependency_blocker("beta", &["alpha".to_string(), "gamma".to_string()])
        );
        assert_eq!(
            state.blocker_view("beta").expect("blocker").dependencies,
            vec!["alpha".to_string(), "gamma".to_string()]
        );

        // Reducer replacement — a refresh, a restart of the projection, any
        // loss of the ephemeral diagnostic fingerprints. The next
        // classification republishes the same current blocker without needing a
        // changed fingerprint to justify itself.
        let mut rebuilt = OrchestratorState::new(vec!["beta".to_string()], 0);
        rebuilt.apply_command(ReducerCommand::AddToQueue("beta".to_string()));
        assert_eq!(
            rebuilt.display_status("beta"),
            "queued",
            "a fresh reducer starts from retained queue intent alone"
        );
        assert!(rebuilt.blocker_view("beta").is_none());

        rebuilt.reconcile_dependency_blocker("beta", &["alpha".to_string()]);
        assert_eq!(rebuilt.display_status("beta"), "blocked");
        assert_eq!(
            rebuilt.blocker_view("beta").expect("blocker").dependencies,
            vec!["alpha".to_string()]
        );
    }

    /// Resolution clears the wait exactly once and hands the row back to its
    /// retained queue intent — and nothing else's hold is cleared with it.
    #[test]
    fn dependency_blocker_projection_resolution() {
        let mut state = OrchestratorState::new(vec!["beta".to_string(), "held".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("beta".to_string()));
        state.apply_command(ReducerCommand::AddToQueue("held".to_string()));
        state.reconcile_dependency_blocker("beta", &["alpha".to_string()]);

        assert!(state.clear_dependency_blocker("beta"));
        assert_eq!(
            state.display_status("beta"),
            "queued",
            "the retained queue intent decides the display again"
        );
        assert!(state.blocker_view("beta").is_none());
        assert!(
            !state.clear_dependency_blocker("beta"),
            "clearing an already-cleared wait changes nothing"
        );

        // An unrelated hold belongs to another owner and survives dependency
        // evidence about a different change.
        state.runtime_entry("held").transition_to_stalled(
            "acceptance_finding",
            "no progress",
            "snapshot",
        );
        assert!(!state.clear_dependency_blocker("held"));
        assert_eq!(state.display_status("held"), "stalled");
    }

    /// A ready change waiting only for an execution slot keeps plain `queued`:
    /// the projection reports the blockers classification found, and fabricates
    /// none.
    #[test]
    fn dependency_blocker_projection_capacity_only() {
        let mut state = OrchestratorState::new(vec!["ready".to_string()], 0);
        state.apply_command(ReducerCommand::AddToQueue("ready".to_string()));

        // Classification found nothing unresolved, so the withdrawal path runs
        // and leaves the row exactly as it was.
        assert!(!state.clear_dependency_blocker("ready"));
        assert_eq!(state.display_status("ready"), "queued");
        assert!(
            state.blocker_view("ready").is_none(),
            "an occupied execution slot is not a blocker"
        );
        let rt = state.change_runtime("ready").expect("runtime entry");
        assert_eq!(rt.wait_state, WaitState::None);
        assert_eq!(rt.blocker_kind(), BlockerKind::None);
    }

    /// A terminal or active row is never decorated with a dependency wait: the
    /// reconciliation path applies exactly the guard the transition path does.
    #[test]
    fn dependency_blocker_projection_refuses_terminal_and_active_rows() {
        let mut state = OrchestratorState::new(vec!["done".to_string(), "running".to_string()], 0);
        state.runtime_entry("done").terminal = TerminalState::Merged;
        state.runtime_entry("running").activity = ActivityState::Applying;

        assert!(!state.reconcile_dependency_blocker("done", &["alpha".to_string()]));
        assert!(!state.reconcile_dependency_blocker("running", &["alpha".to_string()]));
        assert_eq!(state.display_status("done"), "merged");
        assert_eq!(state.display_status("running"), "applying");
    }
}