cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
//! State management for the TUI
//!
//! This module contains AppState and ChangeState implementations,
//! organized into submodules by responsibility.
//!
//! ## Shared State Integration
//!
//! The TUI can reference the shared orchestration state from `crate::orchestration::state::OrchestratorState`
//! for unified state tracking across TUI and Web interfaces. The shared state provides:
//! - Pending/archived change tracking
//! - Apply count tracking per change
//! - Current change being processed
//! - Iteration counters
//!
//! Both TUI and Web states are updated via `ExecutionEvent` messages, ensuring consistency.

use crate::openspec::Change;
use crate::orchestration::operator_command::ParallelEligibility;
use crate::parallel::dedup::{DiagnosticDeduplicationKey, DiagnosticDeduplicationStore};
use crate::tui::config::TuiConfig;
use crate::tui::events::{LogEntry, LogLevel, TuiCommand};
use crate::tui::types::{
    AppExecutionMode, DeleteIntent, ModalState, StopMode, ViewMode, WorkspaceDirtyState,
    WorktreeInfo,
};
use ratatui::style::Color;
use ratatui::widgets::ListState;
use std::collections::{HashMap, HashSet};

use std::path::{Path, PathBuf};

use std::time::{Duration, Instant};
use tracing::{error, info, warn};

#[cfg(test)]
mod execution_mark_tests;
pub(crate) mod log_logic;
pub(crate) mod merged_row_dismissal;
pub(crate) mod modal_logic;
mod processing_logic;
mod selection_logic;
#[cfg(test)]
mod workspace_dirty_observability_tests;
mod worktree_action_logic;
mod worktree_logic;

// ============================================================================
// Constants
// ============================================================================

/// Auto-refresh interval in seconds
pub const AUTO_REFRESH_INTERVAL_SECS: u64 = 5;

/// Maximum number of log entries to keep
pub const MAX_LOG_ENTRIES: usize = 1000;

/// Stated when an `error` row has no retained diagnostic at all.
///
/// Explicit by design: the alternative — presenting an unrelated ordinary log as
/// the failure reason — would misreport why the change failed.
pub const ERROR_DETAILS_UNAVAILABLE: &str = "Error details unavailable";

// ============================================================================
// Type Definitions
// ============================================================================

/// Warning popup content
pub struct WarningPopup {
    pub title: String,
    pub message: String,
}

impl WarningPopup {
    pub fn new(title: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            message: message.into(),
        }
    }
}

/// Outcome of the most recent copy attempt made from the Error Details popup.
///
/// Kept on the popup rather than in the log panel so the operator reads the
/// result where the action happened, without the popup closing under them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CopyFeedback {
    /// The clipboard accepted the text.
    Copied,
    /// The clipboard refused, carrying the reason it gave.
    Failed(String),
}

impl CopyFeedback {
    /// Operator-facing one-line message for this outcome.
    pub fn message(&self) -> String {
        match self {
            CopyFeedback::Copied => "Copied to clipboard".to_string(),
            CopyFeedback::Failed(reason) => {
                format!("Copy failed: {reason}. Select the text manually to copy it.")
            }
        }
    }
}

/// Error Details popup content and popup-local presentation state.
///
/// Process-local observability state. It holds the retained final diagnostic for
/// one change so the operator can read and copy it after the matching log entry
/// has been evicted from the bounded buffer. It is never persisted and never
/// used as scheduler dispatch, retry routing, acceptance, archive, or merge input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorDetailsPopup {
    /// Change the diagnostic belongs to.
    pub change_id: String,
    /// Complete, untruncated final diagnostic.
    pub error: String,
    /// Popup-local scroll offset; it never moves the Changes list or Logs panel.
    pub scroll: u16,
    /// Result of the last copy attempt, if one has been made.
    pub copy_feedback: Option<CopyFeedback>,
}

impl ErrorDetailsPopup {
    /// The exact plain text `c` places on the clipboard.
    ///
    /// Stable by contract: `Change: <id>` and `Error: <diagnostic>` on two
    /// lines, so a pasted report is the same shape every time.
    pub fn clipboard_text(&self) -> String {
        format!("Change: {}\nError: {}", self.change_id, self.error)
    }
}

/// State of a single change in the TUI
#[derive(Debug, Clone)]
pub struct ChangeState {
    /// Change ID
    pub id: String,
    /// Number of completed tasks
    pub completed_tasks: u32,
    /// Total number of tasks
    pub total_tasks: u32,
    /// Display status cache (from reducer/TUI events)
    pub display_status_cache: String,
    /// Reducer-derived blocker kind for a `blocked` row.
    ///
    /// Cached from [`crate::orchestration::state::OrchestratorState::all_blocker_views`]
    /// rather than re-derived here, so the TUI can distinguish a dependency wait
    /// from an external prerequisite wait without inferring anything itself.
    pub blocker_kind_cache: crate::orchestration::state::BlockerKind,
    /// Reducer-derived operator-facing blocker detail for a blocked/stalled row.
    pub blocker_detail_cache: Option<String>,
    /// Display color cache for status
    pub display_color_cache: Color,
    /// Error message cache for error status
    pub error_message_cache: Option<String>,
    /// Whether this change is selected
    pub selected: bool,
    /// Whether this is a newly detected change
    pub is_new: bool,
    /// Whether this change is eligible for parallel execution, and why not.
    ///
    /// The reason is carried rather than collapsed into a boolean because the
    /// two ineligible cases look identical to admission but not to an operator:
    /// only dirty proposal content may be presented as uncommitted state.
    pub parallel_eligibility: ParallelEligibility,
    /// Whether a worktree exists for this change
    pub has_worktree: bool,
    /// Start boundary of the *current* active execution interval.
    ///
    /// `None` whenever the row is not actively executing. It is only ever the
    /// open interval's start, never the whole run's start, so wall-clock time
    /// spent in `error`, `stalled`, blocked, merge-wait, or any other inactive
    /// status can never leak into the displayed duration.
    pub started_at: Option<Instant>,
    /// Accumulated net execution time from every *closed* active interval.
    ///
    /// Retained across inactive and terminal transitions so a completed change
    /// keeps showing how long it actually ran. Presentation state only: it is
    /// process-local, never persisted, and never scheduler, resume, acceptance,
    /// archive, merge, or next-action input.
    pub elapsed_time: Option<Duration>,
    /// Current iteration number (for apply/archive/acceptance operations)
    pub iteration_number: Option<u32>,
    /// Ephemeral Apply-lane operation label: `"apply"` or `"commit"`.
    ///
    /// Purely rendering state. `display_status_cache` stays `"applying"` for the
    /// whole finalization sequence, and nothing routes on this field.
    pub apply_operation_cache: String,
    /// Whether the reducer has recorded archive completion for this change.
    ///
    /// Synchronized from
    /// [`crate::orchestration::state::OrchestratorState::archived_changes`] in the
    /// same snapshot read as `display_status_cache`, so a row's status and its
    /// archive milestone can never come from two different instants.
    ///
    /// It exists because the two facts genuinely diverge: after archive the
    /// reducer truthfully advances the row to `resolving`, `resolve pending`, or
    /// `merge wait`, none of which is a terminal status. Inferring "post-archive"
    /// from `resolving` would misclassify a fresh-process resolve retry, which is
    /// `resolving` with no archive on record and stays markable.
    ///
    /// Presentation state only, and process-local: it is discarded on restart, is
    /// never persisted, and never becomes scheduler, resume, acceptance, archive,
    /// or merge input.
    pub archive_complete_cache: bool,
}

/// Main application state for the TUI
pub struct AppState {
    /// Current view mode (Changes or Worktrees)
    pub view_mode: ViewMode,
    /// Current orchestration execution mode.
    ///
    /// This axis is never replaced by a popup: overlays live in [`AppState::modal`].
    pub execution_mode: AppExecutionMode,
    /// Active modal interaction layered over `execution_mode`, if any.
    ///
    /// Process-local presentation/input-ownership state. It is never persisted and
    /// must not be used as scheduler dispatch, resume routing, acceptance, archive,
    /// merge, or next-action input.
    pub modal: Option<ModalState>,
    /// List of changes with their states
    pub changes: Vec<ChangeState>,
    /// Current cursor position in the list
    pub cursor_index: usize,
    /// List widget state
    pub list_state: ListState,
    /// List of worktrees
    pub worktrees: Vec<WorktreeInfo>,
    /// Current cursor position in the worktree list
    pub worktree_cursor_index: usize,
    /// Worktree list widget state
    pub worktree_list_state: ListState,
    /// ID of the currently processing change
    pub current_change: Option<String>,
    /// ID of the change that caused the error (for display in Error mode)
    pub error_change_id: Option<String>,
    /// Log entries
    pub logs: Vec<LogEntry>,
    /// Last auto-refresh timestamp
    pub last_refresh: Instant,
    /// Number of newly detected changes
    pub new_change_count: usize,
    /// Known change IDs (for detecting new changes)
    pub known_change_ids: HashSet<String>,
    /// Whether the application should quit
    pub should_quit: bool,
    /// Warning message to display
    pub warning_message: Option<String>,
    /// Warning popup content
    pub warning_popup: Option<WarningPopup>,
    /// Scroll offset for the warning popup body (presentation-only state)
    pub warning_popup_scroll: u16,
    /// Error Details popup for a change-level failure, if one is open.
    ///
    /// Lives on its own axis rather than in [`AppState::modal`] so opening it can
    /// never replace a pending confirmation, and so it can claim its keys ahead
    /// of interaction modals while still yielding to the warning popup.
    pub error_details_popup: Option<ErrorDetailsPopup>,
    /// Clipboard boundary used by the Error Details popup.
    ///
    /// Injectable so tests assert what would have been copied without mutating
    /// the developer's clipboard.
    clipboard: std::sync::Arc<dyn crate::tui::clipboard::Clipboard>,
    /// Current spinner animation frame
    pub spinner_frame: usize,
    /// Process-local sequence number of `logs[0]`.
    ///
    /// Buffer trimming shifts indices, so the Logs anchor cannot use them as
    /// identity. This counter gives every retained entry a stable process-local
    /// ID (`log_seq_base + index`) without adding a field to `LogEntry`.
    log_seq_base: u64,
    /// Top visible Logs display line, in source coordinates.
    ///
    /// `None` means "follow the newest line" — the auto-scroll position.
    /// Ephemeral in-process presentation state only; it is discarded on restart
    /// and never used as workflow-control input.
    pub(crate) log_anchor: Option<log_logic::LogViewAnchor>,
    /// Last Logs-panel geometry the renderer observed.
    pub(crate) log_viewport: log_logic::LogViewport,
    /// Whether to auto-scroll logs to bottom on new entries
    pub log_auto_scroll: bool,
    /// Current stop mode
    pub stop_mode: StopMode,
    /// Whether Ready is currently backed by a live persistent-scheduler idle
    /// episode rather than pre-run selection.
    ///
    /// Process-local presentation state, exactly like `execution_mode`: it
    /// defaults to false, is discarded on restart, and never authorizes a
    /// command. It only makes the live-scheduler controls discoverable —
    /// [`crate::orchestration::run_control::RunControlService`] revalidates
    /// scheduler liveness itself before executing any of them.
    pub persistent_scheduler_idle: bool,
    /// VCS backend being used (git)
    pub vcs_backend: String,
    /// Max concurrent workspaces for worktree execution
    pub max_concurrent: usize,
    /// Repository root captured once at TUI startup, as header project identity.
    ///
    /// Private on purpose: the header must report the project this process was
    /// started against, so the only way in is
    /// [`AppState::set_project_path`], which the runner calls with the same
    /// `repo_root` the refresh task and the dirty predicate already use.
    /// Rendering never re-derives it from the process current directory, which
    /// can move after startup.
    ///
    /// Presentation-only, process-local state. It is never persisted and never
    /// used as scheduler dispatch, resume routing, acceptance, archive, or
    /// next-action input.
    project_path: PathBuf,
    /// Attached base branch captured once at TUI startup, as header identity.
    ///
    /// Private for the same reason as [`AppState::project_path`]: the header
    /// reports the branch this process was started on, so the only way in is
    /// [`AppState::set_base_branch`], which the runner calls with the branch it
    /// resolved from the same `repo_root`. Rendering never re-reads Git, so a
    /// later checkout cannot retarget the header.
    ///
    /// `None` when startup could not resolve an attached branch — a detached
    /// HEAD or an unavailable branch lookup — in which case the header renders
    /// no branch segment rather than inventing one.
    ///
    /// Presentation-only, process-local state. It is never persisted and never
    /// used as scheduler dispatch, resume routing, acceptance, archive, or
    /// next-action input; the integration base branch stays whatever the
    /// workspace's own Git state says at the moment work runs.
    base_branch: Option<String>,
    /// When orchestration started (for overall elapsed time)
    pub orchestration_started_at: Option<Instant>,
    /// Total elapsed time when orchestration finished
    pub orchestration_elapsed: Option<Duration>,
    /// Web UI URL (set when web server is enabled)
    pub web_url: Option<String>,
    /// Map of change_id to worktree path for active worktrees (for progress fallback)
    pub worktree_paths: HashMap<String, PathBuf>,
    /// Process-local UI markers for manually requested worktree deletions.
    ///
    /// This is transient observability/input-suppression state only. It must not be
    /// persisted or used by orchestration reducers/schedulers as workflow-control input.
    deleting_worktree_paths: HashSet<PathBuf>,
    /// Reference to shared orchestration state (for unified state tracking)
    /// TUI can query this for pending/archived status, apply counts, etc.
    pub shared_orchestrator_state:
        Option<std::sync::Arc<tokio::sync::RwLock<crate::orchestration::state::OrchestratorState>>>,
    /// Shared single-resolver reservation ledger.
    ///
    /// The TUI does not own resolve ordering: the same process-local ledger backs
    /// `/api/v2`, so an `M` keypress and a remote `resolve_merge` compete for one
    /// active resolver and share one FIFO queue.
    resolve_reservations: std::sync::Arc<crate::orchestration::run_control::ResolveReservations>,
    /// Whether the log panel is visible in Changes view
    pub logs_panel_enabled: bool,
    /// Whether the Logs panel is limited to the proposal under the Changes cursor.
    ///
    /// Presentation-only, non-persistent TUI state. It never mutates
    /// `AppState::logs` and must not be used as scheduler dispatch, resume
    /// routing, acceptance, or archive input.
    pub selected_proposal_log_filter: bool,
    /// Client-local TUI preferences such as keybindings.
    ///
    /// This is presentation/input mapping state only and must not be used for
    /// resume routing, acceptance gating, archive routing, or scheduling.
    pub tui_config: TuiConfig,
    /// Latest reducer-derived display status snapshot observed by the TUI.
    ///
    /// This is presentation-only state used to order display synchronization evidence:
    /// reducer-owned lifecycle intent is stronger than refresh-derived display hints.
    /// It must not be used as scheduler dispatch, resume routing, or workflow-control input.
    reducer_display_status_snapshot: HashMap<String, &'static str>,
    /// Latest reducer-derived archive-completion snapshot observed by the TUI.
    ///
    /// Retained at app level, not only per row, because catalog refresh rebuilds
    /// `ChangeState` values: a row that refresh re-creates from `Change` would
    /// otherwise come back with `archive_complete_cache = false` and flash a
    /// checkbox the reducer already retired. Refresh reapplies this snapshot in
    /// the same pass.
    ///
    /// Presentation-only, process-local state. It is discarded on restart and is
    /// never used as scheduler dispatch, resume routing, acceptance, or archive
    /// input.
    reducer_archived_changes: HashSet<String>,
    /// Runtime-only observability dedupe for TUI diagnostics.
    ///
    /// This state is not workflow-control state.
    diagnostic_dedup: DiagnosticDeduplicationStore<DiagnosticDeduplicationKey>,
    /// Process-local execution marks shared with the operator command service.
    ///
    /// `ChangeState::selected` stays the rendering projection; this store is the
    /// frontend-independent copy other adapters read. It is never persisted, so a
    /// restarted process starts with every mark `false`.
    execution_marks: std::sync::Arc<crate::orchestration::operator_command::ExecutionMarkStore>,
    /// Shared process-wide worktree runtime facts.
    ///
    /// One store, shared by every frontend, so a keypress and a remote command
    /// read the same concurrency, backend, and per-change eligibility.
    parallel_runtime: std::sync::Arc<crate::orchestration::operator_command::ParallelRuntime>,
    /// Latest successful workspace dirty observation from the local refresh task.
    ///
    /// Private on purpose: the only way to move it is
    /// [`AppState::adopt_workspace_dirty_observation`], which consumes a typed
    /// event that the refresh task publishes only after a completed `git status`
    /// read. Nothing else can turn a failed or unfinished check into a
    /// `Clean` claim.
    ///
    /// Presentation-only, process-local state. It is never persisted and never
    /// used as scheduler dispatch, resume routing, acceptance, archive, or
    /// next-action input.
    workspace_dirty: WorkspaceDirtyState,
    /// Change IDs the operator dismissed from this process's Changes projection.
    ///
    /// Presentation-only, process-local state, in the same class as `modal` and
    /// `selected_proposal_log_filter`: it is never serialized, never sent through
    /// `TuiCommand`, never copied into `OrchestratorState`, and never exposed
    /// through `/api/v2`. A restarted process starts empty and re-derives every
    /// row from the workspace, so it is not durable workflow state.
    ///
    /// It suppresses *retained terminal* presentation only. Catalog processing
    /// clears an ID from this set the moment it re-observes it as an active
    /// non-terminal change, so an ID that comes back to life is never hidden.
    dismissed_merged_ids: HashSet<String>,
    /// Target-scoped mark writes an operator interaction requested but that the
    /// shared service has not applied yet.
    ///
    /// Key handling is where the operator expresses intent, and it must not be
    /// the place the shared store is written: the write has to take the same
    /// mutation guard event reconciliation takes, and that guard is async. The
    /// interaction records `(change_id, marked)` pairs here instead, the run loop
    /// drains them through the shared service, and the rows are then mirrored
    /// back from the store. Nothing outside one process lifetime sees this.
    pending_mark_writes: Vec<(String, bool)>,
}

// ============================================================================
// ChangeState Implementation
// ============================================================================

impl ChangeState {
    /// Create a new ChangeState from a Change
    ///
    /// Note: This method initializes state from the Change object. Task progress
    /// is synchronized with shared orchestrator state in update_changes(), which
    /// populates OrchestratorState::task_progress() from fetched changes and then
    /// queries it back when updating UI state. This ensures consistency between
    /// TUI and orchestrator for progress tracking.
    pub fn from_change(change: &Change) -> Self {
        Self {
            id: change.id.clone(),
            // Initial values from Change object; synchronized with shared state in update_changes()
            completed_tasks: change.completed_tasks,
            total_tasks: change.total_tasks,
            selected: false, // Always start unselected
            is_new: false,
            display_status_cache: "not queued".to_string(),
            blocker_kind_cache: crate::orchestration::state::BlockerKind::None,
            blocker_detail_cache: None,
            display_color_cache: Color::DarkGray,
            error_message_cache: None,
            parallel_eligibility: ParallelEligibility::Eligible,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
            apply_operation_cache: "apply".to_string(),
            archive_complete_cache: false,
        }
    }

    /// Operation label the Apply lane renders for this row.
    pub fn apply_operation(&self) -> &str {
        if self.apply_operation_cache.is_empty() {
            return "apply";
        }
        &self.apply_operation_cache
    }

    /// Whether this change may take part in parallel execution.
    ///
    /// Every ineligible reason answers `false` here: this is the admission
    /// guard, and narrowing it is never what distinguishing reasons is for.
    pub fn is_parallel_eligible(&self) -> bool {
        self.parallel_eligibility.is_eligible()
    }

    /// Whether uncommitted or untracked proposal files were actually observed.
    ///
    /// The `UNCOMMITTED` badge and the commit instruction key off this rather
    /// than off [`ChangeState::is_parallel_eligible`], so a clean proposal that
    /// is merely absent from `HEAD` is never described as dirty.
    pub fn has_uncommitted_proposal_files(&self) -> bool {
        self.parallel_eligibility.has_uncommitted_proposal_files()
    }

    /// Calculate progress percentage
    pub fn progress_percent(&self) -> f32 {
        if self.total_tasks == 0 {
            return 0.0;
        }
        (self.completed_tasks as f32 / self.total_tasks as f32) * 100.0
    }

    /// Open a new active execution interval, keeping any interval already open.
    ///
    /// Idempotent by construction: repeated active updates — the same active
    /// status re-applied, or one active status following another — must keep
    /// the original start boundary rather than restarting the interval.
    pub fn start_active_interval(&mut self) {
        self.start_active_interval_at(Instant::now());
    }

    pub(crate) fn start_active_interval_at(&mut self, now: Instant) {
        if self.started_at.is_none() {
            self.started_at = Some(now);
        }
    }

    /// Close the current active interval exactly once and add it to the total.
    ///
    /// Idempotent as well, and that is what makes the process-level `Stopped`
    /// boundary order-independent: whichever of the stop event and the reducer's
    /// `not queued` synchronization arrives second finds no open interval and
    /// adds nothing.
    pub fn pause_active_interval(&mut self) {
        self.pause_active_interval_at(Instant::now());
    }

    pub(crate) fn pause_active_interval_at(&mut self, now: Instant) {
        let Some(started) = self.started_at.take() else {
            return;
        };
        let interval = now.saturating_duration_since(started);
        self.elapsed_time = Some(self.elapsed_time.unwrap_or_default() + interval);
    }

    /// Net execution time to display: closed intervals plus the open one.
    ///
    /// `None` only when the row has never executed, which is what the `--`
    /// placeholder means. An inactive or terminal row with history answers with
    /// its retained total, which stops growing because no interval is open.
    pub fn current_total_elapsed(&self) -> Option<Duration> {
        self.current_total_elapsed_at(Instant::now())
    }

    pub(crate) fn current_total_elapsed_at(&self, now: Instant) -> Option<Duration> {
        match (self.elapsed_time, self.started_at) {
            (None, None) => None,
            (accumulated, open) => Some(
                accumulated.unwrap_or_default()
                    + open
                        .map(|started| now.saturating_duration_since(started))
                        .unwrap_or_default(),
            ),
        }
    }

    /// Whether this row proves execution history — an open interval or a
    /// retained accumulated duration.
    ///
    /// Catalog refresh uses this to keep a temporarily absent row alive without
    /// introducing a separate durable flag for the same fact.
    pub fn has_execution_history(&self) -> bool {
        self.started_at.is_some() || self.elapsed_time.is_some()
    }

    pub fn set_display_status_cache(&mut self, status: &str) {
        // Net execution timing is centralized here so every status transition —
        // reducer synchronization, event handler, or refresh-derived repaint —
        // accumulates against the one shared active vocabulary instead of a
        // second hand-written list that could fall behind it.
        if crate::orchestration::operator_command::is_active_status(status) {
            self.start_active_interval();
        } else {
            self.pause_active_interval();
        }
        self.display_status_cache = status.to_string();
        self.display_color_cache = match status {
            "not queued" => Color::DarkGray,
            "queued" => Color::Yellow,
            "blocked" => Color::Gray,
            "stalled" => Color::LightYellow,
            "preparing" => Color::Green,
            "applying" => Color::Cyan,
            "accepting" => Color::LightGreen,
            "archiving" => Color::Magenta,
            "merge wait" => Color::LightMagenta,
            "resolve pending" => Color::Magenta,
            "resolving" => Color::LightCyan,
            "archived" => Color::Blue,
            "merged" => Color::LightBlue,
            "rejected" => Color::LightRed,
            "error" => Color::Red,
            _ => Color::DarkGray,
        };
        if status != "error" {
            self.error_message_cache = None;
        }
        // Leaving a blocked/stalled row drops its blocker view, so a stale
        // badge can never outlive the hold that produced it.
        if !matches!(status, "blocked" | "stalled") {
            self.blocker_kind_cache = crate::orchestration::state::BlockerKind::None;
            self.blocker_detail_cache = None;
        }
    }

    /// Status text for the row badge.
    ///
    /// A blocked row appends its reducer-derived blocker kind so an operator can
    /// tell a dependency wait from an external prerequisite wait at a glance;
    /// every other status keeps its plain word.
    pub fn status_badge(&self) -> String {
        match (
            self.display_status_cache.as_str(),
            self.blocker_kind_cache.as_str(),
        ) {
            ("blocked", Some(kind)) => format!("blocked:{kind}"),
            (status, _) => status.to_string(),
        }
    }

    /// Adopt a reducer-derived blocker view verbatim.
    pub fn set_blocker_view(&mut self, view: Option<&crate::orchestration::state::BlockerView>) {
        match view {
            Some(view) => {
                self.blocker_kind_cache = view.kind;
                self.blocker_detail_cache = view.detail.clone();
            }
            None => {
                self.blocker_kind_cache = crate::orchestration::state::BlockerKind::None;
                self.blocker_detail_cache = None;
            }
        }
    }

    pub fn set_error_message_cache(&mut self, message: String) {
        self.error_message_cache = Some(message);
        self.set_display_status_cache("error");
    }

    /// Update iteration number with monotonic increase guard
    ///
    /// This helper ensures iteration display doesn't regress within the same stage.
    /// - Ignores None values (no-op)
    /// - Only updates if new_iteration > current iteration_number
    /// - Prevents display flickering when out-of-order events arrive
    pub fn update_iteration_monotonic(&mut self, new_iteration: Option<u32>) {
        if let Some(new_val) = new_iteration {
            match self.iteration_number {
                None => {
                    // First iteration for this stage, accept it
                    self.iteration_number = Some(new_val);
                }
                Some(current) => {
                    // Only update if new value is higher (monotonic increase)
                    if new_val > current {
                        self.iteration_number = Some(new_val);
                    }
                    // Otherwise, ignore (prevents regression)
                }
            }
        }
        // If new_iteration is None, ignore (no update)
    }
}

// ============================================================================
// AppState Core Implementation
// ============================================================================

impl AppState {
    /// Create a new AppState with initial changes
    ///
    /// All changes start unselected on startup.
    /// Users must explicitly select changes to process.
    pub fn new(changes: Vec<Change>) -> Self {
        let known_ids: HashSet<String> = changes.iter().map(|c| c.id.clone()).collect();

        // All changes start unselected
        let change_states: Vec<ChangeState> =
            changes.iter().map(ChangeState::from_change).collect();

        let mut list_state = ListState::default();
        if !change_states.is_empty() {
            list_state.select(Some(0));
        }

        Self {
            view_mode: ViewMode::Changes,
            execution_mode: AppExecutionMode::Select,
            modal: None,
            changes: change_states,
            cursor_index: 0,
            list_state,
            worktrees: Vec::new(),
            worktree_cursor_index: 0,
            worktree_list_state: ListState::default(),
            current_change: None,
            error_change_id: None,
            logs: Vec::new(),
            last_refresh: Instant::now(),
            new_change_count: 0,
            known_change_ids: known_ids,
            should_quit: false,
            warning_message: None,
            warning_popup: None,
            warning_popup_scroll: 0,
            error_details_popup: None,
            clipboard: crate::tui::clipboard::default_clipboard(),
            spinner_frame: 0,
            log_seq_base: 0,
            log_anchor: None,
            log_viewport: log_logic::LogViewport::default(),
            log_auto_scroll: true,
            stop_mode: StopMode::None,
            persistent_scheduler_idle: false,
            vcs_backend: "git".to_string(),
            max_concurrent: 4, // Default value, can be overridden from config
            project_path: PathBuf::new(),
            base_branch: None,
            orchestration_started_at: None,
            orchestration_elapsed: None,
            web_url: None,
            worktree_paths: HashMap::new(),
            deleting_worktree_paths: HashSet::new(),
            shared_orchestrator_state: None,
            resolve_reservations: std::sync::Arc::new(
                crate::orchestration::run_control::ResolveReservations::new(),
            ),
            logs_panel_enabled: true, // Default: logs panel visible
            selected_proposal_log_filter: false, // Default: show logs for every proposal
            tui_config: TuiConfig::default(),
            reducer_display_status_snapshot: HashMap::new(),
            reducer_archived_changes: HashSet::new(),
            diagnostic_dedup: DiagnosticDeduplicationStore::new(),
            execution_marks: std::sync::Arc::new(
                crate::orchestration::operator_command::ExecutionMarkStore::new(),
            ),
            parallel_runtime: std::sync::Arc::new(
                crate::orchestration::operator_command::ParallelRuntime::new(),
            ),
            workspace_dirty: WorkspaceDirtyState::default(),
            dismissed_merged_ids: HashSet::new(),
            pending_mark_writes: Vec::new(),
        }
    }

    /// Adopt the startup repository root as this process's project identity.
    ///
    /// Called once by the local TUI runner with the `repo_root` it captured
    /// before any refresh ran. Nothing re-reads the process current directory
    /// afterwards, so a later `chdir` cannot retarget the header.
    pub fn set_project_path(&mut self, repo_root: impl Into<PathBuf>) {
        self.project_path = repo_root.into();
    }

    /// The captured project path, for the header.
    ///
    /// Empty until the runner sets it; the header renders no path segment in
    /// that case rather than inventing one.
    pub fn project_path(&self) -> &Path {
        &self.project_path
    }

    /// Adopt the startup-resolved attached branch as header identity.
    ///
    /// Called once by the local TUI runner with the branch it read from the
    /// captured `repo_root`. A missing, detached, or blank result is stored as
    /// `None`, so a whitespace-only branch name can never become an empty
    /// `[]` segment. Nothing re-reads Git afterwards, so a later checkout in
    /// the repository cannot retarget the header.
    pub fn set_base_branch(&mut self, branch: Option<impl Into<String>>) {
        self.base_branch = branch
            .map(Into::into)
            .map(|branch| branch.trim().to_string())
            .filter(|branch| !branch.is_empty());
    }

    /// The captured base branch, for the header.
    ///
    /// `None` until the runner sets it, and `None` whenever startup could not
    /// resolve an attached branch; the header renders no branch segment in
    /// that case rather than inventing one.
    pub fn base_branch(&self) -> Option<&str> {
        self.base_branch.as_deref()
    }

    /// Latest workspace dirty observation, for the header badge.
    ///
    /// Read-only by design: rendering is the only consumer, and there is no
    /// setter beyond the typed observation adoption path.
    pub fn workspace_dirty(&self) -> WorkspaceDirtyState {
        self.workspace_dirty
    }

    /// Shared handle to the process-wide parallel runtime facts.
    pub fn parallel_runtime(
        &self,
    ) -> std::sync::Arc<crate::orchestration::operator_command::ParallelRuntime> {
        self.parallel_runtime.clone()
    }

    /// Adopt an externally owned parallel runtime store.
    ///
    /// Test-only for the same reason as [`AppState::set_execution_marks`]:
    /// production wires this the other way round — the run-control service and
    /// the web state are built over `parallel_runtime()` — but a test that
    /// builds the shared services first needs the app to join the store they
    /// already read, or the toggle would exist once per frontend.
    #[cfg(test)]
    pub fn set_parallel_runtime(
        &mut self,
        parallel: std::sync::Arc<crate::orchestration::operator_command::ParallelRuntime>,
    ) {
        self.parallel_runtime = parallel;
        self.publish_parallel_runtime();
    }

    /// Publish the TUI's observations into the shared parallel runtime store.
    ///
    /// Concurrency, backend, and per-change eligibility are all observations
    /// only this frontend makes; publishing them is what lets the shared start
    /// guard and a remote client use them without re-deriving them.
    pub fn publish_parallel_runtime(&self) {
        self.parallel_runtime
            .set_max_concurrent(self.max_concurrent);
        self.parallel_runtime
            .set_vcs_backend(self.vcs_backend.clone());
        self.parallel_runtime.set_parallel_ineligible(
            self.changes
                .iter()
                .filter(|change| !change.is_parallel_eligible())
                .map(|change| (change.id.clone(), change.parallel_eligibility)),
        );
    }

    /// Clear mark and queue presentation for every parallel-ineligible row.
    ///
    /// Returns the affected change IDs so the caller can report them; an
    /// operator whose marks silently disappeared cannot tell that from a bug.
    fn clear_parallel_ineligible_intent(&mut self) -> Vec<String> {
        use crate::orchestration::operator_command::{
            parallel_cleanup_targets, ParallelCleanupRow,
        };

        let rows: Vec<ParallelCleanupRow<'_>> = self
            .changes
            .iter()
            .map(|change| ParallelCleanupRow {
                change_id: &change.id,
                parallel_eligible: change.is_parallel_eligible(),
                marked: change.selected,
                queued: change.display_status_cache == "queued",
            })
            .collect();
        let cleared = parallel_cleanup_targets(&rows);

        for change in &mut self.changes {
            if !cleared.contains(&change.id) {
                continue;
            }
            change.selected = false;
            if change.display_status_cache == "queued" {
                change.set_display_status_cache("not queued");
            }
            // Target-scoped, never a whole-store replace: an ineligible row loses
            // its own mark, and a mark another frontend set on an unrelated row
            // cannot be swept away by this frontend's cached row set.
            self.execution_marks.set(&change.id, false);
        }
        cleared
    }

    /// Shared handle to the process-local execution marks.
    ///
    /// The operator command service and any future frontend adapter read marks
    /// through this handle instead of reaching into TUI rendering state.
    pub fn execution_marks(
        &self,
    ) -> std::sync::Arc<crate::orchestration::operator_command::ExecutionMarkStore> {
        self.execution_marks.clone()
    }

    /// Adopt an externally owned execution-mark store.
    ///
    /// Test-only by construction: production wires this the other way round — the
    /// run-control service is built over `execution_marks()` — but a test that
    /// builds the service first needs the app to join the store the service
    /// already reads, or the "authoritative marked target set" would exist in two
    /// copies.
    #[cfg(test)]
    pub fn set_execution_marks(
        &mut self,
        marks: std::sync::Arc<crate::orchestration::operator_command::ExecutionMarkStore>,
    ) {
        self.execution_marks = marks;
    }

    /// Shared handle to the process-local resolve reservation ledger.
    ///
    /// The run-control service takes the same handle, which is what makes the
    /// single-resolver rule hold across the TUI and `/api/v2` instead of once per
    /// frontend.
    pub fn resolve_reservations(
        &self,
    ) -> std::sync::Arc<crate::orchestration::run_control::ResolveReservations> {
        self.resolve_reservations.clone()
    }

    /// Adopt an externally owned reservation ledger.
    ///
    /// Test-only for the same reason as [`AppState::set_execution_marks`]:
    /// production builds the run-control service over `resolve_reservations()`.
    #[cfg(test)]
    pub fn set_resolve_reservations(
        &mut self,
        reservations: std::sync::Arc<crate::orchestration::run_control::ResolveReservations>,
    ) {
        self.resolve_reservations = reservations;
    }

    /// True when a merge resolution currently owns the single resolver slot.
    pub fn is_resolving(&self) -> bool {
        self.resolve_reservations.is_active()
    }

    /// Record that `change_id` owns the resolver (driven by `ResolveStarted`).
    pub fn set_resolving(&self, change_id: &str) {
        self.resolve_reservations.mark_active(change_id);
    }

    /// Clear the active resolver without promoting a waiting change.
    pub fn clear_resolving(&self) {
        if let Some(active) = self.resolve_reservations.active() {
            self.resolve_reservations.cancel(&active);
        }
    }

    /// Mirror row marks from the shared store.
    ///
    /// One direction only, and this is the direction: the store decides, the row
    /// renders. A system event can revoke a mark while this frontend still holds
    /// a stale row, so a row that disagreed with the store used to be a second
    /// authority — the one that let the TUI show `[ ]` while `/api/v2` still
    /// reported `execution_marked: true`.
    pub fn sync_execution_marks_from_store(&mut self) {
        for change in &mut self.changes {
            change.selected = self.execution_marks.is_marked(&change.id);
        }
        self.acknowledge_operator_mark_interactions();
    }

    /// Retire the `NEW` badge of every row a settled operator mark interaction
    /// touched, whatever frontend that interaction arrived through.
    ///
    /// `NEW` is attention state: it says "you have not looked at this yet". An
    /// operator who marked or unmarked a change has looked at it, and that is
    /// true whether they pressed Space here or drove `/api/v2`, `cflx client`,
    /// or MCP — the same shared store settled the interaction either way. Only
    /// reading the mark *value* is what let a change render as remotely handled
    /// and still new at the same time.
    ///
    /// The store hands over interactions, never mark state, so none of the other
    /// writers to the same field can reach this: passive synchronization drains
    /// an empty batch, an unchanged request never records one, and neither
    /// event-driven revocation nor Start admission arms settlement at all.
    ///
    /// A target with no row is dropped rather than held: the acknowledgement is
    /// about attention that exists now, and a change this frontend is not
    /// displaying has none to retire.
    fn acknowledge_operator_mark_interactions(&mut self) {
        let interacted = self.execution_marks.take_operator_interactions();
        if interacted.is_empty() {
            return;
        }

        let mut acknowledged = false;
        for change in &mut self.changes {
            if change.is_new && interacted.iter().any(|id| id == &change.id) {
                change.is_new = false;
                acknowledged = true;
            }
        }

        // Recounted from the rows that survived rather than decremented per
        // acknowledgement, for the same reason refresh recounts: the footer must
        // describe the projection it is rendered beside, and an unrelated NEW row
        // keeps its badge and its place in that count.
        if acknowledged {
            self.new_change_count = self.changes.iter().filter(|c| c.is_new).count();
        }
    }

    /// Record a target-scoped mark write for the run loop to apply.
    ///
    /// The interaction has already run the shared admission classification for
    /// the row; what is deferred is only the *write*, because it must take the
    /// same async mutation guard event reconciliation takes.
    pub(crate) fn request_mark_write(&mut self, change_id: &str, marked: bool) {
        if let Some(pending) = self
            .pending_mark_writes
            .iter_mut()
            .find(|(id, _)| id == change_id)
        {
            pending.1 = marked;
            return;
        }
        self.pending_mark_writes
            .push((change_id.to_string(), marked));
    }

    /// Take the mark writes recorded since the last drain, in request order.
    pub fn take_pending_mark_writes(&mut self) -> Vec<(String, bool)> {
        std::mem::take(&mut self.pending_mark_writes)
    }

    /// Apply the pending mark writes straight to the store.
    ///
    /// Test-only: production drains them through `OperatorCommandService`, which
    /// is what makes the write take the shared mutation guard. A test with no
    /// service still needs the store to reach the state the run loop would have
    /// produced before the next event arrives.
    #[cfg(test)]
    pub fn flush_pending_mark_writes(&mut self) {
        for (change_id, marked) in self.take_pending_mark_writes() {
            self.execution_marks.set(&change_id, marked);
        }
    }

    /// Publish the current TUI row projection into the shared store.
    ///
    /// Test-only. Production never writes the store from a whole row set: a
    /// cached row that a concurrent event already invalidated would resurrect
    /// the mark that event revoked, and would overwrite marks this frontend
    /// never observed. Operator interactions use target-scoped writes through
    /// the shared service instead; tests use this to arrange a starting state.
    #[cfg(test)]
    pub fn publish_execution_marks(&self) {
        self.execution_marks.replace(
            self.changes
                .iter()
                .filter(|change| change.selected)
                .map(|change| change.id.clone()),
        );
    }

    /// True when at least one row carries retryable evidence the service admits.
    ///
    /// Route classification is the shared one, so guidance offers the retry key
    /// only when some target really exists for it. A retained Apply
    /// iteration-limit diagnostic is deliberately not consulted: the shared
    /// service admits an explicit retry on the row's terminal-error evidence, so
    /// consulting it here would reintroduce a frontend-only refusal.
    pub fn has_admissible_retry_target(&self) -> bool {
        self.changes.iter().any(|change| {
            crate::orchestration::operator_command::classify_retry_route(
                &change.display_status_cache,
                change.blocker_kind_cache,
            )
            .is_some()
        })
    }

    pub fn set_tui_config(&mut self, tui_config: TuiConfig) {
        self.tui_config = tui_config;
    }

    pub fn start_key_label(&self) -> String {
        self.tui_config.start_key_label()
    }

    /// Show a warning popup and reset popup-local presentation state.
    pub fn show_warning_popup(&mut self, title: impl Into<String>, message: impl Into<String>) {
        self.warning_popup = Some(WarningPopup::new(title, message));
        self.warning_popup_scroll = 0;
    }

    /// Clear any warning popup and reset popup-local presentation state.
    pub fn clear_warning_popup(&mut self) {
        self.warning_popup = None;
        self.warning_popup_scroll = 0;
    }

    /// Scroll the warning popup body by a signed amount while keeping the offset non-negative.
    pub fn scroll_warning_popup(&mut self, delta: i16) {
        if delta.is_negative() {
            self.warning_popup_scroll = self
                .warning_popup_scroll
                .saturating_sub(delta.unsigned_abs());
        } else {
            self.warning_popup_scroll = self.warning_popup_scroll.saturating_add(delta as u16);
        }
    }

    /// Open the Error Details popup for the change under the Changes cursor.
    ///
    /// Only an `error` row can open it: every other row keeps whatever `Enter`
    /// already did. Returns whether the popup was opened, so the caller can fall
    /// through to the pre-existing behavior when it was not.
    ///
    /// Opening is presentation only — no workflow-control state changes.
    pub fn open_error_details_popup(&mut self) -> bool {
        if self.view_mode != ViewMode::Changes {
            return false;
        }

        let Some(change) = self.changes.get(self.cursor_index) else {
            return false;
        };
        if change.display_status_cache != "error" {
            return false;
        }

        self.error_details_popup = Some(ErrorDetailsPopup {
            change_id: change.id.clone(),
            error: change
                .error_message_cache
                .clone()
                .unwrap_or_else(|| ERROR_DETAILS_UNAVAILABLE.to_string()),
            scroll: 0,
            copy_feedback: None,
        });
        true
    }

    /// Close the Error Details popup and drop its popup-local state.
    ///
    /// Closing is presentation only: it never transitions the change, the queue,
    /// or the run.
    pub fn close_error_details_popup(&mut self) {
        self.error_details_popup = None;
    }

    /// Scroll the Error Details popup body by a signed amount.
    ///
    /// The offset stays non-negative and the Changes cursor and Logs-panel
    /// position are untouched, so popup scrolling can never move the views
    /// underneath it.
    pub fn scroll_error_details_popup(&mut self, delta: i16) {
        let Some(popup) = self.error_details_popup.as_mut() else {
            return;
        };
        popup.scroll = if delta.is_negative() {
            popup.scroll.saturating_sub(delta.unsigned_abs())
        } else {
            popup.scroll.saturating_add(delta as u16)
        };
    }

    /// Copy the open Error Details popup's diagnostic to the OS clipboard.
    ///
    /// The popup stays open and keeps its complete diagnostic either way; the
    /// outcome is reported inside the popup so the operator never loses the text
    /// they were trying to copy.
    pub fn copy_error_details(&mut self) {
        let Some(popup) = self.error_details_popup.as_ref() else {
            return;
        };

        let text = popup.clipboard_text();
        let feedback = match self.clipboard.set_text(&text) {
            Ok(()) => CopyFeedback::Copied,
            Err(reason) => CopyFeedback::Failed(reason),
        };

        if let Some(popup) = self.error_details_popup.as_mut() {
            popup.copy_feedback = Some(feedback);
        }
    }

    /// Replace the clipboard boundary with a test double.
    ///
    /// Test-only: production always keeps
    /// [`crate::tui::clipboard::default_clipboard`], so this is the seam that
    /// lets automated tests assert what would have been copied without writing
    /// to the developer's real clipboard.
    #[cfg(test)]
    pub fn set_clipboard(
        &mut self,
        clipboard: std::sync::Arc<dyn crate::tui::clipboard::Clipboard>,
    ) {
        self.clipboard = clipboard;
    }

    /// Set reference to shared orchestration state for unified tracking.
    /// This allows TUI to query core orchestration state (pending/archived, apply counts, etc.)
    pub fn set_shared_state(
        &mut self,
        shared_state: std::sync::Arc<
            tokio::sync::RwLock<crate::orchestration::state::OrchestratorState>,
        >,
    ) {
        self.shared_orchestrator_state = Some(shared_state);
    }

    /// Show QR popup (only when web_url is set).
    ///
    /// The popup is layered over the current execution mode; it never captures or
    /// replaces it, so a background transition arriving while the popup is open is
    /// exactly what the operator sees once it closes.
    pub fn show_qr_popup(&mut self) {
        if self.web_url.is_some() {
            self.modal = Some(ModalState::QrPopup);
        }
    }

    /// Hide the QR popup, exposing the latest execution mode.
    pub fn hide_qr_popup(&mut self) {
        if matches!(self.modal, Some(ModalState::QrPopup)) {
            self.modal = None;
        }
    }

    /// True when any overlay — warning popup or modal — owns input.
    ///
    /// The warning popup is an independent diagnostic overlay with its own
    /// scrolling contract; both must suppress ordinary view commands.
    pub fn has_overlay(&self) -> bool {
        self.warning_popup.is_some() || self.modal.is_some()
    }

    /// Fresh observation the active modal's validity is judged against.
    fn modal_validity_context(&self) -> modal_logic::ModalValidityContext<'_> {
        modal_logic::ModalValidityContext {
            execution_mode: self.execution_mode,
            web_url: self.web_url.as_deref(),
            worktrees: &self.worktrees,
            changes: &self.changes,
            deleting_worktree_paths: &self.deleting_worktree_paths,
        }
    }

    /// Re-evaluate the active modal against current state.
    ///
    /// Clearing the modal clears its identity payload with it, because the payload
    /// lives inside the variant. Execution state is never touched here: an overlay
    /// losing its target must not rewrite the lifecycle underneath it.
    ///
    /// Returns the reason when a modal was invalidated.
    pub(crate) fn revalidate_modal(&mut self) -> Option<modal_logic::ModalInvalidation> {
        let modal = self.modal.as_ref()?;
        let invalidation = modal_logic::evaluate(modal, &self.modal_validity_context()).err()?;
        self.modal = None;
        Some(invalidation)
    }

    /// Clear the active modal and report the invalidation reason to the operator.
    fn invalidate_modal_with_report(
        &mut self,
        invalidation: modal_logic::ModalInvalidation,
        action: &str,
    ) {
        self.modal = None;
        let message = format!("{} canceled: {}", action, invalidation.reason());
        self.warning_message = Some(message.clone());
        self.add_log(LogEntry::warn(message));
    }

    /// Move cursor up
    pub fn cursor_up(&mut self) {
        if self.changes.is_empty() {
            return;
        }
        let previous_filter_target = self.captured_selected_proposal_log_filter_target();
        self.cursor_index = if self.cursor_index == 0 {
            self.changes.len() - 1
        } else {
            self.cursor_index - 1
        };
        self.list_state.select(Some(self.cursor_index));
        self.sync_selected_proposal_log_filter_after_cursor_move(previous_filter_target.as_deref());
    }

    /// Move cursor down
    pub fn cursor_down(&mut self) {
        if self.changes.is_empty() {
            return;
        }
        let previous_filter_target = self.captured_selected_proposal_log_filter_target();
        self.cursor_index = (self.cursor_index + 1) % self.changes.len();
        self.list_state.select(Some(self.cursor_index));
        self.sync_selected_proposal_log_filter_after_cursor_move(previous_filter_target.as_deref());
    }

    /// Move worktree cursor up
    pub fn worktree_cursor_up(&mut self) {
        let Some(next_index) = worktree_logic::previous_worktree_cursor_index(
            self.worktree_cursor_index,
            self.worktrees.len(),
        ) else {
            return;
        };

        self.worktree_cursor_index = next_index;
        self.worktree_list_state
            .select(Some(self.worktree_cursor_index));
    }

    /// Move worktree cursor down
    pub fn worktree_cursor_down(&mut self) {
        let Some(next_index) = worktree_logic::next_worktree_cursor_index(
            self.worktree_cursor_index,
            self.worktrees.len(),
        ) else {
            return;
        };

        self.worktree_cursor_index = next_index;
        self.worktree_list_state
            .select(Some(self.worktree_cursor_index));
    }

    /// Get the selected worktree path (if any)
    pub fn get_selected_worktree_path(&self) -> Option<String> {
        if self.worktree_cursor_index < self.worktrees.len() {
            Some(
                self.worktrees[self.worktree_cursor_index]
                    .path
                    .display()
                    .to_string(),
            )
        } else {
            None
        }
    }

    /// Get the selected worktree (if any)
    pub fn get_selected_worktree(&self) -> Option<&WorktreeInfo> {
        if self.worktree_cursor_index < self.worktrees.len() {
            Some(&self.worktrees[self.worktree_cursor_index])
        } else {
            None
        }
    }

    /// Mark a worktree as having an accepted delete request in progress.
    pub fn mark_worktree_deleting(&mut self, path: impl Into<PathBuf>) {
        self.deleting_worktree_paths.insert(path.into());
    }

    /// Clear the transient delete-in-progress marker for a worktree.
    pub fn clear_worktree_deleting(&mut self, path: &PathBuf) {
        self.deleting_worktree_paths.remove(path);
    }

    /// Return whether a worktree path is currently marked deleting.
    pub fn is_worktree_deleting(&self, path: &PathBuf) -> bool {
        self.deleting_worktree_paths.contains(path)
    }

    /// Return a display label for the first visible deleting worktree, if any.
    pub fn deleting_worktree_status_label(&self) -> Option<String> {
        self.worktrees
            .iter()
            .find(|worktree| self.is_worktree_deleting(&worktree.path))
            .map(|worktree| worktree.display_label())
            .or_else(|| {
                self.deleting_worktree_paths
                    .iter()
                    .next()
                    .map(|path| path.display().to_string())
            })
    }

    fn selected_worktree_is_deleting(&self) -> bool {
        self.get_selected_worktree()
            .is_some_and(|worktree| self.is_worktree_deleting(&worktree.path))
    }

    fn block_selected_deleting_worktree_action(&mut self) -> bool {
        if self.selected_worktree_is_deleting() {
            self.warning_message = Some("Worktree is already being deleted".to_string());
            true
        } else {
            false
        }
    }

    /// Return true if the selected worktree is deleting and the caller should suppress its action.
    pub fn suppress_if_selected_worktree_deleting(&mut self) -> bool {
        self.block_selected_deleting_worktree_action()
    }

    /// Request worktree delete with validation
    ///
    /// Returns Some(TuiCommand) if deletion should proceed, None if it should be blocked
    pub fn request_worktree_delete_from_list(&mut self) -> Option<TuiCommand> {
        if self.block_selected_deleting_worktree_action() {
            return None;
        }

        match worktree_action_logic::validate_delete_request(
            &self.worktrees,
            self.worktree_cursor_index,
            &self.changes,
        ) {
            Ok((path, branch)) => {
                // Opening a confirmation is advisory. The identity that will be
                // revalidated at confirmation time is captured here, inside the
                // modal variant, so it cannot drift away from the modal itself.
                self.modal = Some(ModalState::ConfirmWorktreeDelete { path, branch });
                None
            }
            Err(msg) => {
                self.warning_message = Some(msg);
                None
            }
        }
    }

    /// Confirm and execute pending worktree action.
    pub fn confirm_worktree_action_delete(&mut self) -> Option<TuiCommand> {
        self.confirm_worktree_action_delete_with_options(false)
    }

    /// Confirm and execute pending worktree deletion with explicit teardown behavior.
    ///
    /// The confirmation is re-checked against a fresh worktree observation before
    /// anything is mutated: a stale identity refuses the command and leaves the
    /// worktree untouched rather than deleting whatever now occupies the path.
    ///
    /// Neither `Y` (`skip_teardown = false`) nor `S` (`skip_teardown = true`)
    /// grants permission to discard uncommitted work. A known-dirty target
    /// refuses in the shared service and comes back as an escalation into
    /// [`Self::open_dirty_discard_confirmation`].
    pub fn confirm_worktree_action_delete_with_options(
        &mut self,
        skip_teardown: bool,
    ) -> Option<TuiCommand> {
        let Some(ModalState::ConfirmWorktreeDelete { path, branch }) = self.modal.clone() else {
            return None;
        };

        if let Err(invalidation) =
            modal_logic::evaluate_worktree_delete(&path, &branch, &self.modal_validity_context())
        {
            self.invalidate_modal_with_report(invalidation, "Worktree delete");
            return None;
        }

        self.modal = None;
        self.mark_worktree_deleting(path.clone());
        let teardown_note = if skip_teardown {
            " with skip-teardown"
        } else {
            ""
        };
        self.add_log(LogEntry::info(format!(
            "Deleting worktree{}: {}",
            teardown_note,
            path.display()
        )));

        Some(TuiCommand::DeleteWorktree(DeleteIntent::ordinary(
            path,
            branch,
            skip_teardown,
        )))
    }

    /// Escalate the shared service's fresh known-dirty refusal into a second,
    /// explicitly destructive confirmation.
    ///
    /// The target comes from the service's own observation, taken under its
    /// mutation guard. Nothing here is read from `worktrees`, which carries no
    /// dirty state and would be a stale answer if it did.
    pub fn open_dirty_discard_confirmation(
        &mut self,
        target: &crate::worktree_ops::service::DirtyTarget,
        skip_teardown: bool,
    ) {
        self.modal = Some(ModalState::ConfirmDirtyDiscard {
            path: target.path.clone(),
            identity: target.identity.clone(),
            branch: target.branch.clone(),
            head: target.head.clone(),
            skip_teardown,
        });
        self.add_log(LogEntry::warn(format!(
            "Worktree has uncommitted changes: {} (press X to discard them and delete)",
            target.path.display()
        )));
    }

    /// Grant known-dirty discard for the pending destructive confirmation.
    ///
    /// This is reachable only from the uppercase `X` keypress. It re-checks the
    /// confirmation against the latest observation first, so a target that became
    /// active, was re-branded, moved its HEAD, or entered another delete between
    /// the escalation and the keypress refuses instead of being discarded.
    pub fn confirm_dirty_discard(&mut self) -> Option<TuiCommand> {
        let Some(ModalState::ConfirmDirtyDiscard {
            path,
            identity,
            branch,
            head,
            skip_teardown,
        }) = self.modal.clone()
        else {
            return None;
        };

        if let Err(invalidation) =
            modal_logic::evaluate_discard(&path, &branch, &head, &self.modal_validity_context())
        {
            self.invalidate_modal_with_report(invalidation, "Dirty worktree discard");
            return None;
        }

        self.modal = None;
        self.mark_worktree_deleting(path.clone());
        let teardown_note = if skip_teardown {
            " without teardown"
        } else {
            ""
        };
        self.add_log(LogEntry::warn(format!(
            "Discarding uncommitted changes and deleting worktree{}: {}",
            teardown_note,
            path.display()
        )));

        Some(TuiCommand::DeleteWorktree(DeleteIntent {
            path,
            branch,
            identity: Some(identity),
            head: Some(head),
            skip_teardown,
            allow_known_dirty: true,
            allow_commits_ahead: false,
        }))
    }

    /// Escalate the shared service's fresh commits-ahead refusal into a
    /// dedicated destructive confirmation.
    ///
    /// Same rule as [`Self::open_dirty_discard_confirmation`]: every field is the
    /// service's own observation. The worktree list does carry a
    /// `has_commits_ahead` flag, but it is a projection with no identity, no
    /// HEAD, and no dirty state, and it is not what the branch will be deleted
    /// at.
    pub fn open_ahead_discard_confirmation(
        &mut self,
        target: &crate::worktree_ops::service::AheadTarget,
        skip_teardown: bool,
    ) {
        self.modal = Some(ModalState::ConfirmAheadDiscard {
            path: target.path.clone(),
            identity: target.identity.clone(),
            branch: target.branch.clone(),
            head: target.head.clone(),
            dirty: target.dirty,
            skip_teardown,
        });
        let dirty_note = if target.dirty {
            " and uncommitted changes"
        } else {
            ""
        };
        self.add_log(LogEntry::warn(format!(
            "Worktree has unmerged commits{}: {} (press X to delete the worktree and branch '{}')",
            dirty_note,
            target.path.display(),
            target.branch
        )));
    }

    /// Grant commits-ahead discard for the pending destructive confirmation.
    ///
    /// Reachable only from the uppercase `X` keypress on the ahead confirmation.
    /// The dirty permission travels with it exactly when the confirmation
    /// disclosed uncommitted changes, so the one keypress never authorizes a
    /// loss the operator was not shown.
    pub fn confirm_ahead_discard(&mut self) -> Option<TuiCommand> {
        let Some(ModalState::ConfirmAheadDiscard {
            path,
            identity,
            branch,
            head,
            dirty,
            skip_teardown,
        }) = self.modal.clone()
        else {
            return None;
        };

        if let Err(invalidation) =
            modal_logic::evaluate_discard(&path, &branch, &head, &self.modal_validity_context())
        {
            self.invalidate_modal_with_report(invalidation, "Ahead worktree discard");
            return None;
        }

        self.modal = None;
        self.mark_worktree_deleting(path.clone());
        let teardown_note = if skip_teardown {
            " without teardown"
        } else {
            ""
        };
        let dirty_note = if dirty {
            " and uncommitted changes"
        } else {
            ""
        };
        self.add_log(LogEntry::warn(format!(
            "Discarding unmerged commits{} and deleting worktree{} with branch '{}': {}",
            dirty_note,
            teardown_note,
            branch,
            path.display()
        )));

        Some(TuiCommand::DeleteWorktree(DeleteIntent {
            path,
            branch,
            identity: Some(identity),
            head: Some(head),
            skip_teardown,
            allow_known_dirty: dirty,
            allow_commits_ahead: true,
        }))
    }

    /// Cancel pending worktree action.
    ///
    /// Only the overlay is dismissed; the execution mode underneath is whatever the
    /// latest lifecycle event left it as. Cancelling a destructive confirmation
    /// retains the worktree, everything uncommitted in it, and its branch.
    pub fn cancel_worktree_action(&mut self) {
        if matches!(
            self.modal,
            Some(
                ModalState::ConfirmWorktreeDelete { .. }
                    | ModalState::ConfirmDirtyDiscard { .. }
                    | ModalState::ConfirmAheadDiscard { .. }
            )
        ) {
            self.modal = None;
        }
    }

    /// Open the force-kill confirmation for the change under the cursor.
    ///
    /// Returns true when the confirmation was opened. Opening is advisory: the
    /// shared operator command service still revalidates before terminating.
    pub fn request_force_kill_confirmation(&mut self) -> bool {
        if self.view_mode != ViewMode::Changes
            || !matches!(self.execution_mode, AppExecutionMode::Running)
            || self.cursor_index >= self.changes.len()
        {
            return false;
        }

        let change = &self.changes[self.cursor_index];
        if !crate::orchestration::operator_command::is_active_status(&change.display_status_cache) {
            return false;
        }

        let change_id = change.id.clone();
        self.modal = Some(ModalState::ConfirmForceKill {
            change_id: change_id.clone(),
        });
        self.add_log(LogEntry::warn(format!(
            "Confirm force-kill for '{}': press Y to confirm, N/Esc to cancel",
            change_id
        )));
        true
    }

    /// Confirm the pending force-kill, dispatching through the shared service.
    ///
    /// The TUI display cache can only refuse; it never authorizes. A surviving but
    /// stale target is refused here, and everything that survives this check is
    /// still revalidated by `OperatorCommandService::stop_and_dequeue`, which owns
    /// cancellation, termination evidence, and the timeout path.
    pub fn confirm_force_kill(&mut self) -> Option<TuiCommand> {
        let Some(ModalState::ConfirmForceKill { change_id }) = self.modal.clone() else {
            return None;
        };

        if let Err(invalidation) =
            modal_logic::evaluate_force_kill(&change_id, &self.modal_validity_context())
        {
            self.invalidate_modal_with_report(invalidation, "Force-kill");
            return None;
        }

        self.modal = None;
        self.add_log(LogEntry::info(format!(
            "Force-kill confirmed: {}",
            change_id
        )));
        Some(TuiCommand::DequeueChange(change_id))
    }

    /// Cancel the pending force-kill without touching execution state.
    pub fn cancel_force_kill(&mut self) {
        if matches!(self.modal, Some(ModalState::ConfirmForceKill { .. })) {
            self.modal = None;
            self.add_log(LogEntry::info("Force-kill canceled".to_string()));
        }
    }

    /// Dismiss the focused `merged` row immediately, with no confirmation.
    ///
    /// Presentation only: it hides a reviewed row from this process's Changes
    /// projection and records nothing outside it. Returns true when a row was
    /// dismissed; a non-`merged` focused row is a silent no-op.
    pub fn dismiss_merged_row(&mut self) -> bool {
        merged_row_dismissal::dismiss_focused(self)
    }

    /// Dismiss every projected `merged` row immediately, with no confirmation.
    ///
    /// Returns true when at least one row was dismissed; an empty target set is
    /// a silent no-op.
    pub fn dismiss_all_merged_rows(&mut self) -> bool {
        merged_row_dismissal::dismiss_all_projected(self)
    }

    /// Whether the focused row can be dismissed right now.
    ///
    /// Drives the `d: dismiss` hint, so the key is never advertised for a row it
    /// would do nothing to.
    pub fn focused_row_is_dismissable(&self) -> bool {
        merged_row_dismissal::focused_row_is_dismissable(self)
    }

    /// Whether the current Changes-list projection holds a dismissable row.
    ///
    /// Scroll position is deliberately not part of it: the bulk hint and the
    /// bulk action target the same projection.
    pub fn has_dismissable_merged_rows(&self) -> bool {
        merged_row_dismissal::has_dismissable_rows(self)
    }

    /// Rows this process has dismissed, as the catalog boundary sees them.
    ///
    /// Assertion helper only — production code reads the field directly, so this
    /// accessor exists purely so tests can observe suppression without reaching
    /// into private state. Nothing outside this process reads it, and it is
    /// discarded on restart.
    #[cfg(test)]
    pub(crate) fn dismissed_merged_ids(&self) -> &HashSet<String> {
        &self.dismissed_merged_ids
    }

    /// Request to merge worktree branch into base branch.
    ///
    /// Returns Some(TuiCommand) if merge should proceed, None if blocked.
    pub fn request_merge_worktree_branch(&mut self) -> Option<TuiCommand> {
        worktree_action_logic::request_merge_worktree_branch(self)
    }

    /// Toggle the cursor row's execution mark.
    ///
    /// Available for every visible non-terminal row in every execution mode. It
    /// writes only process-local next-run intent: no queue mutation, no stop,
    /// no retry, no display-status transition. Terminal rows are silent no-ops.
    pub fn toggle_selection(&mut self) {
        selection_logic::toggle_selection(self)
    }

    fn can_bulk_toggle_change(&self, change: &ChangeState) -> bool {
        selection_logic::can_bulk_toggle_change(change)
    }

    /// Returns true when at least one change can be targeted by bulk toggle.
    ///
    /// Mirrors the admission `toggle_all_marks` enforces — Changes view, no
    /// overlay owning input, and at least one visible non-terminal row — so the
    /// `x` hint is never offered for a key that would do nothing. Execution mode
    /// is deliberately not part of it.
    pub fn has_bulk_toggle_targets(&self) -> bool {
        self.view_mode == ViewMode::Changes
            && !self.has_overlay()
            && self
                .changes
                .iter()
                .any(|change| self.can_bulk_toggle_change(change))
    }

    /// Apply one derived execution-mark state to every visible non-terminal row.
    ///
    /// If any target row is unmarked, mark them all; otherwise unmark them all.
    /// Available in every execution mode, and mark-only: work already admitted
    /// to the current run is never queued, dequeued, stopped, or retried by it.
    /// Terminal rows are excluded without a refusal warning.
    pub fn toggle_all_marks(&mut self) -> Vec<TuiCommand> {
        selection_logic::toggle_all_marks(self)
    }

    /// Trigger merge resolution for the change under the cursor when applicable.
    ///
    /// This is presentation only. Whether the change becomes the active resolver
    /// or waits in FIFO order, whether the reducer still accepts the intent, and
    /// whether the scheduler is started or woken are all decided by the shared
    /// run-control service when the emitted command is handled, so an `M`
    /// keypress and a remote `resolve_merge` cannot reach different conclusions.
    pub fn resolve_merge(&mut self) -> Option<TuiCommand> {
        // Must have valid cursor position
        if self.changes.is_empty() || self.cursor_index >= self.changes.len() {
            return None;
        }

        // Must be in correct mode
        if !matches!(
            self.execution_mode,
            AppExecutionMode::Select | AppExecutionMode::Stopped | AppExecutionMode::Running
        ) {
            return None;
        }

        // Check current change status and get change_id
        let change = &self.changes[self.cursor_index];
        if !matches!(change.display_status_cache.as_str(), "merge wait") {
            return None;
        }

        Some(TuiCommand::ResolveMerge(change.id.clone()))
    }

    /// Add a change to the resolve queue (with duplicate prevention).
    ///
    /// Returns true if the change was added, false if it was already reserved.
    pub fn add_to_resolve_queue(&mut self, change_id: &str) -> bool {
        self.resolve_reservations.reserve(change_id).is_some()
    }

    /// Remove one specific change from the resolve queue.
    ///
    /// Used when reducer-owned retry intent for that change is gone (for example a
    /// manual `MergeDeferred(auto_resumable=false)`), so stale queue membership
    /// cannot outlive it. FIFO order of unrelated entries is preserved.
    ///
    /// Returns true if the change was queued and has been removed.
    pub fn remove_from_resolve_queue(&mut self, change_id: &str) -> bool {
        self.resolve_reservations.cancel(change_id)
    }

    /// Release the active resolver and take the next change from the queue.
    ///
    /// Returns the promoted change ID if one was waiting, otherwise None.
    pub fn pop_from_resolve_queue(&mut self) -> Option<String> {
        self.resolve_reservations.finish_active()
    }

    /// Changes currently waiting behind the active resolver, in FIFO order.
    ///
    /// Assertion helper only: production reads the ledger through
    /// [`AppState::has_queued_resolves`] or the shared run-control service.
    #[cfg(test)]
    pub fn queued_resolves(&self) -> Vec<String> {
        self.resolve_reservations.waiting()
    }

    /// Check if there are queued resolves waiting.
    pub fn has_queued_resolves(&self) -> bool {
        self.resolve_reservations.has_waiting()
    }

    /// Update parallel eligibility status for changes.
    ///
    /// A change is eligible for parallel execution if:
    /// 1. It exists in HEAD's commit tree (committed_change_ids), AND
    /// 2. It has no uncommitted or untracked files under openspec/changes/<change_id>/
    ///
    /// Both failures keep the change out of parallel queueing; they are recorded
    /// as distinct reasons so rendering and refusal messages can stay truthful
    /// about which one was actually observed.
    pub fn apply_parallel_eligibility(
        &mut self,
        committed_change_ids: &HashSet<String>,
        uncommitted_file_change_ids: &HashSet<String>,
    ) {
        for change in &mut self.changes {
            change.parallel_eligibility = ParallelEligibility::observe(
                &change.id,
                committed_change_ids,
                uncommitted_file_change_ids,
            );
        }

        if matches!(
            self.execution_mode,
            AppExecutionMode::Select | AppExecutionMode::Stopped
        ) {
            self.clear_parallel_ineligible_intent();
        }

        // A change that just became ineligible must reach the shared start
        // guard at the same observation, not one refresh later.
        self.publish_parallel_runtime();
    }

    /// Update worktree presence flags for changes.
    pub fn apply_worktree_status(&mut self, worktree_change_ids: &HashSet<String>) {
        for change in &mut self.changes {
            let sanitized = change.id.replace(['/', '\\', ' '], "-");
            change.has_worktree = worktree_change_ids.contains(&sanitized);
        }
    }

    /// Sync the Apply-lane operation label from the reducer.
    ///
    /// The commit subphase already arrives as an event, so this is a
    /// self-healing refresh rather than the only writer: a frontend that missed
    /// one event still converges on the reducer's view instead of rendering
    /// `[commit]` forever. It cannot change any row's status, color, or
    /// lifecycle — only which word the Apply lane prints.
    pub fn apply_operation_labels_from_reducer(
        &mut self,
        operation_map: &HashMap<String, &'static str>,
    ) {
        for change in &mut self.changes {
            if let Some(&label) = operation_map.get(&change.id) {
                change.apply_operation_cache = label.to_string();
            }
        }
    }

    /// Sync the reducer's archive-completion snapshot into the row cache.
    ///
    /// Taken from the same reducer read as the display statuses so a row's status
    /// and its archive milestone always describe one instant. The snapshot is
    /// retained so refresh reconstruction can reapply it — see
    /// [`AppState::reapply_reducer_archive_completion`].
    ///
    /// Nothing is inferred from the status string here: this is only the reducer's
    /// own record, projected onto the rows that carry it.
    pub fn apply_archived_changes_from_reducer(&mut self, archived: &HashSet<String>) {
        self.reducer_archived_changes = archived.clone();
        self.reapply_reducer_archive_completion();
    }

    /// Reapply the retained archive-completion snapshot to the current rows.
    ///
    /// Catalog refresh rebuilds and re-adds rows; without this the reconstructed
    /// row would render an empty `[ ]` for a change the reducer already archived,
    /// which is exactly the one-frame checkbox flash post-archive rows must never
    /// show.
    pub(crate) fn reapply_reducer_archive_completion(&mut self) {
        for change in &mut self.changes {
            change.archive_complete_cache = self.reducer_archived_changes.contains(&change.id);
        }
    }

    /// Changes the reducer has recorded as archive-complete, as this TUI sees them.
    ///
    /// Assertion helper only: production reads the per-row cache.
    #[cfg(test)]
    pub(crate) fn reducer_archived_changes(&self) -> &HashSet<String> {
        &self.reducer_archived_changes
    }

    /// Sync displayed status caches from the reducer's display status snapshot.
    ///
    /// This is Phase 6.1: TUI derives displayed change status from the shared
    /// orchestration reducer state instead of maintaining an independent lifecycle copy.
    /// Only transitions that are safe (no active execution regression) are applied.
    pub fn apply_display_statuses_from_reducer(
        &mut self,
        display_map: &HashMap<String, &'static str>,
    ) {
        self.reducer_display_status_snapshot = display_map.clone();

        for change in &mut self.changes {
            if change.display_status_cache == "rejected"
                && !matches!(display_map.get(&change.id).copied(), Some("rejected"))
            {
                // rejected rows are display-only and remain immutable until marker removal.
                continue;
            }

            // Reducer `queued` is queue presentation, not an execution mark.
            // Amplifying it into `selected = true` here used to invent operator
            // intent the shared store never recorded, which is exactly the drift
            // `/api/v2` would then report as `execution_marked` for a change no
            // one marked.
            if let Some(&status_str) = display_map.get(&change.id) {
                let normalized = match status_str {
                    "stopped" => "not queued",
                    other => other,
                };

                if normalized == "error" {
                    if change.display_status_cache == "error" {
                        continue;
                    }
                    // The diagnostic itself is never invented here. It arrives
                    // from the reducer through
                    // [`AppState::apply_error_details_from_reducer`], so an
                    // operator sees the retained failure text or the explicit
                    // "unavailable" fallback — never a placeholder token.
                    change.set_display_status_cache("error");
                } else {
                    change.set_display_status_cache(normalized);
                }
            }
        }

        self.prune_stale_error_details_popup();
    }

    /// Close an Error Details popup whose change has left `error`.
    ///
    /// A retry is the common case: once the row is queued again, the popup would
    /// otherwise keep presenting a diagnostic that no longer describes the
    /// change's current state.
    fn prune_stale_error_details_popup(&mut self) {
        let Some(popup) = self.error_details_popup.as_ref() else {
            return;
        };

        let still_failed = self
            .changes
            .iter()
            .any(|change| change.id == popup.change_id && change.display_status_cache == "error");
        if !still_failed {
            self.error_details_popup = None;
        }
    }

    /// Sync retained final diagnostics for error rows from the reducer.
    ///
    /// Presentation only. The diagnostic is what the operator reads in the row
    /// preview and the Error Details popup; it never becomes scheduling, retry,
    /// acceptance, archive, or merge input.
    ///
    /// It is kept independent of the bounded log buffer on purpose: a change can
    /// stay in `error` long after the failure log entry has been evicted, so the
    /// row must be able to explain itself without any retained `LogEntry`.
    ///
    /// The reducer's diagnostic wins over whatever the row already cached. A row
    /// can reach `error` carrying an unrelated compatibility reason (a skipped
    /// dependency, for example), and that stale non-error text must not survive
    /// as the operator-facing failure reason. Rows the reducer does not report as
    /// failed are left alone: `set_display_status_cache` already drops the cache
    /// when a row transitions away from `error`.
    pub fn apply_error_details_from_reducer(&mut self, error_details: &HashMap<String, String>) {
        for change in &mut self.changes {
            if change.display_status_cache != "error" {
                continue;
            }
            if let Some(detail) = error_details.get(&change.id) {
                change.error_message_cache = Some(detail.clone());
            }
        }
    }

    /// Sync blocker views from the reducer.
    ///
    /// Kept separate from the display-status sync so a row's `blocked` versus
    /// `stalled` word and its blocker kind always come from the same reducer
    /// snapshot instead of being inferred independently here.
    pub fn apply_blocker_views_from_reducer(
        &mut self,
        blocker_views: &HashMap<String, crate::orchestration::state::BlockerView>,
    ) {
        for change in &mut self.changes {
            change.set_blocker_view(blocker_views.get(&change.id));
        }
    }

    /// Get the number of selected changes
    pub fn selected_count(&self) -> usize {
        self.changes.iter().filter(|c| c.selected).count()
    }
}

// ============================================================================
// Mode-related Methods
// ============================================================================

impl AppState {
    /// Reset stop/cancel state before a new run
    pub fn reset_for_run(&mut self) {
        self.stop_mode = StopMode::None;
        self.current_change = None;
        self.error_change_id = None;
        self.orchestration_started_at = Some(Instant::now());
        self.orchestration_elapsed = None;
        self.reset_analysis_log_dedupe();
    }

    pub(crate) fn reset_analysis_log_dedupe(&mut self) {
        self.diagnostic_dedup.reset_matching(|key| {
            matches!(key, DiagnosticDeduplicationKey::TuiAnalysisStarted { .. })
        });
    }

    /// Project this frontend's lifecycle mode onto the shared operator vocabulary.
    ///
    /// Modal popups live on a separate axis, so there is nothing to see through
    /// here: the execution mode is already the only thing the shared lifecycle
    /// matrix must see, and a popup can neither widen nor narrow it.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn operator_mode(&self) -> crate::orchestration::operator_command::OperatorMode {
        self.execution_mode.operator_mode()
    }

    /// Adopt the Core process lifecycle mode.
    ///
    /// One direction only, and this is the direction. `execution_mode` used to
    /// be command-admission authority as well as presentation, which is how the
    /// live TUI and the `/api/v2` `app_mode` could describe the same process
    /// differently after an accepted command. Core owns admission now; this
    /// frontend renders it.
    pub fn adopt_core_mode(&mut self, mode: crate::orchestration::operator_command::OperatorMode) {
        self.execution_mode = AppExecutionMode::from_operator_mode(mode);
    }

    /// Project an accepted run dispatch onto TUI presentation state.
    ///
    /// The shared service already decided the targets and applied the reducer
    /// intent; this only refreshes the row cache and the run-scoped UI state so
    /// the screen matches what was actually dispatched.
    pub fn begin_run(&mut self, change_ids: &[String]) {
        self.admit_run_targets(change_ids);
        self.execution_mode = AppExecutionMode::Running;
    }

    /// Project an accepted Start that only *woke* a live scheduler.
    ///
    /// The queue intent is real and the rows are queued, but nothing has been
    /// admitted for execution yet: `SchedulerEffect::Notified` means the
    /// scheduler was notified, not that it started anything. Claiming Running
    /// here would make a Start against a persistent-idle scheduler report
    /// execution the operator cannot see, so the execution axis is left for the
    /// first typed work-start event to move.
    pub fn queue_run(&mut self, change_ids: &[String]) {
        self.admit_run_targets(change_ids);
    }

    /// Row cache and run-scoped presentation shared by both Start projections.
    ///
    /// The run-scoped reset belongs to a dispatch that *opens* a run. A Start
    /// accepted while the process is already Running — the change-local error
    /// retry — adds a target to the run in progress, so clearing the current
    /// change and restarting the elapsed timer there would erase unrelated live
    /// work's presentation on behalf of a command that never touched it.
    fn admit_run_targets(&mut self, change_ids: &[String]) {
        for change in &mut self.changes {
            if change_ids.iter().any(|id| id == &change.id) {
                change.set_display_status_cache("queued");
            }
        }
        if self.execution_mode != AppExecutionMode::Running {
            self.reset_for_run();
        }
        // The service resolved these targets *from* the shared marks, so the row
        // projection is read back from the store rather than written into it.
        self.sync_execution_marks_from_store();
    }
}

// ============================================================================
// Log Management
// ============================================================================

impl AppState {
    /// Get the latest log entry for a specific change_id
    ///
    /// Returns the most recent log entry that matches the given change_id.
    /// Used for displaying log previews in the change list.
    ///
    /// In remote mode, change IDs have the form `"<project_id>::<project_name>/<change_id>"`.
    /// Log entries from the remote server may have `change_id` set to the bare `project_id`
    /// (when no specific change is known). This method also matches those project-level logs
    /// by checking if the `change_id` argument starts with `"<entry.change_id>::"`.
    pub fn get_latest_log_for_change(&self, change_id: &str) -> Option<&LogEntry> {
        self.logs.iter().rev().find(|entry| {
            if let Some(entry_cid) = entry.change_id.as_deref() {
                // Exact match (local mode and remote mode with full change_id)
                if entry_cid == change_id {
                    return true;
                }
                // Project-level log match: entry has project_id, change_id starts with that project_id
                // Remote change IDs have the form "<project_id>::<project_name>/<change_id>"
                // Remote logs with only project_id set as change_id will match via this prefix check.
                let prefix = format!("{}::", entry_cid);
                if change_id.starts_with(&prefix) {
                    return true;
                }
            }
            false
        })
    }

    /// Add a log entry
    pub fn add_log(&mut self, entry: LogEntry) {
        // Send to tracing for debug file output (always enabled)
        // Include change_id, operation, iteration, and workspace_path in tracing output for context matching
        let change_id = entry.change_id.as_deref().unwrap_or("-");
        let operation = entry.operation.as_deref().unwrap_or("-");
        let iteration = entry.iteration.unwrap_or(0);
        let workspace_path = entry.workspace_path.as_deref().unwrap_or("-");

        match entry.level {
            LogLevel::Info | LogLevel::Success => {
                info!(
                    target: "tui_log",
                    change_id = change_id,
                    operation = operation,
                    iteration = iteration,
                    workspace_path = workspace_path,
                    "{}",
                    entry.message
                );
            }
            LogLevel::Warn => {
                warn!(
                    target: "tui_log",
                    change_id = change_id,
                    operation = operation,
                    iteration = iteration,
                    workspace_path = workspace_path,
                    "{}",
                    entry.message
                );
            }
            LogLevel::Error => {
                error!(
                    target: "tui_log",
                    change_id = change_id,
                    operation = operation,
                    iteration = iteration,
                    workspace_path = workspace_path,
                    "{}",
                    entry.message
                );
            }
        }

        self.logs.push(entry);

        // Handle buffer trimming when exceeding max entries. The sequence base
        // moves with the evicted entry so surviving anchors keep their identity.
        if log_logic::apply_log_buffer_limit(self.logs.len(), MAX_LOG_ENTRIES) {
            self.logs.remove(0);
            self.log_seq_base = self.log_seq_base.saturating_add(1);
        }

        // The anchor is stored in source coordinates, so an append or a trim
        // needs no adjustment here: the next projection re-derives the top line
        // from the current wrapped sequence, and auto-scroll (`log_anchor ==
        // None`) keeps following the newest line.
    }

    /// Record the Logs-panel geometry the renderer just used.
    ///
    /// Navigation needs the same width the renderer wrapped with, otherwise the
    /// display-line indices the two compute would disagree.
    pub(crate) fn set_log_viewport(&mut self, width: usize, height: usize) {
        self.log_viewport = log_logic::LogViewport { width, height };
    }

    /// Visible entries paired with their process-local sequence numbers.
    pub(crate) fn visible_log_entries(&self) -> Vec<(u64, &LogEntry)> {
        self.logs
            .iter()
            .enumerate()
            .filter(|(_, entry)| self.log_entry_visible_for_selected_proposal_filter(entry))
            .map(|(index, entry)| (self.log_seq_base + index as u64, entry))
            .collect()
    }

    /// Current wrapped display-line sequence for the Logs panel.
    pub(crate) fn log_display_lines(&self) -> Vec<log_logic::LogDisplayLine> {
        log_logic::build_log_display_lines(&self.visible_log_entries(), self.log_viewport.width)
    }

    /// Index of the top visible display line under the current anchor.
    pub(crate) fn log_start_line(&self, lines: &[log_logic::LogDisplayLine]) -> usize {
        log_logic::resolve_start_line(lines, self.log_anchor, self.log_viewport.visible_height())
    }

    /// Scroll logs up by a page of display lines (show older content).
    ///
    /// A page is measured in display lines, so a single entry taller than the
    /// viewport is traversed line by line instead of being skipped whole.
    pub fn scroll_logs_up(&mut self, page_size: usize) {
        let lines = self.log_display_lines();
        let start = self.log_start_line(&lines);
        let next = start.saturating_sub(page_size.max(1));
        self.log_anchor = log_logic::anchor_at_line(&lines, next);
        // Disable auto-scroll when user scrolls up
        self.log_auto_scroll = false;
    }

    /// Scroll logs down by a page of display lines (show newer content).
    pub fn scroll_logs_down(&mut self, page_size: usize) {
        let lines = self.log_display_lines();
        let max_start = lines
            .len()
            .saturating_sub(self.log_viewport.visible_height());
        let start = self.log_start_line(&lines);
        let next = start.saturating_add(page_size.max(1));

        // Re-enable auto-scroll once the newest line is back in view.
        if next >= max_start {
            self.scroll_logs_to_bottom();
        } else {
            self.log_anchor = log_logic::anchor_at_line(&lines, next);
            self.log_auto_scroll = false;
        }
    }

    /// Jump to the oldest display line (top of history)
    pub fn scroll_logs_to_top(&mut self) {
        let lines = self.log_display_lines();
        self.log_anchor = log_logic::anchor_at_line(&lines, 0);
        self.log_auto_scroll = false;
    }

    /// Jump to the newest display line (bottom) and re-enable auto-scroll
    pub fn scroll_logs_to_bottom(&mut self) {
        self.log_anchor = None;
        self.log_auto_scroll = true;
    }

    /// Toggle log panel visibility
    pub fn toggle_logs_panel(&mut self) {
        self.logs_panel_enabled = log_logic::toggle_logs_panel(self.logs_panel_enabled);
    }

    /// Proposal ID the selected-proposal log filter currently targets.
    ///
    /// Derived from the Changes cursor so no second copy of the target can drift
    /// out of sync. Returns `None` when the list is empty or the cursor is out of
    /// range.
    pub fn selected_proposal_log_filter_target(&self) -> Option<&str> {
        self.changes
            .get(self.cursor_index)
            .map(|change| change.id.as_str())
    }

    /// Toggle the presentation-only selected-proposal log filter.
    ///
    /// Filtering changes which entries are visible, so the current display-line
    /// anchor is no longer meaningful; return to the newest visible output with
    /// auto-scroll enabled. `AppState::logs` is never modified.
    pub fn toggle_selected_proposal_log_filter(&mut self) {
        self.selected_proposal_log_filter =
            log_logic::toggle_selected_proposal_log_filter(self.selected_proposal_log_filter);
        self.scroll_logs_to_bottom();
    }

    /// Whether a buffered entry is visible under the current filter state.
    pub fn log_entry_visible_for_selected_proposal_filter(&self, entry: &LogEntry) -> bool {
        log_logic::log_entry_matches_selected_proposal(
            self.selected_proposal_log_filter,
            entry.change_id.as_deref(),
            self.selected_proposal_log_filter_target(),
        )
    }

    /// Snapshot the filter target before a cursor move, only when it can matter.
    fn captured_selected_proposal_log_filter_target(&self) -> Option<String> {
        if self.selected_proposal_log_filter {
            self.selected_proposal_log_filter_target()
                .map(str::to_string)
        } else {
            None
        }
    }

    /// Reset the Logs panel position when a cursor move retargets an active filter.
    fn sync_selected_proposal_log_filter_after_cursor_move(
        &mut self,
        previous_target: Option<&str>,
    ) {
        if log_logic::should_reset_log_position_for_target_change(
            self.selected_proposal_log_filter,
            previous_target,
            self.selected_proposal_log_filter_target(),
        ) {
            self.scroll_logs_to_bottom();
        }
    }
}

// ============================================================================
// Event Handling
// ============================================================================

mod event_handlers;

// ============================================================================
// Helper Methods
// ============================================================================

impl AppState {
    /// Update changes from a refresh
    ///
    /// Updates task progress (completed_tasks, total_tasks) from fetched changes and
    /// enriches change metadata from shared orchestration state when available (apply counts,
    /// pending/archived tracking).
    ///
    /// IMPORTANT: This method does NOT modify display_status_cache. In Stopped mode, task completion
    /// does not trigger auto-queue. Changes are only queued through explicit user action (Space key).
    ///
    /// Note: Task progress is synchronized with shared orchestration state.
    /// When changes are fetched from openspec CLI, their task progress is written
    /// to OrchestratorState::task_progress(). When updating UI state, progress is
    /// read from shared state to ensure consistency across TUI and orchestrator.
    fn update_changes_with_rejected(
        &mut self,
        fetched_changes: Vec<Change>,
        rejected_changes: Vec<Change>,
    ) {
        processing_logic::update_changes_with_rejected(self, fetched_changes, rejected_changes);
    }

    #[cfg(test)]
    fn update_changes_with_rejected_for_test(
        &mut self,
        fetched_changes: Vec<Change>,
        rejected_changes: Vec<Change>,
    ) {
        self.update_changes_with_rejected(fetched_changes, rejected_changes);
    }
}
// Note: auto_clear_merge_wait() and apply_merge_wait_status() have been removed in Phase 5.3.
// Their logic is now handled by the shared reducer's apply_observation() path.
// The TUI syncs display_status_cache via apply_display_statuses_from_reducer() in the runner.

// ============================================================================
// Guard Logic
// ============================================================================

pub(crate) mod guards {
    use super::{ChangeState, ViewMode, WorktreeInfo};
    use crate::orchestration::operator_command::is_markable_status;

    /// Result type for merge validation
    pub enum MergeGuardResult {
        /// Merge is allowed
        Allowed,
        /// Merge is blocked with a warning message
        Blocked(String),
    }

    /// Validates that the view mode is correct for merge operations
    pub fn validate_view_mode(view_mode: ViewMode) -> MergeGuardResult {
        if view_mode != ViewMode::Worktrees {
            MergeGuardResult::Blocked("Switch to Worktrees view to merge".to_string())
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates that no resolve operation is in progress
    pub fn validate_not_resolving(is_resolving: bool) -> MergeGuardResult {
        if is_resolving {
            MergeGuardResult::Blocked("Cannot merge: resolve operation in progress".to_string())
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates that worktrees list is not empty
    pub fn validate_worktrees_not_empty(worktrees_len: usize) -> MergeGuardResult {
        if worktrees_len == 0 {
            MergeGuardResult::Blocked("No worktrees loaded".to_string())
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates that cursor index is within bounds
    pub fn validate_cursor_in_bounds(
        cursor_index: usize,
        worktrees_len: usize,
    ) -> MergeGuardResult {
        if cursor_index >= worktrees_len {
            MergeGuardResult::Blocked(format!(
                "Cursor out of range: {} >= {}",
                cursor_index, worktrees_len
            ))
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates worktree-specific constraints for merging
    pub fn validate_worktree_mergeable(worktree: &WorktreeInfo) -> MergeGuardResult {
        // Cannot merge main worktree
        if worktree.is_main {
            return MergeGuardResult::Blocked("Cannot merge main worktree".to_string());
        }

        // Cannot merge detached HEAD
        if worktree.is_detached {
            return MergeGuardResult::Blocked("Cannot merge detached HEAD".to_string());
        }

        // Branch name must not be empty
        if worktree.branch.is_empty() {
            return MergeGuardResult::Blocked("Cannot merge: no branch name".to_string());
        }

        // Cannot merge if already merging
        if worktree.is_merging {
            return MergeGuardResult::Blocked(
                "Cannot merge: merge already in progress".to_string(),
            );
        }

        // A row periodic refresh skipped carries no ahead/conflict evidence, so
        // there is nothing here to refuse *on*. Blocking it would make the
        // filtering permanently unmergeable; instead the request goes through
        // and the shared service decides from its own fresh targeted
        // observation of this exact worktree.
        if !worktree.inspection.is_inspected() {
            return MergeGuardResult::Allowed;
        }

        // Cannot merge if conflicts detected
        if worktree.has_merge_conflict() {
            return MergeGuardResult::Blocked(format!(
                "Cannot merge: {} conflict(s) detected",
                worktree.conflict_file_count()
            ));
        }

        // Cannot merge if no commits ahead of base branch
        if !worktree.has_commits_ahead {
            return MergeGuardResult::Blocked(
                "Cannot merge: no commits ahead of base branch".to_string(),
            );
        }

        MergeGuardResult::Allowed
    }

    /// Toggle the execution mark for one row, in every execution mode.
    ///
    /// A mark is process-local next-run target intent, so this touches
    /// `selected` and the NEW badge and nothing else: no queue command, no
    /// display-status transition, no retry or stop request. Terminal rows are
    /// filtered out by the caller and never reach here.
    ///
    /// Returns the operator-facing log line for the mutation.
    pub fn toggle_execution_mark(change: &mut ChangeState, new_change_count: &mut usize) -> String {
        change.selected = !change.selected;
        if change.is_new {
            change.is_new = false;
            *new_change_count = new_change_count.saturating_sub(1);
        }
        if change.selected {
            format!("Marked for execution: {}", change.id)
        } else {
            format!("Unmarked: {}", change.id)
        }
    }

    /// True when Space and bulk `x` may mutate this row's execution mark.
    ///
    /// Derived from the shared classifier alone, so the TUI cannot hold a second
    /// markability table. Worktree eligibility and Apply-limit evidence are not
    /// consulted: they decide whether a *run* may start, not whether an operator
    /// may express intent.
    ///
    /// The archive-completion evidence is supplied, not inferred: a row whose
    /// hidden checkbox says "no next run" must not still be toggleable, and a
    /// `resolving` row with no reducer archive record stays markable.
    pub fn is_mark_target(change: &ChangeState) -> bool {
        is_markable_status(&change.display_status_cache, change.archive_complete_cache)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::events::OrchestratorEvent;

    #[test]
    fn tui_config_defaults_and_configured_labels_are_available_in_app_state() {
        let mut app = AppState::new(vec![]);
        assert_eq!(app.start_key_label(), "F5/!");

        let custom = TuiConfig::parse_jsonc(
            r#"{"keybindings":{"start":["F5","!"]}}"#,
            std::path::Path::new("/tmp/tui.jsonc"),
        )
        .unwrap();
        app.set_tui_config(custom);

        assert_eq!(app.start_key_label(), "F5/!");
    }

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

    // ========================================================================
    // Header base branch capture (verification `tui-header-base-branch-tests`)
    //
    // Unit-scoped on purpose: the capture is a plain presentation field, so the
    // runner's Git read is the only part that touches a repository and these
    // assertions supply the resolved value directly.
    // ========================================================================

    /// Nothing is captured until the runner captures it, and what it captures
    /// is exactly what the header reads back.
    #[test]
    fn header_base_branch_capture_defaults_to_unset_and_keeps_what_the_runner_supplied() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        assert_eq!(
            app.base_branch(),
            None,
            "a fresh app has no branch identity to show"
        );

        app.set_base_branch(Some("main"));
        assert_eq!(app.base_branch(), Some("main"));

        // The startup capture is a value, not a live Git read: re-reading it any
        // number of times answers the same branch.
        assert_eq!(app.base_branch(), Some("main"));
    }

    /// An unresolved, detached, or blank startup lookup leaves the identity
    /// unset rather than producing an empty `[]` segment.
    #[test]
    fn header_base_branch_capture_treats_missing_and_blank_lookups_as_unset() {
        for blank in ["", "   ", "\n", "\t "] {
            let mut app = AppState::new(vec![]);
            app.set_base_branch(Some(blank));
            assert_eq!(
                app.base_branch(),
                None,
                "{blank:?} must not become a rendered branch segment"
            );
        }

        let mut detached = AppState::new(vec![]);
        detached.set_base_branch(Some("main"));
        detached.set_base_branch(None::<String>);
        assert_eq!(
            detached.base_branch(),
            None,
            "an unresolved lookup clears the segment instead of guessing"
        );

        // Surrounding whitespace from a command read is presentation noise, not
        // part of the branch name.
        let mut padded = AppState::new(vec![]);
        padded.set_base_branch(Some("  feature/base  "));
        assert_eq!(padded.base_branch(), Some("feature/base"));
    }

    // ========================================================================
    // Net execution time (verification `net-execution-time-tests`)
    //
    // The clock is supplied explicitly to the `_at` primitives, so these stay
    // unit-scoped: no sleeping, no real timer boundary, and every assertion is
    // an exact duration rather than a wall-clock tolerance.
    // ========================================================================

    fn timing_row() -> ChangeState {
        ChangeState::from_change(&create_test_change("timed", 0, 1))
    }

    /// Two active intervals separated by inactive time sum to the active time
    /// alone; the inactive gap contributes nothing.
    #[test]
    fn net_execution_time_excludes_the_inactive_interval_between_two_active_ones() {
        let base = Instant::now();
        let mut row = timing_row();

        row.start_active_interval_at(base);
        row.pause_active_interval_at(base + Duration::from_secs(10));
        // 100 seconds parked in `error` before an operator retries.
        row.start_active_interval_at(base + Duration::from_secs(110));
        row.pause_active_interval_at(base + Duration::from_secs(115));

        assert_eq!(row.elapsed_time, Some(Duration::from_secs(15)));
        assert_eq!(
            row.current_total_elapsed_at(base + Duration::from_secs(900)),
            Some(Duration::from_secs(15)),
            "an inactive row's retained total must not keep growing"
        );
    }

    /// Repeated active updates keep the original start boundary.
    #[test]
    fn net_execution_time_repeated_active_updates_neither_reset_nor_double_count() {
        let base = Instant::now();
        let mut row = timing_row();

        row.start_active_interval_at(base);
        row.start_active_interval_at(base + Duration::from_secs(3));
        row.start_active_interval_at(base + Duration::from_secs(7));

        assert_eq!(row.started_at, Some(base));
        assert_eq!(row.elapsed_time, None);
        assert_eq!(
            row.current_total_elapsed_at(base + Duration::from_secs(9)),
            Some(Duration::from_secs(9))
        );
    }

    /// Pausing an already-closed interval adds nothing.
    #[test]
    fn net_execution_time_pause_is_idempotent() {
        let base = Instant::now();
        let mut row = timing_row();

        row.start_active_interval_at(base);
        row.pause_active_interval_at(base + Duration::from_secs(12));
        row.pause_active_interval_at(base + Duration::from_secs(60));

        assert_eq!(row.started_at, None);
        assert_eq!(row.elapsed_time, Some(Duration::from_secs(12)));
    }

    /// While active the display is the accumulated total plus the open interval.
    #[test]
    fn net_execution_time_while_active_adds_the_open_interval_to_the_total() {
        let base = Instant::now();
        let mut row = timing_row();
        row.elapsed_time = Some(Duration::from_secs(30));

        row.start_active_interval_at(base);

        assert_eq!(
            row.current_total_elapsed_at(base + Duration::from_secs(5)),
            Some(Duration::from_secs(35))
        );
    }

    /// A row that never executed has nothing to display.
    #[test]
    fn net_execution_time_is_absent_until_a_row_executes() {
        let row = timing_row();
        assert_eq!(row.current_total_elapsed(), None);
        assert!(!row.has_execution_history());
    }

    /// Every status in the shared active vocabulary opens an interval, and every
    /// other status closes it — the classification comes from `is_active_status`
    /// alone, never from a second hand-written list.
    #[test]
    fn net_execution_time_status_transitions_follow_the_shared_active_vocabulary() {
        use crate::orchestration::operator_command::ACTIVE_STATUSES;

        for status in ACTIVE_STATUSES {
            let mut row = timing_row();
            row.set_display_status_cache(status);
            assert!(
                row.started_at.is_some(),
                "`{status}` must open an active interval"
            );
        }

        for status in [
            "not queued",
            "queued",
            "blocked",
            "stalled",
            "merge wait",
            "resolve pending",
            "archived",
            "merged",
            "pushed",
            "rejected",
            "error",
        ] {
            let base = Instant::now();
            let mut row = timing_row();
            row.start_active_interval_at(base);
            row.set_display_status_cache(status);
            assert_eq!(
                row.started_at, None,
                "`{status}` must close the active interval"
            );
            assert!(
                row.elapsed_time.is_some(),
                "`{status}` must retain the accumulated duration"
            );
        }
    }

    /// Terminal, error, and stalled rows retain their accumulated duration.
    #[test]
    fn net_execution_time_is_retained_through_terminal_and_error_transitions() {
        for status in ["merged", "error", "stalled"] {
            let base = Instant::now();
            let mut row = timing_row();
            row.set_display_status_cache("applying");
            row.started_at = Some(base);

            row.set_display_status_cache(status);

            assert_eq!(row.display_status_cache, status);
            assert!(row.has_execution_history());
            let retained = row.elapsed_time.expect("retained duration");
            assert_eq!(
                row.current_total_elapsed_at(base + Duration::from_secs(600)),
                Some(retained),
                "`{status}` must retain a frozen duration, not a growing one"
            );
        }
    }

    /// Reducer status synchronization is the same centralized boundary: it must
    /// accumulate rather than restart, across a full inactive round trip.
    #[test]
    fn net_execution_time_survives_a_reducer_driven_inactive_round_trip() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);

        let mut display_map: HashMap<String, &'static str> = HashMap::new();
        display_map.insert("change-a".to_string(), "applying");
        app.apply_display_statuses_from_reducer(&display_map);
        let first_start = app.changes[0].started_at.expect("interval opened");

        display_map.insert("change-a".to_string(), "error");
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(app.changes[0].started_at, None);
        let after_first = app.changes[0].elapsed_time.expect("first interval closed");

        display_map.insert("change-a".to_string(), "applying");
        app.apply_display_statuses_from_reducer(&display_map);
        let second_start = app.changes[0].started_at.expect("interval reopened");

        assert!(
            second_start >= first_start,
            "a fresh interval must be opened, not the closed one restored"
        );
        assert_eq!(
            app.changes[0].elapsed_time,
            Some(after_first),
            "resuming must not discard the duration already accumulated"
        );
    }

    fn visible_filtered_messages(app: &AppState) -> Vec<String> {
        app.logs
            .iter()
            .filter(|entry| app.log_entry_visible_for_selected_proposal_filter(entry))
            .map(|entry| entry.message.clone())
            .collect()
    }

    fn app_with_mixed_proposal_logs() -> AppState {
        let mut app = AppState::new(vec![
            create_test_change("alpha", 0, 1),
            create_test_change("beta", 0, 1),
        ]);
        app.logs.clear();
        app.add_log(LogEntry::info("alpha apply").with_change_id("alpha"));
        app.add_log(LogEntry::info("beta apply").with_change_id("beta"));
        app.add_log(LogEntry::info("global orchestration"));
        app
    }

    /// Buffer trimming evicts the anchored entry, so the anchor must clamp to
    /// the oldest surviving display line without resuming auto-scroll.
    #[test]
    fn trimming_the_anchored_entry_clamps_to_the_oldest_surviving_line() {
        let mut app = AppState::new(vec![create_test_change("alpha", 0, 1)]);
        app.logs.clear();
        app.set_log_viewport(60, 7);
        for index in 0..MAX_LOG_ENTRIES {
            app.add_log(LogEntry::info(format!("log {index}")));
        }

        app.scroll_logs_to_top();
        let anchored = app.log_anchor.unwrap();
        assert_eq!(anchored.entry_seq, 0);

        // Five more entries evict the five oldest, including the anchored one.
        for index in 0..5 {
            app.add_log(LogEntry::info(format!("overflow {index}")));
        }
        assert_eq!(app.logs.len(), MAX_LOG_ENTRIES);
        assert_eq!(app.logs[0].message, "log 5");

        // The anchor object is untouched, but it now resolves to the oldest
        // surviving line rather than to a stale index or to the newest output.
        assert_eq!(app.log_anchor, Some(anchored));
        let lines = app.log_display_lines();
        assert_eq!(app.log_start_line(&lines), 0);
        assert_eq!(lines[0].text, "log 5");
        assert!(!app.log_auto_scroll);
    }

    #[test]
    fn selected_proposal_log_filter_defaults_off_and_shows_every_entry() {
        let app = app_with_mixed_proposal_logs();

        assert!(!app.selected_proposal_log_filter);
        assert_eq!(
            visible_filtered_messages(&app),
            vec!["alpha apply", "beta apply", "global orchestration"]
        );
    }

    #[test]
    fn selected_proposal_log_filter_shows_only_cursor_proposal_entries() {
        let mut app = app_with_mixed_proposal_logs();

        app.toggle_selected_proposal_log_filter();

        assert!(app.selected_proposal_log_filter);
        assert_eq!(app.selected_proposal_log_filter_target(), Some("alpha"));
        assert_eq!(visible_filtered_messages(&app), vec!["alpha apply"]);
    }

    #[test]
    fn selected_proposal_log_filter_follows_cursor_and_resets_to_newest() {
        let mut app = app_with_mixed_proposal_logs();
        app.toggle_selected_proposal_log_filter();
        app.scroll_logs_to_top();
        assert!(app.log_anchor.is_some());

        app.cursor_down();

        assert_eq!(app.selected_proposal_log_filter_target(), Some("beta"));
        assert_eq!(visible_filtered_messages(&app), vec!["beta apply"]);
        assert_eq!(app.log_anchor, None);
        assert!(app.log_auto_scroll);
    }

    #[test]
    fn cursor_move_keeps_log_position_when_filter_is_off() {
        let mut app = app_with_mixed_proposal_logs();
        app.scroll_logs_to_top();
        let anchored = app.log_anchor;
        assert!(anchored.is_some());

        app.cursor_down();

        assert_eq!(app.log_anchor, anchored);
        assert!(!app.log_auto_scroll);
    }

    #[test]
    fn toggling_selected_proposal_log_filter_never_mutates_the_log_buffer() {
        let mut app = app_with_mixed_proposal_logs();
        let before: Vec<String> = app.logs.iter().map(|e| e.message.clone()).collect();

        app.toggle_selected_proposal_log_filter();
        app.toggle_selected_proposal_log_filter();

        let after: Vec<String> = app.logs.iter().map(|e| e.message.clone()).collect();
        assert_eq!(before, after);
        assert!(!app.selected_proposal_log_filter);
        assert_eq!(
            visible_filtered_messages(&app),
            vec!["alpha apply", "beta apply", "global orchestration"]
        );
    }

    #[test]
    fn toggling_selected_proposal_log_filter_returns_to_newest_output() {
        let mut app = app_with_mixed_proposal_logs();
        app.scroll_logs_to_top();
        assert!(app.log_anchor.is_some());

        app.toggle_selected_proposal_log_filter();

        assert_eq!(app.log_anchor, None);
        assert!(app.log_auto_scroll);
    }

    #[test]
    fn selected_proposal_log_filter_hides_everything_without_a_cursor_proposal() {
        let mut app = AppState::new(vec![]);
        app.logs.clear();
        app.add_log(LogEntry::info("alpha apply").with_change_id("alpha"));
        app.add_log(LogEntry::info("global orchestration"));

        app.toggle_selected_proposal_log_filter();

        assert_eq!(app.selected_proposal_log_filter_target(), None);
        assert!(visible_filtered_messages(&app).is_empty());
        assert_eq!(app.logs.len(), 2);
    }

    #[test]
    fn selected_proposal_log_filter_uses_handler_attached_metadata_not_message_text() {
        let mut app = AppState::new(vec![
            create_test_change("alpha", 0, 1),
            create_test_change("beta", 0, 1),
        ]);
        app.logs.clear();

        app.handle_processing_started("alpha".to_string());
        app.handle_processing_error("beta".to_string(), "boom".to_string());
        app.handle_analysis_started(1, "attempt-a".to_string());

        app.toggle_selected_proposal_log_filter();

        // The beta error message contains the substring "beta", but only the
        // structured metadata decides visibility.
        assert_eq!(visible_filtered_messages(&app), vec!["Processing: alpha"]);
        assert_eq!(app.logs.len(), 3);
    }

    #[test]
    fn selected_proposal_log_filter_excludes_remote_project_only_entries() {
        let mut app = AppState::new(vec![create_test_change("proj-1::demo/alpha", 0, 1)]);
        app.logs.clear();
        app.add_log(LogEntry::info("project scoped output").with_change_id("proj-1"));
        app.add_log(LogEntry::info("proposal output").with_change_id("proj-1::demo/alpha"));

        app.toggle_selected_proposal_log_filter();

        assert_eq!(visible_filtered_messages(&app), vec!["proposal output"]);
    }

    fn create_test_worktree(path: &str, branch: &str, is_main: bool) -> WorktreeInfo {
        WorktreeInfo {
            path: PathBuf::from(path),
            head: "abc123".to_string(),
            branch: branch.to_string(),
            is_detached: false,
            is_main,
            merge_conflict: None,
            has_commits_ahead: true,
            is_merging: false,
            inspection: crate::worktree_ops::InspectionState::Checked,
        }
    }

    #[test]
    fn stale_archive_started_does_not_regress_merged_row() {
        let change = create_test_change("alpha", 1, 1);
        let mut app = AppState::new(vec![change]);
        app.changes[0].set_display_status_cache("merged");

        app.handle_orchestrator_event(OrchestratorEvent::ArchiveStarted {
            change_id: "alpha".to_string(),
            command: "archive alpha".to_string(),
        });

        assert_eq!(app.changes[0].display_status_cache, "merged");
        assert_eq!(app.changes[0].display_color_cache, Color::LightBlue);
    }

    #[test]
    fn worktree_delete_progress_marker_marks_and_clears_path() {
        let mut app = AppState::new(vec![]);
        let path = PathBuf::from("/tmp/worktree-a");

        assert!(!app.is_worktree_deleting(&path));
        app.mark_worktree_deleting(path.clone());
        assert!(app.is_worktree_deleting(&path));
        app.clear_worktree_deleting(&path);
        assert!(!app.is_worktree_deleting(&path));
    }

    #[test]
    fn worktree_delete_confirmation_marks_before_emitting_delete_command() {
        let mut app = AppState::new(vec![]);
        app.worktrees = vec![create_test_worktree("/tmp/worktree-a", "feature-a", false)];
        app.request_worktree_delete_from_list();

        let command = app.confirm_worktree_action_delete();

        assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")));
        assert!(matches!(
            &command,
            Some(TuiCommand::DeleteWorktree(intent))
                if intent.path == *"/tmp/worktree-a"
                    && intent.branch == "feature-a"
                    && !intent.skip_teardown
                    && !intent.allow_known_dirty
        ));
        assert!(app
            .logs
            .iter()
            .any(|entry| entry.message.contains("Deleting worktree: /tmp/worktree-a")));
    }

    #[test]
    fn worktree_skip_teardown_confirmation_marks_before_emitting_delete_command() {
        let mut app = AppState::new(vec![]);
        app.worktrees = vec![create_test_worktree("/tmp/worktree-a", "feature-a", false)];
        app.request_worktree_delete_from_list();

        let command = app.confirm_worktree_action_delete_with_options(true);

        assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")));
        assert!(matches!(
            &command,
            Some(TuiCommand::DeleteWorktree(intent))
                if intent.path == *"/tmp/worktree-a"
                    && intent.branch == "feature-a"
                    && intent.skip_teardown
                    && !intent.allow_known_dirty
        ));
        assert!(app.logs.iter().any(|entry| {
            entry
                .message
                .contains("Deleting worktree with skip-teardown: /tmp/worktree-a")
        }));
    }

    #[test]
    fn a_worktree_without_a_branch_identity_can_never_produce_a_delete_command() {
        // Both ways an observation loses its identity, driven through the whole
        // request → confirm path: no modal opens, so no confirmation exists to
        // dispatch, and the delete marker is never taken either.
        let mut detached = create_test_worktree("/tmp/worktree-a", "feature-a", false);
        detached.is_detached = true;
        let nameless = create_test_worktree("/tmp/worktree-a", "", false);

        for (name, worktree) in [("detached", detached), ("empty-branch", nameless)] {
            let mut app = AppState::new(vec![]);
            app.view_mode = ViewMode::Worktrees;
            app.worktrees = vec![worktree];

            assert!(app.request_worktree_delete_from_list().is_none());

            assert!(
                app.modal.is_none(),
                "{name}: no confirmation may open without a revalidatable identity"
            );
            assert!(
                app.warning_message
                    .as_deref()
                    .is_some_and(|msg| msg.contains("no branch to confirm against")),
                "{name}: the operator must be told why: {:?}",
                app.warning_message
            );
            assert!(
                app.confirm_worktree_action_delete().is_none(),
                "{name}: confirming without a modal must not emit a delete command"
            );
            assert!(
                app.confirm_worktree_action_delete_with_options(true)
                    .is_none(),
                "{name}: skip-teardown confirm must not emit a delete command either"
            );
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
                "{name}: a refused request must not mark the worktree deleting"
            );
        }
    }

    #[test]
    fn a_branch_bearing_worktree_beside_a_detached_one_stays_deletable() {
        // The identity guard refuses the target it cannot revalidate without
        // narrowing deletion for ordinary branch-bearing worktrees.
        let mut detached = create_test_worktree("/tmp/worktree-detached", "feature-a", false);
        detached.is_detached = true;
        let mut app = AppState::new(vec![]);
        app.view_mode = ViewMode::Worktrees;
        app.worktrees = vec![
            detached,
            create_test_worktree("/tmp/worktree-b", "feature-b", false),
        ];
        app.worktree_cursor_index = 1;

        app.request_worktree_delete_from_list();

        assert_eq!(
            app.modal,
            Some(ModalState::ConfirmWorktreeDelete {
                path: PathBuf::from("/tmp/worktree-b"),
                branch: "feature-b".to_string(),
            })
        );
        assert!(matches!(
            &app.confirm_worktree_action_delete(),
            Some(TuiCommand::DeleteWorktree(intent))
                if intent.path == std::path::Path::new("/tmp/worktree-b") && intent.branch == "feature-b"
        ));
    }

    /// A named way a dirty-discard target can drift before the confirmation.
    type DirtyDriftCase = (&'static str, fn(&mut AppState));

    fn dirty_target(path: &str, branch: &str) -> crate::worktree_ops::service::DirtyTarget {
        crate::worktree_ops::service::DirtyTarget {
            path: PathBuf::from(path),
            identity: format!("gitdir: {path}/.git"),
            branch: branch.to_string(),
            head: "abc123".to_string(),
        }
    }

    /// An app whose single worktree matches [`dirty_target`]'s observation.
    fn dirty_discard_app() -> AppState {
        let mut app = AppState::new(vec![create_test_change("feature-a", 0, 1)]);
        app.view_mode = ViewMode::Worktrees;
        app.worktrees = vec![create_test_worktree("/tmp/worktree-a", "feature-a", false)];
        app
    }

    #[test]
    fn tui_dirty_worktree_delete_escalation_captures_the_services_observation() {
        for skip_teardown in [false, true] {
            let mut app = dirty_discard_app();

            app.open_dirty_discard_confirmation(
                &dirty_target("/tmp/worktree-a", "feature-a"),
                skip_teardown,
            );

            // Every field comes from the service's fresh look, including the
            // identity and HEAD the projection in `worktrees` does not carry.
            assert_eq!(
                app.modal,
                Some(ModalState::ConfirmDirtyDiscard {
                    path: PathBuf::from("/tmp/worktree-a"),
                    identity: "gitdir: /tmp/worktree-a/.git".to_string(),
                    branch: "feature-a".to_string(),
                    head: "abc123".to_string(),
                    skip_teardown,
                })
            );
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
                "escalating is not deleting: the marker must not be taken yet"
            );
            assert!(app
                .logs
                .iter()
                .any(|entry| entry.message.contains("press X to discard them")));
        }
    }

    #[test]
    fn tui_dirty_worktree_delete_confirmation_grants_discard_with_the_captured_teardown_bit() {
        for skip_teardown in [false, true] {
            let mut app = dirty_discard_app();
            app.open_dirty_discard_confirmation(
                &dirty_target("/tmp/worktree-a", "feature-a"),
                skip_teardown,
            );

            let command = app.confirm_dirty_discard();

            let Some(TuiCommand::DeleteWorktree(intent)) = command else {
                panic!("expected a delete command, got {command:?}");
            };
            assert_eq!(intent.path, PathBuf::from("/tmp/worktree-a"));
            assert_eq!(intent.branch, "feature-a");
            assert_eq!(
                intent.identity.as_deref(),
                Some("gitdir: /tmp/worktree-a/.git")
            );
            assert_eq!(intent.head.as_deref(), Some("abc123"));
            assert!(
                intent.allow_known_dirty,
                "uppercase X is what grants the discard permission"
            );
            assert_eq!(
                intent.skip_teardown, skip_teardown,
                "the teardown decision is the one taken in the ordinary confirmation"
            );
            assert!(app.modal.is_none());
            assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")));
        }
    }

    #[test]
    fn tui_dirty_worktree_delete_ordinary_confirmations_never_grant_discard() {
        for skip_teardown in [false, true] {
            let mut app = dirty_discard_app();
            app.request_worktree_delete_from_list();

            let command = app.confirm_worktree_action_delete_with_options(skip_teardown);

            let Some(TuiCommand::DeleteWorktree(intent)) = command else {
                panic!("expected a delete command, got {command:?}");
            };
            assert!(
                !intent.allow_known_dirty,
                "neither Y nor S may grant permission to discard uncommitted work"
            );
            assert!(
                !intent.allow_commits_ahead,
                "neither Y nor S may grant permission to discard unmerged commits"
            );
            assert_eq!(intent.skip_teardown, skip_teardown);
            assert_eq!(intent.identity, None);
            assert_eq!(intent.head, None);
        }
    }

    fn ahead_target(
        path: &str,
        branch: &str,
        dirty: bool,
    ) -> crate::worktree_ops::service::AheadTarget {
        crate::worktree_ops::service::AheadTarget {
            path: PathBuf::from(path),
            identity: format!("gitdir: {path}/.git"),
            branch: branch.to_string(),
            head: "abc123".to_string(),
            dirty,
        }
    }

    #[test]
    fn tui_ahead_worktree_delete_escalation_captures_the_services_observation() {
        for dirty in [false, true] {
            for skip_teardown in [false, true] {
                let mut app = dirty_discard_app();

                app.open_ahead_discard_confirmation(
                    &ahead_target("/tmp/worktree-a", "feature-a", dirty),
                    skip_teardown,
                );

                assert_eq!(
                    app.modal,
                    Some(ModalState::ConfirmAheadDiscard {
                        path: PathBuf::from("/tmp/worktree-a"),
                        identity: "gitdir: /tmp/worktree-a/.git".to_string(),
                        branch: "feature-a".to_string(),
                        head: "abc123".to_string(),
                        dirty,
                        skip_teardown,
                    })
                );
                assert!(
                    !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
                    "escalating is not deleting: the marker must not be taken yet"
                );
                assert!(app
                    .logs
                    .iter()
                    .any(|entry| entry.message.contains("has unmerged commits")
                        && entry.message.contains("press X")));
            }
        }
    }

    #[test]
    fn tui_ahead_worktree_delete_confirmation_grants_exactly_what_it_disclosed() {
        for dirty in [false, true] {
            for skip_teardown in [false, true] {
                let mut app = dirty_discard_app();
                app.open_ahead_discard_confirmation(
                    &ahead_target("/tmp/worktree-a", "feature-a", dirty),
                    skip_teardown,
                );

                let command = app.confirm_ahead_discard();

                let Some(TuiCommand::DeleteWorktree(intent)) = command else {
                    panic!("expected a delete command, got {command:?}");
                };
                assert_eq!(intent.path, PathBuf::from("/tmp/worktree-a"));
                assert_eq!(intent.branch, "feature-a");
                assert_eq!(
                    intent.identity.as_deref(),
                    Some("gitdir: /tmp/worktree-a/.git")
                );
                assert_eq!(intent.head.as_deref(), Some("abc123"));
                assert!(
                    intent.allow_commits_ahead,
                    "uppercase X is what grants the ahead-discard permission"
                );
                assert_eq!(
                    intent.allow_known_dirty, dirty,
                    "dirty discard travels with X only when the modal disclosed that loss too"
                );
                assert_eq!(intent.skip_teardown, skip_teardown);
                assert!(app.modal.is_none());
                assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")));
            }
        }
    }

    #[test]
    fn tui_ahead_worktree_delete_cancellation_retains_the_worktree_and_branch() {
        let mut app = dirty_discard_app();
        app.open_ahead_discard_confirmation(
            &ahead_target("/tmp/worktree-a", "feature-a", true),
            false,
        );

        app.cancel_worktree_action();

        assert!(app.modal.is_none());
        assert!(
            !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
            "cancelling must leave the worktree, its content, and its branch alone"
        );
        assert!(
            app.confirm_ahead_discard().is_none(),
            "confirming without a modal must not emit a delete command"
        );
    }

    #[test]
    fn tui_ahead_worktree_delete_refuses_a_target_that_drifted_before_dispatch() {
        let cases: [DirtyDriftCase; 5] = [
            ("absent", |app: &mut AppState| app.worktrees.clear()),
            ("main", |app: &mut AppState| app.worktrees[0].is_main = true),
            ("rebranded", |app: &mut AppState| {
                app.worktrees[0].branch = "feature-z".to_string()
            }),
            ("head-moved", |app: &mut AppState| {
                app.worktrees[0].head = "def456".to_string()
            }),
            ("active", |app: &mut AppState| {
                app.changes[0].set_display_status_cache("applying")
            }),
        ];

        for (name, mutate) in cases {
            let mut app = dirty_discard_app();
            app.open_ahead_discard_confirmation(
                &ahead_target("/tmp/worktree-a", "feature-a", false),
                false,
            );
            mutate(&mut app);

            assert!(
                app.confirm_ahead_discard().is_none(),
                "{name}: a drifted target must not be discarded"
            );
            assert!(
                app.modal.is_none(),
                "{name}: the stale modal must be cleared"
            );
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
                "{name}: a refused discard must not mark the worktree deleting"
            );
        }
    }

    #[test]
    fn tui_ahead_and_dirty_confirmations_never_answer_for_each_other() {
        // Two overlays, two permissions. Pressing through one must not satisfy
        // the other, in either direction.
        let mut ahead = dirty_discard_app();
        ahead.open_ahead_discard_confirmation(
            &ahead_target("/tmp/worktree-a", "feature-a", true),
            false,
        );
        assert!(
            ahead.confirm_dirty_discard().is_none(),
            "the dirty confirmation must not act on an ahead modal"
        );
        assert!(ahead.modal.is_some(), "and must leave it standing");

        let mut dirty = dirty_discard_app();
        dirty.open_dirty_discard_confirmation(&dirty_target("/tmp/worktree-a", "feature-a"), false);
        assert!(
            dirty.confirm_ahead_discard().is_none(),
            "the ahead confirmation must not act on a dirty modal"
        );
        assert!(dirty.modal.is_some(), "and must leave it standing");
    }

    #[test]
    fn tui_dirty_worktree_delete_cancellation_retains_the_worktree() {
        let mut app = dirty_discard_app();
        app.open_dirty_discard_confirmation(&dirty_target("/tmp/worktree-a", "feature-a"), false);

        app.cancel_worktree_action();

        assert!(app.modal.is_none());
        assert!(
            !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
            "cancelling must leave the worktree and its content alone"
        );
        assert!(
            app.confirm_dirty_discard().is_none(),
            "confirming without a modal must not emit a delete command"
        );
    }

    #[test]
    fn tui_dirty_worktree_delete_refuses_a_target_that_drifted_before_dispatch() {
        let cases: [DirtyDriftCase; 5] = [
            ("absent", |app: &mut AppState| app.worktrees.clear()),
            ("main", |app: &mut AppState| app.worktrees[0].is_main = true),
            ("rebranded", |app: &mut AppState| {
                app.worktrees[0].branch = "feature-z".to_string()
            }),
            ("head-moved", |app: &mut AppState| {
                app.worktrees[0].head = "def456".to_string()
            }),
            ("active", |app: &mut AppState| {
                app.changes[0].set_display_status_cache("applying")
            }),
        ];

        for (name, mutate) in cases {
            let mut app = dirty_discard_app();
            app.open_dirty_discard_confirmation(
                &dirty_target("/tmp/worktree-a", "feature-a"),
                false,
            );
            mutate(&mut app);

            assert!(
                app.confirm_dirty_discard().is_none(),
                "{name}: a drifted target must not be discarded"
            );
            assert!(
                app.modal.is_none(),
                "{name}: the stale modal must be cleared"
            );
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/worktree-a")),
                "{name}: a refused discard must not mark the worktree deleting"
            );
        }
    }

    #[test]
    fn worktree_delete_request_is_suppressed_while_marker_is_active() {
        let mut app = AppState::new(vec![]);
        let path = PathBuf::from("/tmp/worktree-a");
        app.worktrees = vec![create_test_worktree("/tmp/worktree-a", "feature-a", false)];
        app.mark_worktree_deleting(path);

        app.request_worktree_delete_from_list();

        assert!(app.modal.is_none());
        assert_eq!(
            app.warning_message.as_deref(),
            Some("Worktree is already being deleted")
        );
    }

    #[test]
    fn merge_request_is_suppressed_while_selected_worktree_is_deleting() {
        let mut app = AppState::new(vec![]);
        app.view_mode = ViewMode::Worktrees;
        let path = PathBuf::from("/tmp/worktree-a");
        app.worktrees = vec![create_test_worktree("/tmp/worktree-a", "feature-a", false)];
        app.mark_worktree_deleting(path);

        let command = app.request_merge_worktree_branch();

        assert!(command.is_none());
        assert_eq!(
            app.warning_message.as_deref(),
            Some("Worktree is already being deleted")
        );
    }

    #[test]
    fn warning_popup_lifecycle_resets_scroll_offset() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.show_warning_popup("first", "message");
        app.scroll_warning_popup(3);
        assert_eq!(app.warning_popup_scroll, 3);

        app.show_warning_popup("second", "message");
        assert_eq!(app.warning_popup_scroll, 0);

        app.scroll_warning_popup(2);
        app.clear_warning_popup();
        assert_eq!(app.warning_popup_scroll, 0);
        assert!(app.warning_popup.is_none());
    }

    #[test]
    fn warning_popup_scroll_saturates_at_zero() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.show_warning_popup("warning", "message");

        app.scroll_warning_popup(-5);

        assert_eq!(app.warning_popup_scroll, 0);
    }

    #[test]
    fn test_change_state_progress() {
        let change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 3,
            total_tasks: 6,
            display_status_cache: "not queued".to_string(),
            blocker_kind_cache: crate::orchestration::state::BlockerKind::None,
            blocker_detail_cache: None,
            display_color_cache: Color::DarkGray,
            error_message_cache: None,
            selected: false,
            is_new: false,
            parallel_eligibility: ParallelEligibility::Eligible,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
            apply_operation_cache: "apply".to_string(),
            archive_complete_cache: false,
        };

        assert_eq!(change.progress_percent(), 50.0);
    }

    #[test]
    fn test_app_state_new_all_not_selected() {
        // All changes should start unselected on startup
        let changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-b", 0, 3),
        ];

        let app = AppState::new(changes);

        assert_eq!(app.execution_mode, AppExecutionMode::Select);
        assert_eq!(app.changes.len(), 2);
        assert_eq!(app.cursor_index, 0);
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
    }

    #[test]
    fn test_app_state_no_auto_selection() {
        // Changes should NOT be auto-selected on startup
        let changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-b", 0, 3),
        ];

        let app = AppState::new(changes);

        assert_eq!(app.execution_mode, AppExecutionMode::Select);
        assert_eq!(app.changes.len(), 2);
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        // Should NOT have log entry for auto-queued changes
        assert!(!app
            .logs
            .iter()
            .any(|log| log.message.contains("Auto-queued")));
    }

    #[test]
    fn test_cursor_navigation() {
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);

        assert_eq!(app.cursor_index, 0);

        app.cursor_down();
        assert_eq!(app.cursor_index, 1);

        app.cursor_down();
        assert_eq!(app.cursor_index, 2);

        app.cursor_down();
        assert_eq!(app.cursor_index, 0); // Wraps around

        app.cursor_up();
        assert_eq!(app.cursor_index, 2); // Wraps around
    }

    #[test]
    fn test_toggle_selection() {
        // Changes start unselected
        let changes = vec![create_test_change("a", 0, 1)];

        let mut app = AppState::new(changes);

        assert!(!app.changes[0].selected);

        app.toggle_selection();
        assert!(app.changes[0].selected);

        app.toggle_selection();
        assert!(!app.changes[0].selected);
    }

    #[test]
    fn test_toggle_all_marks_select_mode() {
        // Test toggle all in Select mode - mark all then unmark all
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);
        assert_eq!(app.execution_mode, AppExecutionMode::Select);

        // All start unselected
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);

        // First toggle: should mark all
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);

        // Second toggle: should unmark all
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);
    }

    #[test]
    fn test_toggle_all_marks_stopped_mode() {
        // Test toggle all in Stopped mode
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Stopped;

        // First toggle: should mark all
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);

        // Second toggle: should unmark all
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
    }

    /// Worktree eligibility no longer gates a mark.
    ///
    /// A mark is next-run intent; whether the run may actually start is decided
    /// at final admission, where the all-or-nothing worktree fence still lives.
    #[test]
    fn test_toggle_all_marks_includes_worktree_ineligible_rows() {
        let changes = vec![
            create_test_change("committed", 0, 1),
            create_test_change("uncommitted", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Select;

        app.changes[0].parallel_eligibility = ParallelEligibility::Eligible;
        app.changes[1].parallel_eligibility = ParallelEligibility::UncommittedProposalFiles;

        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(
            app.changes[1].selected,
            "an ineligible row still carries next-run intent"
        );
        assert!(
            app.warning_message.is_none(),
            "eligibility is not a mark-time refusal: {:?}",
            app.warning_message
        );

        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
    }

    /// Eligibility observation keeps the two Git facts apart.
    ///
    /// Both answers still refuse parallel admission; only the reason differs,
    /// and only one of them is a working-tree condition.
    #[test]
    fn parallel_eligibility_records_why_a_change_is_refused() {
        let changes = vec![
            create_test_change("clean", 0, 1),
            create_test_change("absent", 0, 1),
            create_test_change("dirty", 0, 1),
            create_test_change("brand-new", 0, 1),
        ];
        let mut app = AppState::new(changes);

        let committed = HashSet::from(["clean".to_string(), "dirty".to_string()]);
        let uncommitted = HashSet::from(["dirty".to_string(), "brand-new".to_string()]);
        app.apply_parallel_eligibility(&committed, &uncommitted);

        let by_id = |id: &str| {
            app.changes
                .iter()
                .find(|change| change.id == id)
                .unwrap_or_else(|| panic!("'{id}' must be tracked"))
                .clone()
        };

        assert_eq!(
            by_id("clean").parallel_eligibility,
            ParallelEligibility::Eligible
        );
        assert_eq!(
            by_id("absent").parallel_eligibility,
            ParallelEligibility::ProposalAbsentFromHead
        );
        assert_eq!(
            by_id("dirty").parallel_eligibility,
            ParallelEligibility::UncommittedProposalFiles
        );
        // Untracked and absent at once: committing it is what fixes both, so it
        // is reported as the condition the operator can act on.
        assert_eq!(
            by_id("brand-new").parallel_eligibility,
            ParallelEligibility::UncommittedProposalFiles
        );

        // The admission guard is unchanged: every non-eligible reason is false.
        assert!(by_id("clean").is_parallel_eligible());
        for refused in ["absent", "dirty", "brand-new"] {
            assert!(
                !by_id(refused).is_parallel_eligible(),
                "'{refused}' must stay out of parallel queueing"
            );
        }

        // Only observed dirty content may be presented as uncommitted state.
        assert!(!by_id("absent").has_uncommitted_proposal_files());
        assert!(by_id("dirty").has_uncommitted_proposal_files());

        // The shared runtime store carries the same reasons, not just the set.
        let runtime = app.parallel_runtime();
        assert_eq!(
            runtime.ineligible_ids(),
            vec![
                "absent".to_string(),
                "brand-new".to_string(),
                "dirty".to_string()
            ]
        );
        assert_eq!(
            runtime.eligibility("absent"),
            ParallelEligibility::ProposalAbsentFromHead
        );
        assert_eq!(
            runtime.eligibility("dirty"),
            ParallelEligibility::UncommittedProposalFiles
        );
        assert_eq!(runtime.eligibility("clean"), ParallelEligibility::Eligible);
    }

    /// Worktree ineligibility is a *run* refusal, not a mark refusal.
    ///
    /// Both reasons still exist and still refuse a start; neither may stop an
    /// operator from expressing next-run intent, and neither may make the
    /// checkbox lie about the mark that was set.
    #[test]
    fn single_row_toggle_admits_both_parallel_ineligible_reasons() {
        for eligibility in [
            ParallelEligibility::UncommittedProposalFiles,
            ParallelEligibility::ProposalAbsentFromHead,
        ] {
            let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
            app.changes[0].parallel_eligibility = eligibility;

            app.toggle_selection();

            assert!(
                app.changes[0].selected,
                "{eligibility:?} must still accept mark intent"
            );
            assert!(
                app.warning_message.is_none(),
                "{eligibility:?} must not refuse the mark: {:?}",
                app.warning_message
            );
            assert_eq!(
                app.take_pending_mark_writes(),
                vec![("change-a".to_string(), true)]
            );
        }
    }

    /// A bulk toggle covers every visible non-terminal row, whatever its
    /// worktree eligibility, and never reports an exclusion for one.
    #[test]
    fn bulk_toggle_covers_parallel_ineligible_rows_without_a_warning() {
        let changes = vec![
            create_test_change("eligible", 0, 1),
            create_test_change("dirty", 0, 1),
            create_test_change("absent", 0, 1),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Select;
        app.apply_parallel_eligibility(
            &HashSet::from(["eligible".to_string(), "dirty".to_string()]),
            &HashSet::from(["dirty".to_string()]),
        );

        app.toggle_all_marks();

        assert!(app.changes.iter().all(|change| change.selected));
        assert!(
            app.warning_message.is_none(),
            "no row was excluded, so nothing is reported: {:?}",
            app.warning_message
        );
    }

    #[test]
    fn test_toggle_all_marks_partial_selection() {
        // Test that if any unmarked change exists, toggle marks all
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);

        // Manually select one change
        app.changes[0].selected = true;

        // Toggle all should mark the rest (because unmarked changes exist)
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);

        // Toggle all again should unmark all
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);
    }

    /// Running-mode bulk mark writes marks and nothing else.
    ///
    /// Active, queued, and wait rows are all mark targets now — the row that
    /// used to be skipped so Space could mean "stop" instead. What must not
    /// move is anything the current run owns: no queue command is emitted and
    /// no display status is rewritten.
    #[test]
    fn test_toggle_all_marks_running_mode_writes_marks_without_queue_or_status_effects() {
        let changes = vec![
            create_test_change("active", 0, 1),
            create_test_change("not-queued", 0, 1),
            create_test_change("queued", 0, 1),
            create_test_change("merge-wait", 0, 1),
            create_test_change("resolve-wait", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.set_resolving("__active__");
        app.changes[0].display_status_cache = "resolving".to_string();
        app.changes[1].display_status_cache = "not queued".to_string();
        app.changes[2].display_status_cache = "queued".to_string();
        app.changes[3].display_status_cache = "merge wait".to_string();
        app.changes[4].display_status_cache = "resolve pending".to_string();
        let statuses_before: Vec<String> = app
            .changes
            .iter()
            .map(|change| change.display_status_cache.clone())
            .collect();

        let commands = app.toggle_all_marks();

        assert!(
            commands.is_empty(),
            "a bulk mark emits no queue command: {commands:?}"
        );
        assert!(
            app.changes.iter().all(|change| change.selected),
            "every non-terminal row receives the derived mark"
        );
        let statuses_after: Vec<String> = app
            .changes
            .iter()
            .map(|change| change.display_status_cache.clone())
            .collect();
        assert_eq!(
            statuses_after, statuses_before,
            "a mark never rewrites a display status"
        );

        let commands = app.toggle_all_marks();
        assert!(commands.is_empty());
        assert!(
            app.changes.iter().all(|change| !change.selected),
            "a fully marked target set unmarks in one operation"
        );
    }

    #[test]
    fn test_bulk_toggle_select_mode_returns_no_commands() {
        // In Select mode, toggle_all_marks should NOT emit any queue commands.
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Select;

        let commands = app.toggle_all_marks();

        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(
            commands.is_empty(),
            "Select mode must not emit queue commands"
        );
    }

    #[test]
    fn test_bulk_toggle_stopped_mode_returns_no_commands() {
        // In Stopped mode, toggle_all_marks should NOT emit any queue commands.
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Stopped;

        let commands = app.toggle_all_marks();

        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(
            commands.is_empty(),
            "Stopped mode must not emit queue commands"
        );
    }

    /// Rows for a bulk toggle case: (id, display status, parallel eligible, pre-selected).
    type BulkToggleRow = (&'static str, &'static str, bool, bool);

    /// Applies one bulk toggle case and returns the resulting `selected` flags.
    fn run_bulk_toggle_case(
        mode: AppExecutionMode,
        rows: &[BulkToggleRow],
    ) -> (AppState, Vec<TuiCommand>) {
        let changes = rows
            .iter()
            .map(|(id, _, _, _)| create_test_change(id, 0, 1))
            .collect();
        let mut app = AppState::new(changes);
        app.execution_mode = mode;
        for (index, (_, status, parallel_eligible, selected)) in rows.iter().enumerate() {
            app.changes[index].display_status_cache = status.to_string();
            app.changes[index].parallel_eligibility = if *parallel_eligible {
                ParallelEligibility::Eligible
            } else {
                ParallelEligibility::UncommittedProposalFiles
            };
            app.changes[index].selected = *selected;
        }

        let commands = app.toggle_all_marks();
        (app, commands)
    }

    /// One table-driven bulk toggle regression case.
    struct BulkToggleCase {
        name: &'static str,
        mode: AppExecutionMode,
        rows: Vec<BulkToggleRow>,
        /// Expected `selected` flag for each row after the toggle.
        expected: Vec<bool>,
    }

    #[test]
    fn test_toggle_all_marks_mixed_eligible_and_ineligible_leaves_no_partial_eligible_rows() {
        let cases = vec![
            BulkToggleCase {
                name: "select mode marks every eligible row alongside a rejected row",
                mode: AppExecutionMode::Select,
                rows: vec![
                    ("eligible-marked", "not queued", true, true),
                    ("eligible-unmarked", "not queued", true, false),
                    ("rejected", "rejected", true, false),
                ],
                expected: vec![true, true, false],
            },
            BulkToggleCase {
                name: "select mode unmarks every eligible row when all are marked",
                mode: AppExecutionMode::Select,
                rows: vec![
                    ("eligible-a", "not queued", true, true),
                    ("eligible-b", "not queued", true, true),
                    ("rejected", "rejected", true, false),
                ],
                expected: vec![false, false, false],
            },
            BulkToggleCase {
                name: "stopped mode marks every eligible row alongside a rejected row",
                mode: AppExecutionMode::Stopped,
                rows: vec![
                    ("eligible-marked", "merge wait", true, true),
                    ("eligible-unmarked", "not queued", true, false),
                    ("rejected", "rejected", true, false),
                ],
                expected: vec![true, true, false],
            },
            BulkToggleCase {
                name: "running mode marks the active row too: a mark is next-run intent",
                mode: AppExecutionMode::Running,
                rows: vec![
                    ("active", "applying", true, false),
                    ("eligible-marked", "merge wait", true, true),
                    ("eligible-unmarked", "not queued", true, false),
                    ("rejected", "rejected", true, false),
                ],
                expected: vec![true, true, true, false],
            },
            BulkToggleCase {
                name: "an uncommitted row is marked: worktree eligibility is a start-time fact",
                mode: AppExecutionMode::Select,
                rows: vec![
                    ("committed-marked", "not queued", true, true),
                    ("committed-unmarked", "not queued", true, false),
                    ("uncommitted", "not queued", false, false),
                ],
                expected: vec![true, true, true],
            },
        ];

        for case in cases {
            let (app, _) = run_bulk_toggle_case(case.mode, &case.rows);

            let actual: Vec<bool> = app.changes.iter().map(|change| change.selected).collect();
            assert_eq!(actual, case.expected, "case failed: {}", case.name);
            assert!(
                app.logs
                    .iter()
                    .any(|entry| entry.message.contains("Toggled all")),
                "case must report a bulk toggle result: {}",
                case.name
            );
        }
    }

    /// The bulk toggle reports what it marked, and nothing else.
    ///
    /// A terminal row is skipped silently: excluding a change that has no next
    /// run refuses nothing the operator asked for, so naming it as an exclusion
    /// would describe a constraint that does not exist. And because a mark is
    /// pure intent, no queue command leaves with it.
    #[test]
    fn test_toggle_all_marks_reports_the_marked_count_without_queue_effects() {
        let (app, commands) = run_bulk_toggle_case(
            AppExecutionMode::Running,
            &[
                ("active", "applying", true, false),
                ("rejected", "rejected", true, false),
                ("eligible", "not queued", true, false),
            ],
        );

        assert!(
            commands.is_empty(),
            "a bulk mark emits no queue command: {commands:?}"
        );
        assert!(app.changes[0].selected, "an active row accepts mark intent");
        assert!(!app.changes[1].selected, "a terminal row is not a target");
        assert!(app.changes[2].selected);

        assert!(
            app.warning_message.is_none(),
            "a skipped terminal row is not a refusal: {:?}",
            app.warning_message
        );
        assert!(
            app.logs
                .iter()
                .any(|entry| entry.message == "Toggled all: 2 marked change(s)"),
            "the bulk toggle result must be logged: {:?}",
            app.logs.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_toggle_all_marks_without_exclusions_does_not_warn() {
        let (app, _) = run_bulk_toggle_case(
            AppExecutionMode::Select,
            &[
                ("a", "not queued", true, false),
                ("b", "not queued", true, false),
            ],
        );

        assert!(app.warning_message.is_none());
        assert!(app
            .logs
            .iter()
            .any(|entry| entry.message == "Toggled all: 2 marked change(s)"));
    }

    /// A list holding only terminal rows is a silent no-op.
    ///
    /// There is no run candidate left to express intent about, so there is
    /// nothing to warn about either. The retained marks stay exactly as the
    /// reconciler left them.
    #[test]
    fn test_toggle_all_marks_with_only_terminal_rows_is_silent() {
        let (app, commands) = run_bulk_toggle_case(
            AppExecutionMode::Running,
            &[
                ("archived", "archived", true, false),
                ("rejected", "rejected", true, true),
            ],
        );

        assert!(commands.is_empty());
        assert!(!app.changes[0].selected, "terminal rows must not change");
        assert!(app.changes[1].selected, "terminal rows must not change");

        assert!(
            app.warning_message.is_none(),
            "a terminal-only list refuses nothing: {:?}",
            app.warning_message
        );
        assert!(
            !app.logs
                .iter()
                .any(|entry| entry.message.contains("Toggled all")),
            "nothing was toggled, so nothing is reported"
        );
    }

    #[test]
    fn test_toggle_all_marks_with_no_changes_reports_reason() {
        let mut app = AppState::new(Vec::new());
        app.execution_mode = AppExecutionMode::Select;

        let commands = app.toggle_all_marks();

        assert!(commands.is_empty());
        assert!(app
            .warning_message
            .as_ref()
            .is_some_and(|msg| msg.contains("no changes to toggle")));
    }

    /// Every execution mode admits the bulk toggle now: a pending stop and an
    /// error hold gate *dispatch*, never the operator's next-run intent.
    #[test]
    fn bulk_mark_is_admitted_in_every_execution_mode() {
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Running,
            AppExecutionMode::Stopping,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            let (app, commands) = run_bulk_toggle_case(mode, &[("a", "error", true, false)]);

            assert!(commands.is_empty(), "{mode:?} must emit no queue command");
            assert!(app.changes[0].selected, "{mode:?} must mark the row");
            assert!(
                app.warning_message.is_none(),
                "{mode:?} must not refuse the bulk mark: {:?}",
                app.warning_message
            );
        }
    }

    #[test]
    fn bulk_mark_targets_are_derived_from_visible_non_terminal_rows() {
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Running,
            AppExecutionMode::Stopping,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            let mut app = AppState::new(vec![create_test_change("a", 0, 1)]);
            app.execution_mode = mode;
            assert!(
                app.has_bulk_toggle_targets(),
                "{mode:?} must offer the bulk toggle for a non-terminal row"
            );

            app.changes[0].set_display_status_cache("archived");
            assert!(
                !app.has_bulk_toggle_targets(),
                "{mode:?} must not offer the bulk toggle for terminal rows only"
            );
        }
    }

    #[test]
    fn bulk_mark_requires_changes_view_without_an_overlay() {
        let mut app = AppState::new(vec![create_test_change("a", 0, 1)]);
        app.execution_mode = AppExecutionMode::Select;
        assert!(app.has_bulk_toggle_targets());

        app.view_mode = ViewMode::Worktrees;
        assert!(!app.has_bulk_toggle_targets());

        app.view_mode = ViewMode::Changes;
        app.web_url = Some("http://127.0.0.1:8080".to_string());
        app.show_qr_popup();
        assert!(!app.has_bulk_toggle_targets());
        assert!(
            app.toggle_all_marks().is_empty(),
            "an overlay owning input must not let `x` mutate marks"
        );
        assert!(!app.changes[0].selected);

        app.modal = None;
        app.show_warning_popup("warning", "diagnostic");
        assert!(!app.has_bulk_toggle_targets());
        assert!(app.toggle_all_marks().is_empty());
        assert!(!app.changes[0].selected);
    }

    #[test]
    fn test_selected_count() {
        // Changes start unselected
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);

        assert_eq!(app.selected_count(), 0);

        app.toggle_selection(); // Select first
        assert_eq!(app.selected_count(), 1);
    }

    /// Space on a Running-mode error row records retry *intent* and nothing
    /// else: the queue alias it used to carry is gone, and the retry itself is
    /// decided at final start/retry admission.
    #[test]
    fn test_running_mode_error_change_toggle_sets_retry_mark() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_error_message_cache("boom".to_string());
        app.changes[0].selected = false;

        app.toggle_selection();

        assert!(
            app.changes[0].selected,
            "Space should set retry mark on error change"
        );
        assert_eq!(app.changes[0].display_status_cache, "error");
        assert_eq!(
            app.take_pending_mark_writes(),
            vec![("test-change".to_string(), true)]
        );
        assert!(app
            .logs
            .iter()
            .any(|log| log.message.contains("Marked for execution: test-change")));

        app.toggle_selection();
        assert!(!app.changes[0].selected);
        assert_eq!(app.changes[0].display_status_cache, "error");
        assert_eq!(
            app.take_pending_mark_writes(),
            vec![("test-change".to_string(), false)]
        );
    }

    #[test]
    fn running_not_queued_toggle_survives_reducer_sync_and_changes_refreshed() {
        let changes = vec![create_test_change("dynamic-change", 0, 1)];
        let mut app = AppState::new(changes.clone());
        app.execution_mode = AppExecutionMode::Running;

        app.toggle_selection();
        assert!(app.changes[0].selected);
        // The interaction records a target-scoped write; the run loop applies it
        // through the shared service before the next event is projected.
        app.flush_pending_mark_writes();

        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "dynamic-change".to_string(),
            "queued",
        )]));
        app.handle_orchestrator_event(OrchestratorEvent::ChangesRefreshed {
            changes,
            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!(
            app.changes[0].selected,
            "execution mark must survive refresh"
        );
        assert_eq!(app.changes[0].display_status_cache, "queued");
    }

    /// Reducer `queued` is queue presentation, not an execution mark.
    ///
    /// Synthesizing a mark from queue status used to invent operator intent the
    /// shared store never recorded, which `/api/v2` then published as
    /// `execution_marked` for a change nobody marked. A queued row is unmarked
    /// until the store says otherwise, and unqueueing a *marked* queued row still
    /// takes the queue intent back out.
    #[test]
    fn reducer_queued_status_never_synthesizes_an_execution_mark() {
        let changes = vec![create_test_change("queued-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;

        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "queued-change".to_string(),
            "queued",
        )]));

        assert_eq!(app.changes[0].display_status_cache, "queued");
        assert!(
            !app.changes[0].selected,
            "queue intent must not become an execution mark"
        );
        assert!(
            app.execution_marks().marked_ids().is_empty(),
            "queue intent must not reach the shared mark store"
        );

        // An operator mark on the same row is a separate fact, and unmarking it
        // still withdraws the queue intent.
        app.execution_marks().set("queued-change", true);
        app.sync_execution_marks_from_store();
        assert!(app.changes[0].selected);

        app.toggle_selection();
        assert!(!app.changes[0].selected);
        app.flush_pending_mark_writes();
        assert!(app.execution_marks().marked_ids().is_empty());
    }

    #[test]
    fn active_status_survives_reducer_sync_and_changes_refreshed() {
        let changes = vec![create_test_change("active-change", 0, 1)];
        let mut app = AppState::new(changes.clone());
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_display_status_cache("queued");
        app.changes[0].selected = true;
        app.publish_execution_marks();

        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "active-change".to_string(),
            "applying",
        )]));
        app.handle_orchestrator_event(OrchestratorEvent::ChangesRefreshed {
            changes,
            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!(app.changes[0].display_status_cache, "applying");
        assert!(app.changes[0].selected);
    }

    #[test]
    fn test_stopped_mode_error_change_toggle_sets_retry_mark() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Stopped;
        app.changes[0].set_error_message_cache("boom".to_string());
        app.changes[0].selected = false;

        app.toggle_selection();

        assert!(
            app.changes[0].selected,
            "Space should set retry mark in stopped mode"
        );
        assert!(app
            .logs
            .iter()
            .any(|log| log.message.contains("Marked for execution: test-change")));
    }

    #[test]
    fn test_apply_display_statuses_from_reducer_updates_error_row_to_merged() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].set_error_message_cache("previous failure".to_string());
        app.changes[0].selected = true;
        assert_eq!(app.changes[0].display_status_cache, "error");

        let display_map = HashMap::from([("test-change".to_string(), "merged")]);
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(app.changes[0].display_status_cache, "merged");
        assert!(
            app.changes[0].selected,
            "only rejected rows should be forcibly deselected during reducer sync"
        );
    }

    // ------------------------------------------------------------------
    // Retained final diagnostics for error rows
    // ------------------------------------------------------------------

    /// Build a reducer holding one change that failed with `error`.
    ///
    /// The reducer is a pure in-memory state machine, so driving it with its own
    /// event is unit-scoped: no process, filesystem, VCS, or clock boundary is
    /// touched.
    fn reducer_with_failed_change(
        change_id: &str,
        error: &str,
    ) -> crate::orchestration::state::OrchestratorState {
        let mut state =
            crate::orchestration::state::OrchestratorState::new(vec![change_id.to_string()], 1);
        state.apply_execution_event(&crate::events::ExecutionEvent::ApplyFailed {
            change_id: change_id.to_string(),
            error: error.to_string(),
        });
        state
    }

    /// A direct failure event the TUI observed itself must keep the whole
    /// diagnostic, not a summary of it.
    #[test]
    fn direct_failure_events_retain_the_full_final_diagnostic() {
        let diagnostic = "Apply failed: stalled after 5 empty WIP commits";
        for (label, apply) in [
            (
                "processing error",
                Box::new(|app: &mut AppState, detail: String| {
                    app.handle_orchestrator_event(OrchestratorEvent::ProcessingError {
                        id: "test-change".to_string(),
                        error: detail,
                    })
                }) as Box<dyn Fn(&mut AppState, String)>,
            ),
            (
                "apply failed",
                Box::new(|app: &mut AppState, detail: String| {
                    app.handle_orchestrator_event(OrchestratorEvent::ApplyFailed {
                        change_id: "test-change".to_string(),
                        error: detail,
                    })
                }),
            ),
            (
                "archive failed",
                Box::new(|app: &mut AppState, detail: String| {
                    app.handle_orchestrator_event(OrchestratorEvent::ArchiveFailed {
                        change_id: "test-change".to_string(),
                        error: detail,
                        reason: None,
                        summary: None,
                    })
                }),
            ),
        ] {
            let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
            apply(&mut app, diagnostic.to_string());

            assert_eq!(app.changes[0].display_status_cache, "error", "{label}");
            assert_eq!(
                app.changes[0].error_message_cache.as_deref(),
                Some(diagnostic),
                "{label} must retain the complete diagnostic"
            );
        }
    }

    /// The reducer's retained diagnostic is what an operator reads, even when a
    /// row already cached an unrelated compatibility reason before failing.
    #[test]
    fn reducer_error_detail_replaces_a_stale_non_error_reason() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        // `ChangeSkipped` leaves a dependency note behind on the row.
        app.handle_orchestrator_event(OrchestratorEvent::ChangeSkipped {
            change_id: "test-change".to_string(),
            reason: "Dependency 'other-change' failed".to_string(),
        });
        assert_eq!(
            app.changes[0].error_message_cache.as_deref(),
            Some("Dependency 'other-change' failed")
        );

        let reducer = reducer_with_failed_change("test-change", "Apply failed: stalled");
        app.apply_display_statuses_from_reducer(&reducer.all_display_statuses());
        app.apply_error_details_from_reducer(&reducer.all_error_details());

        assert_eq!(app.changes[0].display_status_cache, "error");
        assert_eq!(
            app.changes[0].error_message_cache.as_deref(),
            Some("Apply failed: stalled"),
            "the reducer's retained failure must replace the stale skip reason"
        );
    }

    /// A row that reaches `error` only through the reducer must never show a
    /// placeholder token; it shows the retained diagnostic instead.
    #[test]
    fn reducer_only_error_row_never_resolves_to_a_placeholder() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        let reducer = reducer_with_failed_change("test-change", "Apply failed: stalled");

        app.apply_display_statuses_from_reducer(&reducer.all_display_statuses());
        app.apply_error_details_from_reducer(&reducer.all_error_details());

        assert_eq!(app.changes[0].display_status_cache, "error");
        assert_eq!(
            app.changes[0].error_message_cache.as_deref(),
            Some("Apply failed: stalled")
        );
        assert_ne!(
            app.changes[0].error_message_cache.as_deref(),
            Some("reducer")
        );
    }

    /// The diagnostic a TUI row shows and the one `/api/v2` projects are the
    /// same reducer-owned text, so an operator reading either surface reads the
    /// same failure.
    #[test]
    fn tui_error_detail_matches_the_api_projected_error_detail() {
        let reducer = reducer_with_failed_change("test-change", "Apply failed: \u{1b}[31mstalled");
        let projected = reducer
            .change_runtime("test-change")
            .and_then(crate::orchestration::state::ChangeRuntimeState::error_message)
            .map(crate::events::sanitize_detail);

        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        app.apply_display_statuses_from_reducer(&reducer.all_display_statuses());
        app.apply_error_details_from_reducer(&reducer.all_error_details());

        assert_eq!(app.changes[0].error_message_cache, projected);
    }

    /// With no reducer-retained diagnostic there is nothing to adopt; the row
    /// keeps an empty cache so rendering can state that details are unavailable.
    #[test]
    fn missing_reducer_error_detail_leaves_the_cache_empty() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "test-change".to_string(),
            "error",
        )]));
        app.apply_error_details_from_reducer(&HashMap::new());

        assert_eq!(app.changes[0].display_status_cache, "error");
        assert_eq!(app.changes[0].error_message_cache, None);
    }

    /// Leaving `error` drops the diagnostic, and a later reducer sync must not
    /// resurrect it onto the now-healthy row.
    #[test]
    fn transition_away_from_error_clears_the_retained_diagnostic() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        app.changes[0].set_error_message_cache("Apply failed: stalled".to_string());

        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "test-change".to_string(),
            "queued",
        )]));
        assert_eq!(app.changes[0].display_status_cache, "queued");
        assert_eq!(app.changes[0].error_message_cache, None);

        // A stale detail map from before the retry must not repaint the row.
        app.apply_error_details_from_reducer(&HashMap::from([(
            "test-change".to_string(),
            "Apply failed: stalled".to_string(),
        )]));
        assert_eq!(app.changes[0].error_message_cache, None);
    }

    /// A retry closes an open Error Details popup rather than leaving it
    /// describing a state the change has already left.
    #[test]
    fn leaving_error_closes_an_open_error_details_popup() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        app.changes[0].set_error_message_cache("Apply failed: stalled".to_string());
        assert!(app.open_error_details_popup());

        // Still failing: the popup survives an ordinary sync.
        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "test-change".to_string(),
            "error",
        )]));
        assert!(app.error_details_popup.is_some());

        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "test-change".to_string(),
            "queued",
        )]));
        assert!(app.error_details_popup.is_none());
    }

    /// Opening, scrolling, copying, and closing the popup are presentation only.
    #[test]
    fn error_details_popup_is_presentation_only() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        app.changes[0].set_error_message_cache("Apply failed: stalled".to_string());
        app.changes[0].selected = true;

        assert!(app.open_error_details_popup());
        app.scroll_error_details_popup(5);
        app.scroll_error_details_popup(-99);
        assert_eq!(
            app.error_details_popup.as_ref().map(|popup| popup.scroll),
            Some(0),
            "the scroll offset stays non-negative"
        );
        app.close_error_details_popup();

        assert_eq!(app.changes[0].display_status_cache, "error");
        assert!(app.changes[0].selected);
        assert_eq!(app.execution_mode, AppExecutionMode::Select);
        assert!(app.modal.is_none());
    }

    /// Only an `error` row can open the popup.
    #[test]
    fn a_non_error_row_cannot_open_the_error_details_popup() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        for status in ["not queued", "queued", "applying", "blocked", "archived"] {
            app.changes[0].set_display_status_cache(status);
            assert!(
                !app.open_error_details_popup(),
                "{status} must not open the Error Details popup"
            );
            assert!(app.error_details_popup.is_none());
        }
    }

    /// An error row with no retained diagnostic still opens, stating that the
    /// details are unavailable rather than showing an empty popup.
    #[test]
    fn error_details_popup_states_when_no_diagnostic_is_available() {
        let mut app = AppState::new(vec![create_test_change("test-change", 0, 1)]);
        app.changes[0].set_display_status_cache("error");

        assert!(app.open_error_details_popup());
        assert_eq!(
            app.error_details_popup
                .as_ref()
                .map(|popup| popup.error.as_str()),
            Some(ERROR_DETAILS_UNAVAILABLE)
        );
    }

    /// The copied text is stable by contract.
    #[test]
    fn error_details_clipboard_text_is_stable_plain_text() {
        let popup = ErrorDetailsPopup {
            change_id: "alpha".to_string(),
            error: "Apply failed: stalled".to_string(),
            scroll: 0,
            copy_feedback: None,
        };

        assert_eq!(
            popup.clipboard_text(),
            "Change: alpha\nError: Apply failed: stalled"
        );
    }

    // Iteration guard tests

    #[test]
    fn test_iteration_monotonic_update_from_none() {
        let mut change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "applying".to_string(),
            blocker_kind_cache: crate::orchestration::state::BlockerKind::None,
            blocker_detail_cache: None,
            display_color_cache: Color::Cyan,
            error_message_cache: None,
            selected: false,
            is_new: false,
            parallel_eligibility: ParallelEligibility::Eligible,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
            apply_operation_cache: "apply".to_string(),
            archive_complete_cache: false,
        };

        // First iteration should be accepted
        change.update_iteration_monotonic(Some(1));
        assert_eq!(change.iteration_number, Some(1));

        // Higher iteration should update
        change.update_iteration_monotonic(Some(2));
        assert_eq!(change.iteration_number, Some(2));
    }

    #[test]
    fn test_iteration_monotonic_prevents_regression() {
        let mut change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "applying".to_string(),
            blocker_kind_cache: crate::orchestration::state::BlockerKind::None,
            blocker_detail_cache: None,
            display_color_cache: Color::Cyan,
            error_message_cache: None,
            selected: false,
            is_new: false,
            parallel_eligibility: ParallelEligibility::Eligible,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: Some(3),
            apply_operation_cache: "apply".to_string(),
            archive_complete_cache: false,
        };

        // Lower iteration should be ignored
        change.update_iteration_monotonic(Some(1));
        assert_eq!(change.iteration_number, Some(3));

        // Same iteration should be ignored
        change.update_iteration_monotonic(Some(3));
        assert_eq!(change.iteration_number, Some(3));

        // Higher iteration should update
        change.update_iteration_monotonic(Some(5));
        assert_eq!(change.iteration_number, Some(5));
    }

    #[test]
    fn test_iteration_monotonic_ignores_none() {
        let mut change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "applying".to_string(),
            blocker_kind_cache: crate::orchestration::state::BlockerKind::None,
            blocker_detail_cache: None,
            display_color_cache: Color::Cyan,
            error_message_cache: None,
            selected: false,
            is_new: false,
            parallel_eligibility: ParallelEligibility::Eligible,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: Some(2),
            apply_operation_cache: "apply".to_string(),
            archive_complete_cache: false,
        };

        // None should be ignored
        change.update_iteration_monotonic(None);
        assert_eq!(change.iteration_number, Some(2));
    }

    #[test]
    fn test_resolve_queue_auto_start_on_completion() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Set change-a to Resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("change-a");

        // Queue change-b for resolve
        app.add_to_resolve_queue("change-b");
        app.changes[1].display_status_cache = "resolve pending".to_string();

        // Simulate resolve completion for change-a
        app.handle_resolve_completed("change-a".to_string(), None);

        // change-b is promoted in the ledger; the reducer-owned ResolveWait it
        // already carries is what the scheduler dispatches from, so promotion
        // emits no command.
        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        // is_resolving should be cleared
        assert!(!app.is_resolving());
        // Queue should be empty
        assert!(!app.has_queued_resolves());
    }

    #[test]
    fn test_resolve_queue_no_auto_start_when_queue_empty() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        // Set change-a to Resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("change-a");

        // Simulate resolve completion with empty queue
        app.handle_resolve_completed("change-a".to_string(), None);

        // is_resolving should be cleared
        assert!(!app.is_resolving());
    }

    #[test]
    fn test_resolve_completed_does_not_log_duplicate_after_merge_completed() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].display_status_cache = "merged".to_string();

        app.handle_resolve_completed("change-a".to_string(), None);

        assert!(!app
            .logs
            .iter()
            .any(|log| log.message == "Merge resolved for 'change-a'"));
    }

    // ── `M` is presentation only ────────────────────────────────────────────
    //
    // The reservation, FIFO ordering, duplicate rejection, reducer transition,
    // and scheduler dispatch all belong to the shared run-control service now —
    // that is what makes an `M` keypress and a remote `resolve_merge` reach one
    // conclusion instead of two. What `AppState` still owns is which row the
    // cursor addresses and whether the key offers a command at all, so that is
    // all these tests pin.

    #[test]
    fn m_emits_a_resolve_command_without_deciding_its_outcome() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.execution_mode = AppExecutionMode::Running;

        let cmd = app.resolve_merge();

        assert!(matches!(cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"));
        assert!(
            !app.is_resolving(),
            "the key path must not pre-empt the shared single-resolver rule"
        );
        assert!(
            !app.resolve_reservations().is_reserved("change-a"),
            "reserving here would turn the service's own reservation into a duplicate"
        );
        assert_eq!(
            app.changes[0].display_status_cache, "merge wait",
            "the row advances when the service accepts, not when the key is pressed"
        );
    }

    #[test]
    fn m_is_ignored_for_a_row_that_is_not_waiting_on_a_merge() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        app.changes[0].display_status_cache = "queued".to_string();
        app.cursor_index = 0;
        app.execution_mode = AppExecutionMode::Running;

        assert!(app.resolve_merge().is_none());
    }

    #[test]
    fn m_offers_the_same_command_in_every_mode_that_allows_it() {
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Stopped,
            AppExecutionMode::Running,
        ] {
            let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
            app.changes[0].display_status_cache = "merge wait".to_string();
            app.cursor_index = 0;
            app.execution_mode = mode;

            assert!(
                matches!(
                    app.resolve_merge(),
                    Some(TuiCommand::ResolveMerge(ref id)) if id == "change-a"
                ),
                "{mode:?} must offer resolve"
            );
        }
    }

    #[test]
    fn consecutive_m_presses_emit_one_command_per_row() {
        let mut app = AppState::new(vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ]);
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.execution_mode = AppExecutionMode::Running;

        app.cursor_index = 0;
        let first = app.resolve_merge();
        app.cursor_index = 1;
        let second = app.resolve_merge();

        assert!(matches!(first, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"));
        assert!(
            matches!(second, Some(TuiCommand::ResolveMerge(id)) if id == "change-b"),
            "the second press still reaches the service, which is what decides it queues"
        );
    }

    /// Regression test: after queuing a resolve via M key, a ChangesRefreshed event
    /// with the change still in merge_wait_ids must NOT regress ResolveWait back to MergeWait.
    #[test]
    fn test_resolve_wait_survives_changes_refreshed() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Set up shared orchestrator state.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string(), "change-b".to_string()],
            0,
        )));
        // Pre-condition: change-b is in MergeWait in the reducer.
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-b", WorkspaceObservation::WorkspaceArchived);
        }
        app.set_shared_state(shared.clone());

        // change-a is currently resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");

        // change-b is in MergeWait; user presses M to queue resolve
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.cursor_index = 1;
        app.execution_mode = AppExecutionMode::Running;

        // What the shared run-control service does when it accepts the resolve:
        // record the reducer intent, then let the adapter advance the row.
        shared.blocking_write().apply_command(
            crate::orchestration::state::ReducerCommand::ResolveMerge("change-b".to_string()),
        );
        app.changes[1].set_display_status_cache("resolve pending");

        // Simulate a ChangesRefreshed event where workspace still reports change-b
        // as Archived (which would normally set MergeWait in the reducer).
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::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: ["change-b".to_string()].into_iter().collect(),
            });
        }

        // The actual TUI path applies reducer display first, then local ChangesRefreshed handling.
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        app.handle_orchestrator_event(OrchestratorEvent::ChangesRefreshed {
            changes: vec![
                create_test_change("change-a", 0, 1),
                create_test_change("change-b", 0, 1),
            ],
            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: ["change-b".to_string()].into_iter().collect(),
        });

        assert_eq!(
            app.changes[1].display_status_cache, "resolve pending",
            "ResolveWait must survive reducer sync followed by ChangesRefreshed handling"
        );
    }

    /// Regression test: after immediate resolve (is_resolving == false), a ChangesRefreshed
    /// event with the change still in merge_wait_ids must NOT regress ResolveWait back to
    /// MergeWait.
    #[test]
    fn test_resolve_wait_survives_changes_refreshed_after_immediate_resolve() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        // Set up shared orchestrator state.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        // Pre-condition: change-a is in MergeWait in the reducer.
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-a", WorkspaceObservation::WorkspaceArchived);
        }
        app.set_shared_state(shared.clone());

        // change-a is in MergeWait, no resolve in progress; user presses M
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.execution_mode = AppExecutionMode::Running;
        app.clear_resolving();

        // What the shared run-control service does when it accepts the resolve.
        shared.blocking_write().apply_command(
            crate::orchestration::state::ReducerCommand::ResolveMerge("change-a".to_string()),
        );
        app.changes[0].set_display_status_cache("resolve pending");

        // Simulate a ChangesRefreshed event where workspace still reports change-a
        // as needing merge (which would normally set MergeWait in the reducer).
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::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: ["change-a".to_string()].into_iter().collect(),
            });
        }

        // The actual TUI path applies reducer display first, then local ChangesRefreshed handling.
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        app.handle_orchestrator_event(OrchestratorEvent::ChangesRefreshed {
            changes: vec![create_test_change("change-a", 0, 1)],
            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: ["change-a".to_string()].into_iter().collect(),
        });

        assert_eq!(
            app.changes[0].display_status_cache, "resolve pending",
            "ResolveWait must survive reducer sync followed by ChangesRefreshed handling after immediate resolve"
        );
    }

    #[test]
    fn test_handle_orchestrator_event_merge_completed_promotes_queued_resolve() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.set_resolving("__active__");
        app.changes[0].display_status_cache = "resolving".to_string();
        app.changes[1].display_status_cache = "resolve pending".to_string();
        app.add_to_resolve_queue("change-b");

        // The promoted change is dispatched from the reducer-owned ResolveWait it
        // already holds, so the event path emits no command for it: a
        // re-submission could only be refused as no longer `merge wait`.
        app.handle_orchestrator_event(OrchestratorEvent::MergeCompleted {
            change_id: "change-a".to_string(),
            revision: "abc123".to_string(),
        });

        assert!(!app.is_resolving());
        assert!(app.queued_resolves().is_empty());
        assert!(app.warning_message.is_none());
        assert_eq!(app.changes[0].display_status_cache, "merged");
        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
    }

    /// Regression: reducer-driven display must not demote a Merged change to MergeWait.
    #[test]
    fn test_apply_merge_wait_status_does_not_demote_merged() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        // Simulate that the change has already reached Merged state.
        app.changes[0].display_status_cache = "merged".to_string();

        // The reducer display map says "merged" → TUI must keep Merged.
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "merged");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "merged",
            "reducer-driven display must not demote a Merged change to MergeWait"
        );
    }

    /// Regression: reducer-driven display must not demote a Blocked change to MergeWait.
    #[test]
    fn test_apply_merge_wait_status_does_not_demote_blocked() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        // The reducer display map says "blocked".
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "blocked");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "blocked",
            "reducer-driven display must not demote a Blocked change to MergeWait"
        );
    }

    #[test]
    fn test_apply_display_statuses_keeps_rejected_row_read_only() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "rejected".to_string();
        app.changes[0].selected = true;
        app.publish_execution_marks();

        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "not queued");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "rejected",
            "rejected row must stay immutable during reducer display sync"
        );
        assert!(
            app.changes[0].selected,
            "a display-status sync must not decide mark truth; only the shared store does"
        );

        // The authoritative revocation is what clears it, and the row follows.
        app.execution_marks().set("change-a", false);
        app.sync_execution_marks_from_store();
        assert!(!app.changes[0].selected);
    }

    /// Verification `net-execution-time-tests`: a retained accumulated duration
    /// is execution-history evidence in its own right, so a row that already
    /// closed its interval survives a temporary catalog absence exactly as a
    /// still-running one does.
    #[test]
    fn net_execution_time_catalog_refresh_retains_an_inactive_row_with_retained_time() {
        let mut app = AppState::new(vec![create_test_change("change-a", 1, 1)]);
        app.changes[0].set_display_status_cache("applying");
        app.changes[0].set_display_status_cache("not queued");
        let retained = app.changes[0].elapsed_time.expect("closed interval");
        assert_eq!(app.changes[0].started_at, None);

        // The change is absent from this snapshot while its worktree is
        // refreshed; nothing else keeps the row alive.
        app.update_changes_with_rejected_for_test(Vec::new(), Vec::new());

        let row = app
            .changes
            .iter()
            .find(|c| c.id == "change-a")
            .expect("row with retained execution time must survive a temporary absence");
        assert_eq!(row.elapsed_time, Some(retained));
        assert!(app.known_change_ids.contains("change-a"));
    }

    /// A row that never executed still drops out of an absent snapshot: the
    /// retention rule is execution evidence, not a blanket keep-everything.
    #[test]
    fn net_execution_time_catalog_refresh_still_drops_a_row_that_never_executed() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        assert!(!app.changes[0].has_execution_history());

        app.update_changes_with_rejected_for_test(Vec::new(), Vec::new());

        assert!(app.changes.iter().all(|c| c.id != "change-a"));
    }

    #[test]
    fn test_update_changes_reactivates_rejected_row_when_marker_removed() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes.clone());
        app.changes[0].display_status_cache = "rejected".to_string();

        app.update_changes_with_rejected_for_test(changes, Vec::new());

        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "active refresh without marker should reactivate rejected row"
        );
        assert!(
            !app.changes[0].selected,
            "reactivated row must remain unselected until explicit user action"
        );
        assert!(
            app.execution_marks().marked_ids().is_empty(),
            "reactivation must not invent operator intent"
        );
    }

    #[test]
    fn test_update_changes_new_rejected_row_is_not_new_and_not_counted() {
        let mut app = AppState::new(vec![]);

        let rejected = create_test_change("change-rejected", 0, 1);
        app.update_changes_with_rejected_for_test(vec![], vec![rejected]);

        let row = app
            .changes
            .iter()
            .find(|c| c.id == "change-rejected")
            .expect("rejected row should be added");
        assert_eq!(row.display_status_cache, "rejected");
        assert!(
            !row.is_new,
            "newly surfaced rejected row must not carry NEW badge"
        );
        assert_eq!(
            app.new_change_count, 0,
            "rejected rows must not increment NEW counter"
        );
    }

    #[test]
    fn test_toggle_selection_ignores_rejected_row_silently() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].display_status_cache = "rejected".to_string();
        app.execution_mode = AppExecutionMode::Select;

        app.toggle_selection();

        assert!(
            !app.changes[0].selected,
            "rejected row must remain unselected"
        );
        assert!(
            app.take_pending_mark_writes().is_empty(),
            "rejected row must queue no mark write"
        );
        assert!(
            app.warning_message.is_none(),
            "a terminal row is a silent no-op, not a refusal: {:?}",
            app.warning_message
        );
    }

    #[test]
    fn test_toggle_all_marks_ignores_rejected_rows() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Select;
        app.changes[0].display_status_cache = "rejected".to_string();
        app.changes[1].display_status_cache = "not queued".to_string();

        let _ = app.toggle_all_marks();

        assert!(
            !app.changes[0].selected,
            "bulk mark (@) must not mark rejected rows"
        );
        assert!(
            app.changes[1].selected,
            "eligible rows should still be marked"
        );
    }

    /// A rejection clears the mark through the authoritative store, not through
    /// the display-status sync.
    ///
    /// The sync is presentation: it renders the reducer's word for the row. The
    /// mark it renders alongside comes from `ExecutionMarkStore`, which the
    /// dispatch boundary already reconciled for the same rejection event.
    #[test]
    fn test_apply_display_statuses_rejected_follows_the_shared_mark_store() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.publish_execution_marks();

        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "rejected");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(app.changes[0].display_status_cache, "rejected");

        app.execution_marks().set("change-a", false);
        app.sync_execution_marks_from_store();
        assert!(
            !app.changes[0].selected,
            "rejected terminal row must not keep execution mark"
        );
    }

    /// Regression: reducer-driven display must not affect a Merged change via merge_wait.
    #[test]
    fn test_auto_clear_merge_wait_does_not_affect_merged() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        // The reducer display map says "merged" — TUI keeps Merged.
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "merged");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "merged",
            "reducer-driven display must not transition a Merged change away from Merged"
        );
    }

    // -----------------------------------------------------------------------
    // Phase 6.1: TUI uses reducer display_status (apply_display_statuses_from_reducer)
    // -----------------------------------------------------------------------

    #[test]
    fn test_tui_uses_reducer_display_status() {
        use std::collections::HashMap;

        let changes = vec![
            create_test_change("c1", 0, 3),
            create_test_change("c2", 0, 3),
        ];
        let mut app = AppState::new(changes);

        // Simulate reducer snapshot with various statuses.
        let mut display_map: HashMap<String, &'static str> = HashMap::new();
        display_map.insert("c1".to_string(), "applying");
        display_map.insert("c2".to_string(), "merge wait");

        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(app.changes[0].display_status_cache, "applying");
        assert_eq!(app.changes[1].display_status_cache, "merge wait");

        // Verify active classification works correctly.
        assert!(matches!(
            app.changes[0].display_status_cache.as_str(),
            "applying"
        ));
    }

    // -----------------------------------------------------------------------
    // Phase 6.4: TUI and Web display vocabulary consistency
    // -----------------------------------------------------------------------

    #[test]
    fn test_display_status_consistency_between_tui_and_web() {
        use std::collections::HashMap;

        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);

        // Scenarios: dependency blocked, merge wait, resolving.
        let scenarios: &[(&str, &str)] = &[
            ("blocked", "blocked"),
            ("merge wait", "merge wait"),
            ("resolve pending", "resolve pending"),
            ("resolving", "resolving"),
            ("archived", "archived"),
            ("merged", "merged"),
            ("queued", "queued"),
            ("not queued", "not queued"),
        ];

        for (reducer_str, expected_tui_status) in scenarios {
            let mut display_map: HashMap<String, &'static str> = HashMap::new();
            display_map.insert("c1".to_string(), reducer_str);
            app.apply_display_statuses_from_reducer(&display_map);

            assert_eq!(
                app.changes[0].display_status_cache, *expected_tui_status,
                "reducer '{}' should map to {:?}",
                reducer_str, expected_tui_status
            );
        }
    }

    // -----------------------------------------------------------------------
    // Phase 3.3: toggle_selection in Running mode emits commands without
    // mutating display_status_cache locally.
    // -----------------------------------------------------------------------

    #[test]
    fn test_running_mode_toggle_writes_marks_without_local_status_mutation() {
        let changes = vec![
            create_test_change("c1", 0, 3),
            create_test_change("c2", 0, 3),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;

        // Simulate c1 in NotQueued state.
        app.changes[0].display_status_cache = "not queued".to_string();

        // toggle_selection writes only the mark; no queue command is produced.
        app.toggle_selection();
        assert!(app.changes[0].selected);
        assert_eq!(
            app.take_pending_mark_writes(),
            vec![("c1".to_string(), true)]
        );
        // display_status_cache must NOT have been locally changed to Queued.
        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "display_status_cache must NOT be mutated locally; reducer drives it"
        );

        // Simulate c2 already Queued.
        app.cursor_index = 1;
        app.changes[1].display_status_cache = "queued".to_string();
        app.changes[1].selected = true;
        app.toggle_selection();
        assert!(!app.changes[1].selected);
        assert_eq!(
            app.take_pending_mark_writes(),
            vec![("c2".to_string(), false)]
        );
        // display_status_cache must NOT have been locally changed to NotQueued.
        assert_eq!(
            app.changes[1].display_status_cache, "queued",
            "display_status_cache must NOT be mutated locally; reducer drives it"
        );
    }

    // -----------------------------------------------------------------------
    // Force-kill: Space on active change must NOT trigger stop
    // -----------------------------------------------------------------------

    #[test]
    fn test_running_mode_space_on_active_change_does_not_stop() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "applying".to_string();

        app.toggle_selection();
        assert!(
            app.changes[0].selected,
            "Space on an active change records next-run intent"
        );
        assert_eq!(
            app.changes[0].display_status_cache, "applying",
            "Space on an active change must not stop or move it"
        );
    }

    #[test]
    fn test_running_mode_space_on_accepting_does_not_stop() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "accepting".to_string();

        app.toggle_selection();
        assert!(
            app.changes[0].selected,
            "Space on an accepting change records next-run intent"
        );
        assert_eq!(
            app.changes[0].display_status_cache, "accepting",
            "Space on an accepting change must not stop or move it"
        );
    }

    // -----------------------------------------------------------------------
    // Phase 3.4: MergeWait / ResolveWait Space and M key behaviour
    // -----------------------------------------------------------------------

    #[test]
    fn test_merge_wait_queue_operations() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "merge wait".to_string();

        // Space on MergeWait toggles the execution mark only.
        app.toggle_selection();
        assert!(app.changes[0].selected);
        // display_status_cache must still be MergeWait.
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
    }

    #[test]
    fn test_resolve_wait_queue_operations() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "resolve pending".to_string();

        // Space on ResolveWait toggles the execution mark only.
        app.toggle_selection();
        assert!(app.changes[0].selected);
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
    }

    // -----------------------------------------------------------------------
    // Fix: parallel TUI queued/blocked state regression
    // -----------------------------------------------------------------------

    #[test]
    fn test_apply_display_statuses_from_reducer_shows_reject_pending() {
        let changes = vec![create_test_change("reject-b", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].display_status_cache = "queued".to_string();

        let mut display_map = std::collections::HashMap::new();
        display_map.insert("reject-b".to_string(), "reject pending");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(app.changes[0].display_status_cache, "reject pending");
    }

    /// After start_processing, the reducer snapshot must preserve Queued through an
    /// initial parallel ChangesRefreshed display sync (startup refresh regression).
    #[test]
    fn test_parallel_start_refresh_preserves_queued_rows() {
        use crate::orchestration::state::OrchestratorState;
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.changes[0].parallel_eligibility = ParallelEligibility::Eligible;

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // The start path queues the change in the reducer and the row cache.
        shared.blocking_write().apply_command(
            crate::orchestration::state::ReducerCommand::AddToQueue("change-a".to_string()),
        );
        app.begin_run(&["change-a".to_string()]);
        assert_eq!(app.changes[0].display_status_cache, "queued");

        // Simulate initial parallel ChangesRefreshed (workspace scan returns nothing special).
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::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(),
            });
        }

        // Display sync from the reducer must keep the row as Queued.
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "initial parallel ChangesRefreshed must not regress a queued row to not-queued"
        );
    }

    /// Regression: after run_orchestrator_parallel resets shared state with with_mode(), it must
    /// re-apply AddToQueue so that the subsequent ChangesRefreshed display sync does not regress
    /// the TUI's Queued rows back to NotQueued.
    #[test]
    fn test_parallel_start_state_reset_preserves_queued_rows() {
        use crate::orchestration::state::{OrchestratorState, ReducerCommand};
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.changes[0].parallel_eligibility = ParallelEligibility::Eligible;

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // The start path queues the change in the reducer and the row cache.
        shared
            .blocking_write()
            .apply_command(ReducerCommand::AddToQueue("change-a".to_string()));
        app.begin_run(&["change-a".to_string()]);
        assert_eq!(app.changes[0].display_status_cache, "queued");

        // Simulate run_orchestrator_parallel replacing shared state (the regression source).
        // Without the fix this would clear queue_intent back to NotQueued.
        {
            let mut guard = shared.blocking_write();
            *guard = OrchestratorState::new(vec!["change-a".to_string()], 0);
            // The fix: re-apply AddToQueue after the state reset.
            guard.apply_command(ReducerCommand::AddToQueue("change-a".to_string()));
        }

        // Simulate the initial ChangesRefreshed that fires at parallel startup.
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::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(),
            });
        }

        // Display sync from the reducer must keep the row as Queued.
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "state reset followed by AddToQueue must preserve Queued through ChangesRefreshed"
        );
    }

    /// DependencyBlocked sets Blocked in both TUI and reducer; DependencyResolved restores
    /// Queued display because the reducer still holds queue_intent = Queued.
    #[test]
    fn test_dependency_block_preserves_queued_intent() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // Simulate the start path (queues change in both TUI and reducer).
        app.changes[0].selected = true;
        app.changes[0].parallel_eligibility = ParallelEligibility::Eligible;
        shared.blocking_write().apply_command(
            crate::orchestration::state::ReducerCommand::AddToQueue("change-a".to_string()),
        );
        app.begin_run(&["change-a".to_string()]);

        // Verify reducer has queued intent.
        assert_eq!(shared.blocking_read().display_status("change-a"), "queued");

        // Dependency block arrives.
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::DependencyBlocked {
                change_id: "change-a".to_string(),
                dependency_ids: vec!["dep".to_string()],
            });
        }
        // Reducer should show "blocked"; queue_intent is still Queued underneath.
        assert_eq!(shared.blocking_read().display_status("change-a"), "blocked");
    }

    /// After DependencyResolved the reducer restores "queued" display because queue_intent
    /// was never cleared during the block.
    #[test]
    fn test_dependency_resolved_restores_queued_display() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        app.changes[0].selected = true;
        app.changes[0].parallel_eligibility = ParallelEligibility::Eligible;
        shared.blocking_write().apply_command(
            crate::orchestration::state::ReducerCommand::AddToQueue("change-a".to_string()),
        );
        app.begin_run(&["change-a".to_string()]);

        // Block then resolve.
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::DependencyBlocked {
                change_id: "change-a".to_string(),
                dependency_ids: vec!["dep".to_string()],
            });
            guard.apply_execution_event(&crate::events::ExecutionEvent::DependencyResolved {
                change_id: "change-a".to_string(),
            });
        }

        // After resolution, reducer must report "queued" (not "not queued").
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "dependency resolution must restore queued display, not not-queued"
        );
    }

    /// Duplicate DependencyBlocked/DependencyResolved events should not spam user-visible TUI logs
    /// when the display state has not changed.
    #[test]
    fn test_duplicate_dependency_events_are_tui_log_noops() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.handle_dependency_blocked("change-a".to_string());
        app.handle_dependency_blocked("change-a".to_string());
        assert_eq!(app.changes[0].display_status_cache, "blocked");
        assert_eq!(
            app.logs
                .iter()
                .filter(|log| log.message.contains("blocked by dependencies"))
                .count(),
            1,
            "duplicate blocked event should not append a duplicate log"
        );

        app.handle_dependency_resolved("change-a".to_string());
        app.handle_dependency_resolved("change-a".to_string());
        assert_eq!(app.changes[0].display_status_cache, "queued");
        assert_eq!(
            app.logs
                .iter()
                .filter(|log| log.message.contains("dependencies resolved"))
                .count(),
            1,
            "duplicate resolved event should not append a duplicate log"
        );

        app.handle_dependency_blocked("change-a".to_string());
        assert_eq!(
            app.logs
                .iter()
                .filter(|log| log.message.contains("blocked by dependencies"))
                .count(),
            2,
            "real resolved -> blocked transition should still append a new log"
        );
    }

    /// ParallelStartRejected must also clear the reducer queue intent so subsequent
    /// ChangesRefreshed display syncs don't re-queue the rejected row.
    #[test]
    fn test_parallel_start_rejected_does_not_clear_other_rows() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string(), "change-b".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // Queue both changes in reducer.
        {
            let mut guard = shared.blocking_write();
            guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
                "change-a".to_string(),
            ));
            guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
                "change-b".to_string(),
            ));
        }
        app.changes[0].display_status_cache = "queued".to_string();
        app.changes[1].display_status_cache = "queued".to_string();
        app.execution_mode = AppExecutionMode::Running;

        // Backend rejects only change-a.
        app.handle_orchestrator_event(OrchestratorEvent::ParallelStartRejected {
            change_ids: vec!["change-a".to_string()],
            reason: "uncommitted".to_string(),
        });

        // change-a must be reset in both TUI and reducer.
        assert_eq!(app.changes[0].display_status_cache, "not queued");
        assert_eq!(
            shared.blocking_read().display_status("change-a"),
            "not queued",
            "reducer must clear queue intent for rejected change-a"
        );

        // change-b must remain Queued in both TUI and reducer.
        assert_eq!(app.changes[1].display_status_cache, "queued");
        assert_eq!(
            shared.blocking_read().display_status("change-b"),
            "queued",
            "reducer must not touch change-b which was not rejected"
        );
    }

    // -----------------------------------------------------------------------
    // Resolving mode transition tests (fix-resolving-mode-transition)
    // -----------------------------------------------------------------------

    #[test]
    fn test_all_completed_transitions_to_select_even_when_resolving() {
        // Scheduler側でResolveWaitを管理するため、TUI側のhandle_all_completedは
        // Resolving changeがある場合でも即座にSelectに遷移する。
        let changes = vec![
            create_test_change("change-a", 3, 3),
            create_test_change("change-b", 2, 4),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "resolving".to_string();

        app.handle_all_completed();

        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Select,
            "Should transition to Select because scheduler manages ResolveWait"
        );
    }

    #[test]
    fn test_resolve_completed_transitions_to_select_when_no_active() {
        // After the last Resolving change completes and no other active changes remain,
        // the mode should transition to Select.
        let changes = vec![
            create_test_change("change-a", 3, 3),
            create_test_change("change-b", 2, 4),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "merged".to_string(); // already done
        app.changes[1].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");

        // Simulate resolve completion
        app.handle_resolve_completed("change-b".to_string(), None);

        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Select,
            "Should transition to Select when no active changes remain after resolve"
        );
    }

    #[test]
    fn test_resolve_completed_stays_running_when_other_active() {
        // If another change is still active (e.g. Applying), mode stays Running.
        let changes = vec![
            create_test_change("change-a", 1, 3),
            create_test_change("change-b", 2, 4),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "applying".to_string(); // still active
        app.changes[1].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");

        app.handle_resolve_completed("change-b".to_string(), None);

        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "Should stay Running when other active changes remain"
        );
    }

    // ========================================================================
    // Execution / modal state separation
    // ========================================================================

    const ALL_EXECUTION_MODES: [AppExecutionMode; 5] = [
        AppExecutionMode::Select,
        AppExecutionMode::Running,
        AppExecutionMode::Stopping,
        AppExecutionMode::Stopped,
        AppExecutionMode::Error,
    ];

    fn modal_app() -> AppState {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        app.web_url = Some("http://127.0.0.1:8080".to_string());
        app.worktrees = vec![create_test_worktree("/tmp/wt-a", "change-a", false)];
        app
    }

    #[test]
    fn new_state_starts_in_select_execution_with_no_modal() {
        let app = AppState::new(vec![create_test_change("change-a", 0, 1)]);

        assert_eq!(app.execution_mode, AppExecutionMode::Select);
        assert_eq!(app.modal, None);
        assert!(!app.has_overlay());
    }

    #[test]
    fn qr_round_trip_preserves_the_execution_mode_it_opened_over() {
        for mode in ALL_EXECUTION_MODES {
            let mut app = modal_app();
            app.execution_mode = mode;

            app.show_qr_popup();
            assert_eq!(app.modal, Some(ModalState::QrPopup));
            assert_eq!(
                app.execution_mode, mode,
                "opening QR must not capture or replace the execution mode"
            );

            app.hide_qr_popup();
            assert_eq!(app.modal, None);
            assert_eq!(
                app.execution_mode, mode,
                "closing QR must not restore a captured execution mode"
            );
        }
    }

    #[test]
    fn qr_survives_a_background_execution_transition_and_exposes_the_latest_mode() {
        let mut app = modal_app();
        app.execution_mode = AppExecutionMode::Running;
        app.show_qr_popup();

        for mode in [
            AppExecutionMode::Stopping,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            app.execution_mode = mode;
            assert_eq!(app.revalidate_modal(), None);
            assert_eq!(app.modal, Some(ModalState::QrPopup));
        }

        app.hide_qr_popup();
        assert_eq!(app.execution_mode, AppExecutionMode::Error);
    }

    #[test]
    fn qr_is_not_opened_while_web_monitoring_is_disabled() {
        let mut app = modal_app();
        app.web_url = None;

        app.show_qr_popup();

        assert_eq!(app.modal, None);
        assert_eq!(app.execution_mode, AppExecutionMode::Select);
    }

    #[test]
    fn worktree_confirmation_carries_the_identity_it_was_opened_with() {
        let mut app = modal_app();
        app.view_mode = ViewMode::Worktrees;

        assert!(app.request_worktree_delete_from_list().is_none());

        assert_eq!(
            app.modal,
            Some(ModalState::ConfirmWorktreeDelete {
                path: PathBuf::from("/tmp/wt-a"),
                branch: "change-a".to_string(),
            })
        );
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Select,
            "opening a confirmation must not move the execution axis"
        );
    }

    #[test]
    fn cancelling_a_confirmation_leaves_the_latest_execution_mode_in_place() {
        let mut app = modal_app();
        app.view_mode = ViewMode::Worktrees;
        app.request_worktree_delete_from_list();

        // A background transition lands while the confirmation is visible.
        app.execution_mode = AppExecutionMode::Stopping;
        app.cancel_worktree_action();

        assert_eq!(app.modal, None);
        assert_eq!(app.execution_mode, AppExecutionMode::Stopping);
    }

    #[test]
    fn a_stale_worktree_confirmation_is_refused_and_cleared_atomically() {
        let mut app = modal_app();
        app.view_mode = ViewMode::Worktrees;
        app.request_worktree_delete_from_list();

        // The path now carries a different branch identity.
        app.worktrees[0].branch = "change-z".to_string();

        assert!(app.confirm_worktree_action_delete().is_none());
        assert_eq!(app.modal, None, "modal and payload are cleared together");
        assert!(!app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")));
        assert!(app
            .warning_message
            .as_ref()
            .is_some_and(|msg| msg.contains("Worktree delete canceled")));
    }

    #[test]
    fn force_kill_confirmation_opens_only_for_active_work_in_running_execution() {
        // Not Running: no confirmation.
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Stopping,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            let mut app = modal_app();
            app.execution_mode = mode;
            app.changes[0].set_display_status_cache("applying");
            assert!(!app.request_force_kill_confirmation(), "{mode:?}");
            assert_eq!(app.modal, None);
        }

        // Running but the row is not active: no confirmation.
        let mut idle = modal_app();
        idle.execution_mode = AppExecutionMode::Running;
        assert!(!idle.request_force_kill_confirmation());
        assert_eq!(idle.modal, None);

        // Running with active work: confirmation carries the target identity.
        let mut active = modal_app();
        active.execution_mode = AppExecutionMode::Running;
        active.changes[0].set_display_status_cache("applying");
        assert!(active.request_force_kill_confirmation());
        assert_eq!(
            active.modal,
            Some(ModalState::ConfirmForceKill {
                change_id: "change-a".to_string()
            })
        );
        assert_eq!(active.execution_mode, AppExecutionMode::Running);
    }

    #[test]
    fn force_kill_survives_running_to_stopping_and_cancel_preserves_stopping() {
        let mut app = modal_app();
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_display_status_cache("applying");
        app.request_force_kill_confirmation();

        app.execution_mode = AppExecutionMode::Stopping;
        assert_eq!(app.revalidate_modal(), None);
        assert!(app.modal.is_some());

        app.cancel_force_kill();
        assert_eq!(app.modal, None);
        assert_eq!(app.execution_mode, AppExecutionMode::Stopping);
    }

    #[test]
    fn revalidation_never_mutates_execution_state() {
        for mode in ALL_EXECUTION_MODES {
            let mut app = modal_app();
            app.execution_mode = mode;
            app.modal = Some(ModalState::ConfirmForceKill {
                change_id: "gone".to_string(),
            });

            app.revalidate_modal();

            assert_eq!(app.modal, None);
            assert_eq!(
                app.execution_mode, mode,
                "clearing an invalid modal must leave execution untouched"
            );
        }
    }

    /// The shared projection — not a scheduler judgement of its own — is what
    /// makes a dependency wait render as `[blocked:dependency]`.
    ///
    /// Unit scope: the reducer is in-memory and the badge is a pure function of
    /// the display status and blocker kind the TUI adopts from it, so nothing
    /// here touches Git, the filesystem, a process, or a clock.
    #[test]
    fn dependency_blocker_projection_tui_badge() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![
            create_test_change("dependency-wait", 0, 1),
            create_test_change("capacity-wait", 0, 1),
        ];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["dependency-wait".to_string(), "capacity-wait".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        {
            let mut guard = shared.blocking_write();
            guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
                "dependency-wait".to_string(),
            ));
            guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
                "capacity-wait".to_string(),
            ));
            // Exactly the reconciliation the scheduler performs on every
            // coherent classification. The TUI reads the result; it never
            // re-derives dependency eligibility itself.
            guard.reconcile_dependency_blocker("dependency-wait", &["alpha".to_string()]);
        }

        let (display_map, blocker_views) = {
            let guard = shared.blocking_read();
            (guard.all_display_statuses(), guard.all_blocker_views())
        };
        app.apply_display_statuses_from_reducer(&display_map);
        app.apply_blocker_views_from_reducer(&blocker_views);

        fn badge(app: &AppState, id: &str) -> String {
            app.changes
                .iter()
                .find(|change| change.id == id)
                .expect("row")
                .status_badge()
        }

        assert_eq!(
            badge(&app, "dependency-wait"),
            "blocked:dependency",
            "a dependency wait must not render as a plain queued row"
        );
        assert_eq!(
            badge(&app, "capacity-wait"),
            "queued",
            "a change waiting only for a slot keeps its plain badge"
        );

        // Resolution hands the row back to its retained queue intent, and the
        // badge follows the same shared projection back.
        shared
            .blocking_write()
            .clear_dependency_blocker("dependency-wait");
        let (display_map, blocker_views) = {
            let guard = shared.blocking_read();
            (guard.all_display_statuses(), guard.all_blocker_views())
        };
        app.apply_display_statuses_from_reducer(&display_map);
        app.apply_blocker_views_from_reducer(&blocker_views);
        assert_eq!(badge(&app, "dependency-wait"), "queued");
    }
}