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
//! TUI runner and main event loop
//!
//! Contains run_tui and run_tui_loop functions.

use crate::config::OrchestratorConfig;
use crate::error::Result;
use crate::lifecycle_integration::LifecycleHandle;
use crate::openspec::Change;
use crate::parallel::PostArchiveAction;
use crate::vcs::{GitWorkspaceManager, WorkspaceManager};
use crossterm::event::{self, Event, KeyEventKind, MouseEventKind};
use ratatui::DefaultTerminal;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};

use super::command_handlers::{handle_tui_command, TuiCommandContext};
use super::events::{LogEntry, OrchestratorEvent, TuiCommand, TuiRefreshObservation};
use super::key_handlers::{handle_key_event, KeyEventContext};
use super::lifecycle::TuiLifecycleSnapshot;
use super::log_deduplicator;
// orchestrator functions now called from command_handlers
use super::queue::DynamicQueue;
use super::render::{render, SPINNER_CHARS};
use super::state::{AppState, AUTO_REFRESH_INTERVAL_SECS};
// AppExecutionMode/StopMode are used in handlers
use super::terminal::restore_terminal;
use super::worktrees::load_worktrees_with_conflict_check;

fn is_refresh_root_usable(repo_root: &Path) -> bool {
    repo_root.is_dir()
}

fn should_skip_local_refresh(repo_root: &Path, stale_refresh_root_warned: &mut bool) -> bool {
    let refresh_root_usable = is_refresh_root_usable(repo_root);
    if !refresh_root_usable {
        if !*stale_refresh_root_warned {
            *stale_refresh_root_warned = true;
            warn!(
                repo_root = %repo_root.display(),
                "Skipping local TUI auto-refresh: stale or missing refresh root"
            );
        }
        return true;
    }

    *stale_refresh_root_warned = false;
    false
}

/// Observe workspace dirty state for one auto-refresh tick.
///
/// The predicate is the shared read-only one
/// ([`crate::vcs::git::commands::has_uncommitted_changes`]), so the header
/// counts staged, unstaged, and untracked work and excludes ignored files under
/// the same explicit untracked/ignored modes every other dirty-state consumer
/// gets — repository or user `status.showUntrackedFiles` configuration cannot
/// make untracked work report as clean here either.
///
/// A failed read returns `None` rather than a value. There is no third answer to
/// publish: the caller keeps its last successful observation instead of turning
/// an unobservable workspace into a clean one. The warning is bounded the same
/// way the stale-root warning above is — once per failure episode, cleared by
/// the next success — so a persistently unreadable repository cannot fill the
/// log at the refresh cadence.
async fn observe_workspace_dirty(
    repo_root: &Path,
    dirty_observation_warned: &mut bool,
) -> Option<TuiRefreshObservation> {
    match crate::vcs::git::commands::has_uncommitted_changes(repo_root).await {
        Ok((dirty, _status)) => {
            *dirty_observation_warned = false;
            Some(TuiRefreshObservation::WorkspaceDirty { dirty })
        }
        Err(err) => {
            if !*dirty_observation_warned {
                *dirty_observation_warned = true;
                warn!(
                    repo_root = %repo_root.display(),
                    error = %err,
                    "Failed to observe workspace dirty state: keeping the last successful observation"
                );
            }
            None
        }
    }
}

fn refresh_local_changes(repo_root: &Path) -> Result<(Vec<Change>, Vec<Change>)> {
    let active_changes = crate::openspec::list_changes_native_from(repo_root)?;
    let rejected_changes = crate::openspec::list_rejected_changes_native_from(repo_root)?;
    Ok((active_changes, rejected_changes))
}

/// Whether this event can change the reducer-derived display caches the TUI
/// renders from.
///
/// It no longer decides whether the reducer is *written* — the dispatch owner
/// does that, exactly once, before the event reaches this frontend. It only
/// decides whether re-reading the reducer afterwards could show anything new,
/// so a chatty output event does not cost a lock and two map rebuilds per chunk.
fn should_apply_event_to_tui_reducer(event: &crate::events::ExecutionEvent) -> bool {
    use crate::events::ExecutionEvent;

    match event {
        // Reducer-visible lifecycle and workspace observations that derive TUI display status,
        // queue intent, active counts, wait states, or terminal state.
        ExecutionEvent::ProcessingStarted(_)
        | ExecutionEvent::ProcessingError { .. }
        | ExecutionEvent::ApplyStarted { .. }
        | ExecutionEvent::ApplyCompleted { .. }
        | ExecutionEvent::ApplyFailed { .. }
        | ExecutionEvent::ArchiveStarted { .. }
        | ExecutionEvent::ArchiveResumed { .. }
        | ExecutionEvent::ArchiveRetryScheduled { .. }
        | ExecutionEvent::ChangeArchived(_)
        | ExecutionEvent::ArchiveFailed { .. }
        | ExecutionEvent::AcceptanceStarted { .. }
        | ExecutionEvent::AcceptanceCompleted { .. }
        | ExecutionEvent::AcceptanceFailed { .. }
        | ExecutionEvent::ChangeRejected { .. }
        | ExecutionEvent::RejectionReviewCompleted { .. }
        | ExecutionEvent::RejectionReviewFailed { .. }
        | ExecutionEvent::WorkspaceStatusUpdated { .. }
        | ExecutionEvent::WorkspacePreparationStarted { .. }
        | ExecutionEvent::WorkspacePreparationEnded { .. }
        | ExecutionEvent::PushStarted { .. }
        | ExecutionEvent::PushCompleted { .. }
        | ExecutionEvent::PushFailed { .. }
        | ExecutionEvent::MergeCompleted { .. }
        | ExecutionEvent::MergeDeferred { .. }
        | ExecutionEvent::ResolveStarted { .. }
        | ExecutionEvent::ResolveCompleted { .. }
        | ExecutionEvent::ResolveFailed { .. }
        | ExecutionEvent::DependencyBlocked { .. }
        | ExecutionEvent::DependencyResolved { .. }
        | ExecutionEvent::AcceptanceGated { .. }
        | ExecutionEvent::ExecutionBlocked { .. }
        | ExecutionEvent::ChangeDequeued { .. }
        | ExecutionEvent::ChangeStopped { .. }
        | ExecutionEvent::ChangesRefreshed { .. } => true,

        // A process-level stop is a reducer-owned run boundary: it returns every
        // interrupted row to `not queued` and guards it against late lifecycle
        // events. The TUI reads that one transition instead of maintaining a
        // second string-matching reset that a new status variant could miss.
        ExecutionEvent::Stopped => true,

        // An accepted operator command commits reducer queue intent, retry
        // edges, and resolve intent before it publishes this event, so the row
        // statuses it produced have to be re-read here. Not re-reading them is
        // exactly how a remote queue or retry command used to reach `/api/v2`
        // without ever reaching the next TUI render.
        ExecutionEvent::OperatorCommandApplied { .. } => true,

        // The reducer holds the ephemeral commit subphase, so the TUI must
        // re-read it to switch a row's rendered operation between apply and
        // commit. It never changes the canonical `applying` display status.
        ExecutionEvent::ApplyCommitPhase { .. } => true,

        // Presentation-only or unrelated TUI events do not affect reducer display state.
        ExecutionEvent::ApplyCommitOutput { .. }
        | ExecutionEvent::ApplyOutput { .. }
        | ExecutionEvent::ArchiveOutput { .. }
        | ExecutionEvent::AcceptanceOutput { .. }
        | ExecutionEvent::ProgressUpdated { .. }
        | ExecutionEvent::WorkspaceCreated { .. }
        | ExecutionEvent::WorkspaceResumed { .. }
        | ExecutionEvent::WorkspacePreserved { .. }
        | ExecutionEvent::CleanupStarted { .. }
        | ExecutionEvent::CleanupCompleted { .. }
        | ExecutionEvent::MergeStarted { .. }
        | ExecutionEvent::MergeConflict { .. }
        | ExecutionEvent::ConflictResolutionStarted
        | ExecutionEvent::ConflictResolutionCompleted
        | ExecutionEvent::ConflictResolutionFailed { .. }
        | ExecutionEvent::ChangeSkipped { .. }
        | ExecutionEvent::AnalysisStarted { .. }
        | ExecutionEvent::AnalysisOutput { .. }
        | ExecutionEvent::AnalysisCompleted { .. }
        | ExecutionEvent::ResolveOutput { .. }
        | ExecutionEvent::HookStarted { .. }
        | ExecutionEvent::HookCompleted { .. }
        | ExecutionEvent::HookFailed { .. }
        | ExecutionEvent::Warning { .. }
        | ExecutionEvent::ParallelStartRejected { .. }
        | ExecutionEvent::Log(_)
        | ExecutionEvent::Stopping
        | ExecutionEvent::AllCompleted
        // The idle transition owns no reducer mutation at all: rows keep their
        // status, blockers, queue intent, and worktree evidence across it, so
        // re-reading the reducer here could only cost a lock for no new fact.
        | ExecutionEvent::PersistentSchedulerIdle
        | ExecutionEvent::Error { .. }
        | ExecutionEvent::WorktreesRefreshed { .. }
        | ExecutionEvent::BranchMergeStarted { .. }
        | ExecutionEvent::BranchMergeCompleted { .. }
        | ExecutionEvent::BranchMergeFailed { .. }
        | ExecutionEvent::ChangeStopFailed { .. } => false,
    }
}

/// Apply the mark writes an operator interaction requested, then mirror the rows.
///
/// The write is deferred out of key handling for one reason: it has to take the
/// same async operator mutation guard the authoritative dispatcher takes for
/// mark reconciliation. Applying it here — one requested change at a time —
/// keeps an interaction from ever replacing the shared store from this
/// frontend's cached row set, so a mark a concurrent event revoked stays
/// revoked and a mark another frontend set stays set.
pub(crate) async fn apply_pending_mark_writes(
    app: &mut AppState,
    service: &Arc<crate::orchestration::operator_command::OperatorCommandService>,
) {
    let pending = app.take_pending_mark_writes();
    if pending.is_empty() {
        return;
    }
    for (change_id, marked) in pending {
        service.apply_execution_mark(&change_id, marked).await;
    }
    app.sync_execution_marks_from_store();
}

/// Refresh the TUI's reducer-derived display caches after one event.
///
/// The reducer is **read**, never written. By the time an event reaches this
/// frontend its dispatch owner has already applied it, so a write here would be
/// the second transition for one internal event: an apply count that advances
/// twice, a change that leaves the queue twice, a terminal state reached twice.
///
/// Status, blocker view, and error detail come from the same snapshot so a row's
/// `blocked`/`stalled` word, its blocker kind, and its final diagnostic can never
/// disagree.
pub(crate) async fn sync_reducer_display_caches(
    app: &mut AppState,
    shared_state: &Arc<tokio::sync::RwLock<crate::orchestration::state::OrchestratorState>>,
    event: &crate::events::ExecutionEvent,
) {
    if !should_apply_event_to_tui_reducer(event) {
        return;
    }
    let (display_map, archived, blocker_views, error_details, apply_operations) = {
        let state = shared_state.read().await;
        (
            state.all_display_statuses(),
            // Same read as the statuses: after `ChangeArchived` the reducer keeps
            // the archive milestone here while truthfully advancing the row to
            // `resolving` or `resolve pending`, so presentation needs both facts
            // from one instant to hide the checkbox without inferring it from the
            // status string.
            state.archived_changes().clone(),
            state.all_blocker_views(),
            state.all_error_details(),
            state.all_apply_operation_labels(),
        )
    };
    app.apply_display_statuses_from_reducer(&display_map);
    app.apply_archived_changes_from_reducer(&archived);
    app.apply_blocker_views_from_reducer(&blocker_views);
    // Rendering-only refresh: the reducer's ephemeral commit subphase decides
    // whether the Apply lane prints `[apply]` or `[commit]`.
    app.apply_operation_labels_from_reducer(&apply_operations);
    // Error rows adopt the reducer's retained diagnostic even when this frontend
    // never observed the failure event itself, so the row can still name its
    // failure after the matching log entry has been evicted.
    app.apply_error_details_from_reducer(&error_details);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocalOrchestratorShutdownOutcome {
    NoTask,
    AlreadyFinished,
    Graceful,
    AbortedAfterTimeout,
}

/// How long local TUI quit waits for the orchestrator before escalating.
///
/// It must not undercut the scheduler's own cancellation boundary: the run
/// needs that whole window to finish command cleanup and pending merge/base-lane
/// handling. The extra margin covers the scheduler's own return path after its
/// barrier completes, so a run that used its full budget still gets to report
/// gracefully instead of being aborted at the exact same instant.
pub const LOCAL_ORCHESTRATOR_SHUTDOWN_GRACE: Duration = Duration::from_secs(
    crate::tui::orchestrator::PARALLEL_CANCELLATION_CLEANUP_DEADLINE.as_secs() + 5,
);

/// Bounded budget for the supervisor's own forceful cleanup after a timeout.
const LOCAL_SHUTDOWN_FORCE_CLEANUP_BUDGET: Duration = Duration::from_secs(10);

pub async fn shutdown_local_orchestrator_task(
    orchestrator_handle: Option<tokio::task::JoinHandle<Result<()>>>,
    orchestrator_cancel: Option<CancellationToken>,
    run_command_scope: Option<crate::ai_command_runner::RunCommandScope>,
    grace_period: Duration,
) -> LocalOrchestratorShutdownOutcome {
    // Admission closes at cancellation time, not after the grace period: a
    // command must not be able to start while the TUI is already leaving.
    if let Some(scope) = &run_command_scope {
        scope.close();
    }

    if let Some(cancel) = orchestrator_cancel {
        info!(
            grace_ms = grace_period.as_millis(),
            "Cancelling local TUI orchestrator during shutdown"
        );
        cancel.cancel();
    }

    let Some(handle) = orchestrator_handle else {
        debug!("No local TUI orchestrator task to shut down");
        return LocalOrchestratorShutdownOutcome::NoTask;
    };

    if handle.is_finished() {
        let _ = handle.await;
        info!("Local TUI orchestrator task was already finished during shutdown");
        return LocalOrchestratorShutdownOutcome::AlreadyFinished;
    }

    tokio::pin!(handle);
    tokio::select! {
        join_result = &mut handle => {
            match join_result {
                Ok(Ok(())) => info!("Local TUI orchestrator task finished gracefully during shutdown"),
                Ok(Err(err)) => warn!(error = %err, "Local TUI orchestrator task exited with error during shutdown"),
                Err(err) => warn!(error = %err, "Local TUI orchestrator task join failed during shutdown"),
            }
            LocalOrchestratorShutdownOutcome::Graceful
        }
        _ = tokio::time::sleep(grace_period) => {
            warn!(
                grace_ms = grace_period.as_millis(),
                "Local TUI orchestrator did not finish before shutdown grace period; aborting task to prevent detached local work"
            );
            // Task abort is not child-process cleanup evidence, and it destroys
            // the only in-task path to the run's PGIDs. The retained scope is
            // consumed here, before the abort, so deterministic groups are
            // force-cleaned and verified while their identities still exist.
            if let Some(scope) = &run_command_scope {
                let cleanup = scope
                    .force_cleanup_retained(LOCAL_SHUTDOWN_FORCE_CLEANUP_BUDGET)
                    .await;
                if cleanup.is_quiescent() {
                    info!(
                        escalated = cleanup.escalated,
                        "Forced cleanup of retained run-owned process groups before aborting the local TUI orchestrator"
                    );
                } else {
                    warn!(
                        "Local TUI shutdown could not prove run-owned process cleanup: {}",
                        cleanup.diagnostics()
                    );
                }
            }
            handle.as_ref().abort_handle().abort();
            match tokio::time::timeout(Duration::from_secs(1), &mut handle).await {
                Ok(Ok(_)) => info!("Aborted local TUI orchestrator task joined after abort"),
                Ok(Err(err)) if err.is_cancelled() => {
                    info!("Local TUI orchestrator task aborted successfully")
                }
                Ok(Err(err)) => {
                    warn!(error = %err, "Local TUI orchestrator task join failed after abort")
                }
                Err(_) => warn!("Timed out while joining aborted local TUI orchestrator task"),
            }
            LocalOrchestratorShutdownOutcome::AbortedAfterTimeout
        }
    }
}

/// Run the local TUI application.
#[allow(clippy::too_many_arguments)]
pub async fn run_tui(
    initial_changes: Vec<Change>,
    config: OrchestratorConfig,
    web_url: Option<String>,
    #[cfg(feature = "web-monitoring")] web_state: Option<Arc<crate::web::WebState>>,
    post_archive_action: PostArchiveAction,
    upstream_runtime: Option<crate::upstream::UpstreamRuntime>,
    lifecycle: LifecycleHandle,
) -> Result<()> {
    // Set up panic hook to restore terminal on panic
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        restore_terminal();
        original_hook(panic_info);
    }));

    let mut terminal = ratatui::init();

    // Mouse capture disabled due to terminal compatibility issues
    // Use PageUp/PageDown or k/j keys for scrolling instead
    // execute!(std::io::stdout(), EnableMouseCapture)?;

    let result = run_tui_loop(
        &mut terminal,
        initial_changes,
        config,
        web_url,
        #[cfg(feature = "web-monitoring")]
        web_state,
        post_archive_action,
        upstream_runtime,
        lifecycle,
    )
    .await;

    // Restore terminal state
    restore_terminal();

    result
}

/// Main TUI event loop
#[allow(clippy::too_many_arguments)]
async fn run_tui_loop(
    terminal: &mut DefaultTerminal,
    initial_changes: Vec<Change>,
    config: OrchestratorConfig,
    web_url: Option<String>,
    #[cfg(feature = "web-monitoring")] web_state: Option<Arc<crate::web::WebState>>,
    post_archive_action: PostArchiveAction,
    upstream_runtime: Option<crate::upstream::UpstreamRuntime>,
    lifecycle: LifecycleHandle,
) -> Result<()> {
    let repo_root = std::env::current_dir()?;

    let (committed_change_ids, uncommitted_file_change_ids): (HashSet<String>, HashSet<String>) = {
        let committed_change_ids: HashSet<String> =
            match crate::vcs::git::commands::list_changes_in_head(&repo_root).await {
                Ok(ids) => ids.into_iter().collect(),
                Err(err) => {
                    warn!("Failed to load committed change snapshot: {}", err);
                    initial_changes
                        .iter()
                        .map(|change| change.id.clone())
                        .collect()
                }
            };

        let uncommitted_file_change_ids: HashSet<String> =
            match crate::vcs::git::commands::list_changes_with_uncommitted_files(&repo_root).await {
                Ok(ids) => ids.into_iter().collect(),
                Err(err) => {
                    warn!("Failed to detect uncommitted files in changes: {}", err);
                    HashSet::new()
                }
            };

        (committed_change_ids, uncommitted_file_change_ids)
    };
    let worktree_base_dir = config
        .get_workspace_base_dir()
        .map(PathBuf::from)
        .unwrap_or_else(|| crate::config::defaults::default_workspace_base_dir(Some(&repo_root)));
    let worktree_manager = GitWorkspaceManager::new(
        worktree_base_dir.clone(),
        repo_root.clone(),
        config.get_max_concurrent_workspaces(),
        config.clone(),
    );
    let worktree_change_ids: HashSet<String> =
        match worktree_manager.list_worktree_change_ids().await {
            Ok(ids) => ids,
            Err(err) => {
                warn!("Failed to load worktree snapshot: {}", err);
                HashSet::new()
            }
        };

    // Collect initial worktree paths for all changes
    let mut initial_worktree_paths = std::collections::HashMap::new();
    for change in &initial_changes {
        match crate::vcs::git::get_worktree_path_for_change(&repo_root, &change.id).await {
            Ok(Some(wt_path)) => {
                initial_worktree_paths.insert(change.id.clone(), wt_path);
            }
            Ok(None) => {
                // No worktree for this change
            }
            Err(e) => {
                debug!("Failed to get worktree path for {}: {}", change.id, e);
            }
        }
    }

    // Create shared orchestration state for unified tracking across TUI and Web
    let change_ids: Vec<String> = initial_changes.iter().map(|c| c.id.clone()).collect();
    let max_iterations = config.get_max_iterations();
    let shared_state = std::sync::Arc::new(tokio::sync::RwLock::new(
        crate::orchestration::state::OrchestratorState::new(change_ids, max_iterations),
    ));

    let tui_config = crate::tui::config::TuiConfig::load_user_config()?;
    let mut app = AppState::new(initial_changes);
    app.set_tui_config(tui_config);
    app.worktree_paths = initial_worktree_paths;
    // Inject shared state reference into TUI for unified tracking
    app.set_shared_state(shared_state.clone());
    // Startup already refused a workspace without a usable Git repository, so
    // worktree execution is available here by construction.
    app.max_concurrent = config.get_max_concurrent_workspaces();
    app.vcs_backend = config.get_vcs_backend().to_string();
    // Header project identity, captured once. The same `repo_root` backs the
    // refresh task and the dirty predicate, so a later process `chdir` moves
    // none of the three.
    app.set_project_path(repo_root.clone());
    // The branch that identity is read against, resolved once here and never
    // again. A detached HEAD or a failed lookup leaves it unset: the header
    // simply omits the segment, because an operator reading a guessed branch is
    // worse off than one reading none, and neither outcome may stop startup.
    app.set_base_branch(
        match crate::vcs::git::commands::get_current_branch(&repo_root).await {
            Ok(branch) => branch,
            Err(err) => {
                debug!("Failed to resolve the startup base branch for the header: {err}");
                None
            }
        },
    );
    app.publish_parallel_runtime();
    app.apply_parallel_eligibility(&committed_change_ids, &uncommitted_file_change_ids);
    app.apply_worktree_status(&worktree_change_ids);
    app.web_url = web_url;

    // Create shared stagger state for all AI commands (worktree, apply, archive, acceptance)
    use crate::ai_command_runner::{AiCommandRunner, SharedStaggerState};
    let shared_stagger_state: SharedStaggerState = Arc::new(tokio::sync::Mutex::new(None));
    let ai_runner =
        AiCommandRunner::from_orchestrator_config(&config, shared_stagger_state.clone());

    // Two directions, deliberately not one channel.
    //
    // `tx` is the producer side every TUI-local emitter already holds. `rx` is
    // therefore a *producer* boundary: this loop is the dispatch owner for what
    // arrives there, and applies it to the reducer once before rendering it.
    //
    // `frontend_rx` is the delivery side of the orchestration boundary's own
    // dispatch owner. Those events were already applied to the reducer and
    // already projected to `/api/v2`; re-applying them here is exactly the
    // double transition — a doubled apply count, a doubled event sequence —
    // that this frontend must not cause.
    let (tx, mut rx) = mpsc::channel::<OrchestratorEvent>(100);
    let (frontend_tx, mut frontend_rx) = mpsc::channel::<OrchestratorEvent>(100);
    let (cmd_tx, mut cmd_rx) = mpsc::channel::<TuiCommand>(100);

    // Inject shared state into WebState if web monitoring is enabled.
    //
    // The execution-mark store and the repository root go with it: without them
    // the v2 snapshot could report neither operator intent nor a redacted
    // change-to-worktree relation, and a remote frontend would have to infer
    // both.
    #[cfg(feature = "web-monitoring")]
    if let Some(ref ws) = web_state {
        ws.set_shared_state(shared_state.clone()).await;
        ws.set_execution_marks(app.execution_marks()).await;
        ws.set_parallel_runtime(app.parallel_runtime()).await;
        // Bound later, once the supervisor exists: see `managed_termination`.
        ws.set_repo_root(repo_root.clone()).await;
    }

    // Dynamic queue for runtime change additions
    let dynamic_queue = DynamicQueue::new();

    // Manual resolve counter for tracking active manual resolves
    // This allows manual resolves to consume parallel execution slots
    let manual_resolve_counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));

    // Shared flag for graceful stop (signaling orchestrator to stop after current change)
    let graceful_stop_flag = Arc::new(AtomicBool::new(false));

    // One reconciler for this process: the shared mark store plus the shared
    // operator mutation guard. Every production dispatch path binds *this* value,
    // so a mark revoked by an event and a mark set by a command are the same fact
    // in the TUI, in `/api/v2`, and in Start target resolution.
    let mark_reconciler = crate::orchestration::mark_reconciliation::ExecutionMarkReconciler::new(
        app.execution_marks(),
        app.parallel_runtime(),
    );

    // The one ephemeral process lifecycle mode. TUI `execution_mode` and Web
    // `app_mode` are projections of it; command admission is validated against
    // it rather than against whichever frontend happened to submit the command.
    // It is process-local and starts fresh here, so a restart recomputes the next
    // action from the workspace alone.
    let core_mode = Arc::new(crate::orchestration::operator_coordinator::CoreMode::new());

    // The one process-local execution-facts store. The dispatch owner feeds it,
    // `/api/v2/execution-status` reads it, and stop settlement consults it, so
    // "which phase was running" has one answer for every consumer. It is an
    // observability output only: it starts empty on every restart and no
    // workflow decision reads it.
    let execution_facts =
        Arc::new(crate::orchestration::execution_facts::ExecutionFactsStore::new());

    // *The* dispatch owner for this process. Runner-local producers, accepted
    // operator-command outcomes, and every orchestration run publish through it,
    // which is what makes one internal event produce exactly one reducer
    // transition, one core mode transition, one mark reconciliation, and one
    // delivery per frontend — no matter which producer raised it.
    //
    // Its TUI sink is `frontend_tx`, the delivery side. Wiring the producer
    // channel here instead would route every dispatched event back into the
    // producer boundary and apply it to the reducer a second time.
    let dispatcher = Arc::new(
        crate::events::EventDispatcher::new(
            shared_state.clone(),
            crate::tui::orchestrator::process_event_sinks(
                &frontend_tx,
                #[cfg(feature = "web-monitoring")]
                web_state.as_ref(),
            ),
        )
        .with_mark_reconciler(Some(mark_reconciler.clone()))
        .with_core_mode(Some(core_mode.clone()))
        .with_execution_facts(Some(execution_facts.clone())),
    );

    // TUI-local producers (key handlers, hooks, worktree operations, the
    // auto-refresh) reach that owner through this forwarder rather than through
    // the render loop. Forwarding off the loop is what stops a burst of local
    // events from filling the delivery channel while the only task that drains
    // it is blocked publishing into it.
    {
        let producer_dispatcher = dispatcher.clone();
        tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                producer_dispatcher.dispatch(event).await;
            }
        });
    }

    // One run supervisor owns the local orchestrator task for this invocation.
    // The TUI adapter and the `/api/v2` adapter drive it through the same
    // run-control service, so neither can start or cancel a run the other
    // cannot see.
    let supervisor = Arc::new(crate::tui::run_supervisor::TuiRunSupervisor::new(
        repo_root.clone(),
        config.clone(),
        dispatcher.clone(),
        dynamic_queue.clone(),
        shared_state.clone(),
        manual_resolve_counter.clone(),
        post_archive_action.clone(),
        upstream_runtime.clone(),
        graceful_stop_flag.clone(),
    ));

    // External SIGINT/SIGTERM become a quit *request* the event loop drains, so
    // they leave through the same bounded shutdown boundary as a keypress
    // instead of terminating the process on top of live agent descendants.
    let external_shutdown = crate::tui::run_supervisor::ExternalShutdownRequest::new();
    external_shutdown.install();

    // The one managed-process authority for this process. The supervisor holds
    // whichever run is live, so reading its scope per call is what keeps a
    // targeted force-stop bound to the run that owns the processes rather than
    // to a scope captured once at startup and reaped several runs ago.
    let managed_termination: Arc<
        dyn crate::orchestration::operator_command::ManagedProcessTermination,
    > = {
        let scope_owner = supervisor.clone();
        Arc::new(
            crate::orchestration::operator_command::LiveRunManagedProcesses::new(move || {
                scope_owner.run_command_scope()
            }),
        )
    };

    // The single process-local application services every frontend commands
    // through. They are built once here, before the first keypress and before v2
    // is bound, so a remote command and a keypress cannot reach different
    // instances of the lifecycle matrix.
    let operator_service = {
        use crate::orchestration::operator_command::{
            HookRunnerQueueHooks, OperatorCommandService,
        };
        // The same two inputs the Acceptance boundary itself derives from: where
        // a change's managed worktree lives, and which embedded reviewer skill
        // the manifest binds.
        let acceptance_worktree_base_dir = worktree_base_dir.clone();
        let accept_skill_name = config.get_accept_skill().to_string();
        let hook_runner = crate::hooks::HookRunner::with_event_tx(
            config.get_hooks(),
            repo_root.clone(),
            tx.clone(),
        );
        Arc::new(
            OperatorCommandService::new(
                shared_state.clone(),
                Arc::new(dynamic_queue.clone()),
                Arc::new(HookRunnerQueueHooks::new(hook_runner)),
                app.execution_marks(),
            )
            .with_parallel(app.parallel_runtime())
            // Read-only, and only at stop settlement: the phase a settled
            // command reports comes from the same store the status resource
            // publishes.
            .with_execution_facts(execution_facts.clone())
            // The managed ownership graph a targeted force-stop signals
            // through. It re-reads the *live* run's command scope on every
            // call, so a kill always reaches the run that is actually
            // executing and reports "owns nothing" between runs.
            .with_managed_termination(managed_termination.clone())
            // Refuses an unchanged retry before anything is dispatched, from
            // two facts that must both hold: a hold *this owner* recorded, and
            // a fingerprint recomputed from the managed worktree right now. A
            // restarted owner remembers nothing and refuses nothing; a
            // repository change moves the fingerprint and restores eligibility.
            // The path is resolved per call, and a change whose worktree is gone
            // simply has nothing to compare against.
            .with_acceptance_admission(Arc::new(
                crate::orchestration::acceptance::execution_manifest::WorkspaceAcceptanceAdmission::new(
                    {
                        let base = acceptance_worktree_base_dir.clone();
                        move |change_id: &str| {
                            let path = base.join(change_id.replace(['/', '\\', ' '], "-"));
                            path.is_dir().then_some(path)
                        }
                    },
                    accept_skill_name.clone(),
                    config.get_state_base_dir().map(str::to_string),
                ),
            )),
        )
    };
    // One store, three readers: the start guard, the operator service that
    // mutates the toggle, and the TUI that observes it.
    let start_eligibility = app.parallel_runtime();
    let run_control = Arc::new(crate::orchestration::run_control::RunControlService::new(
        shared_state.clone(),
        operator_service.clone(),
        supervisor.clone(),
        app.resolve_reservations(),
        start_eligibility.clone(),
    ));

    // The one application transaction. Both adapters submit typed intent to it,
    // so equivalent TUI and `/api/v2` intent cannot take different paths through
    // validation, commit ordering, outcome dispatch, or scheduler activation.
    #[allow(unused_mut)]
    let mut application = crate::orchestration::operator_coordinator::OperatorApplication::new(
        core_mode.clone(),
        run_control.clone(),
        dispatcher.clone(),
    )
    // Explanatory Git evidence for stop settlement, read from the server's own
    // change-to-worktree mapping while the terminated worktree is quiescent.
    .with_apply_commit_evidence(Some(Arc::new(
        crate::orchestration::apply_commit_evidence::GitApplyCommitEvidence::new(repo_root.clone()),
    )));
    #[cfg(feature = "web-monitoring")]
    if let Some(ref ws) = web_state {
        // Where an outcome dispatch's exact revision is read back from. Without
        // it the coordinator still runs the same transaction; it just has no
        // command record to bind a revision to.
        let revisions: Arc<dyn crate::events::OutcomeRevisions> = ws.clone();
        application = application.with_revisions(Some(revisions));
        // The same port the shared transaction kills through, so the
        // `actions.force_stop_change` a client reads and the admission a
        // command hits are one fact rather than two.
        ws.set_managed_termination(managed_termination.clone())
            .await;
    }
    let application = Arc::new(application);
    // Mark settlement becomes possible only now: the transaction that admits its
    // additions has to exist before a deadline may be armed against it. Before
    // this line every mark write in this process is mark-only.
    crate::orchestration::operator_coordinator::bind_mark_settlement(&application);

    // The TUI's ordered submission path. One worker drains it, so keypresses
    // reach the coordinator in the order the operator made them, while the event
    // loop below never awaits the application gate itself.
    let (submission_tx, mut submission_rx) =
        mpsc::channel::<crate::tui::command_handlers::Submission>(256);
    let (feedback_tx, mut feedback_rx) =
        mpsc::channel::<crate::tui::command_handlers::CommandFeedback>(256);
    {
        let worker_application = application.clone();
        let worker_feedback = feedback_tx.clone();
        tokio::spawn(async move {
            while let Some(submission) = submission_rx.recv().await {
                let settled = submission.run(&worker_application).await;
                if worker_feedback.send(settled).await.is_err() {
                    break;
                }
            }
        });
    }
    // One worktree service for this repository, for the same reason: it owns the
    // repository mutation guard, and two instances would be two guards that
    // cannot see each other's in-flight deletion.
    let worktree_service =
        crate::tui::command_handlers::build_worktree_service(&repo_root, &config, &tx);

    // Bind `/api/v2` command delegation to the shared application services.
    //
    // The web server started before this point (it owns the URL shown in the
    // TUI), so v2 refuses commands until the same services the TUI uses exist.
    // Binding them here is what makes a remote command and a keypress take
    // identical paths through lifecycle validation and side effects.
    #[cfg(feature = "web-monitoring")]
    if let Some(ref ws) = web_state {
        // The remote worktree port is built once and bound to both halves of v2:
        // the read routes and the command executor must agree about which
        // worktrees exist and which opaque IDs address them. It is wired to the
        // *same* service the TUI commands through, so a remote delete and a
        // keypress contend for one guard rather than racing through two.
        let worktree_port: Arc<dyn crate::web::remote_control_api::worktrees::WorktreeOperations> =
            Arc::new(
                crate::web::remote_control_api::worktrees::RemoteWorktreeOperations::new(
                    worktree_service.clone(),
                    Arc::new(crate::web::remote_control_api::worktrees::WorktreeRegistry::new()),
                    repo_root.clone(),
                ),
            );

        let runtime = ws.remote_control();
        runtime
            .bind(Arc::new(
                crate::web::remote_control_api::executor::SharedServiceExecutor::new(
                    application.clone(),
                    ws.clone(),
                )
                .with_worktrees(worktree_port.clone()),
            ))
            .await;
        runtime.bind_worktrees(worktree_port).await;
        // The same gate a keypress takes. Binding it is what turns `/api/v2`
        // admission from "atomic for the record" into "serialized through
        // settlement", so two new commands cannot consume one revision.
        runtime.bind_gate(application.gate()).await;
        // The same liveness authority the execution-status resource reports as
        // `scheduler_running`, kept distinct from `has_active_work` so a parked
        // persistent scheduler is never mistaken for admitted work.
        runtime.bind_run_boundary(supervisor.clone());
        // The store the dispatch owner already feeds, so a v2 client reads the
        // same phases the coordinator settles against.
        ws.set_execution_facts(execution_facts.clone()).await;
    }

    // Cancellation token for graceful shutdown
    let cancel_token = CancellationToken::new();

    // Start auto-refresh task
    let refresh_tx = tx.clone();
    let refresh_cancel = cancel_token.clone();
    let refresh_repo_root = repo_root.clone();
    let refresh_worktree_base_dir = worktree_base_dir.clone();
    let refresh_config = config.clone();
    // Presentation-only observations from the same refresh tick. They travel on
    // their own channel rather than as an `ExecutionEvent` precisely because
    // they are not workflow facts: no reducer transition, no operator snapshot
    // revision, and no `/api/v2` event is owed for them.
    let (refresh_observation_tx, mut refresh_observation_rx) =
        mpsc::channel::<TuiRefreshObservation>(16);
    let refresh_handle = tokio::spawn(async move {
        let worktree_manager = GitWorkspaceManager::new(
            refresh_worktree_base_dir,
            refresh_repo_root.clone(),
            refresh_config.get_max_concurrent_workspaces(),
            refresh_config,
        );
        let mut stale_refresh_root_warned = false;
        let mut dirty_observation_warned = false;
        let mut interval = tokio::time::interval(Duration::from_secs(AUTO_REFRESH_INTERVAL_SECS));
        loop {
            tokio::select! {
                _ = refresh_cancel.cancelled() => {
                    break;
                }
                _ = interval.tick() => {
                    if should_skip_local_refresh(
                        &refresh_repo_root,
                        &mut stale_refresh_root_warned,
                    ) {
                        continue;
                    }

                    // The captured startup root, not the process current
                    // directory: a `cd` elsewhere in this process must not
                    // silently retarget what the header reports.
                    if let Some(observation) = observe_workspace_dirty(
                        &refresh_repo_root,
                        &mut dirty_observation_warned,
                    )
                    .await
                    {
                        // A closed receiver means the render loop is gone, so
                        // the badge has no consumer left; the refresh task keeps
                        // serving its orchestration duties regardless.
                        let _ = refresh_observation_tx.send(observation).await;
                    }

                    match refresh_local_changes(&refresh_repo_root) {
                        Ok((mut changes, rejected_changes)) => {
                            let committed_change_ids: HashSet<String> =
                                match crate::vcs::git::commands::list_changes_in_head(&refresh_repo_root).await {
                                    Ok(ids) => ids.into_iter().collect(),
                                    Err(err) => {
                                        warn!("Failed to refresh committed change snapshot: {}", err);
                                        changes.iter().map(|change| change.id.clone()).collect()
                                    }
                                };
                            let uncommitted_file_change_ids: HashSet<String> =
                                match crate::vcs::git::commands::list_changes_with_uncommitted_files(&refresh_repo_root).await {
                                    Ok(ids) => ids.into_iter().collect(),
                                    Err(err) => {
                                        warn!("Failed to refresh uncommitted files snapshot: {}", err);
                                        HashSet::new()
                                    }
                                };
                            let worktree_change_ids: HashSet<String> =
                                match worktree_manager.list_worktree_change_ids().await {
                                    Ok(ids) => ids,
                                    Err(err) => {
                                        warn!("Failed to refresh worktree snapshot: {}", err);
                                        HashSet::new()
                                    }
                                };

                            // Collect worktree paths for all changes
                            let mut worktree_paths = std::collections::HashMap::new();

                            // Enrich progress from worktrees (uncommitted task artifact)
                            for change in &mut changes {
                                match crate::vcs::git::get_worktree_path_for_change(
                                    &refresh_repo_root,
                                    &change.id
                                ).await {
                                    Ok(Some(wt_path)) => {
                                        // Store the worktree path for this change
                                        worktree_paths.insert(change.id.clone(), wt_path.clone());
                                        // Use unified fallback helper: worktree → archive → base
                                        match crate::task_parser::parse_progress_with_fallback(
                                            &change.id,
                                            Some(&wt_path)
                                        ) {
                                            Ok(progress) => {
                                                if progress.total > 0 {
                                                    change.completed_tasks = progress.completed;
                                                    change.total_tasks = progress.total;
                                                } else {
                                                    // Keep existing progress if 0/0
                                                    debug!("Keeping existing progress for {} (parsed: 0/0)", change.id);
                                                }
                                            }
                                            Err(e) => {
                                                debug!("Failed to read progress for {}: {}", change.id, e);
                                                // Keep existing progress (from base tree)
                                            }
                                        }
                                    }
                                    Ok(None) => {
                                        // No worktree exists, use progress from base tree
                                    }
                                    Err(e) => {
                                        warn!("Failed to get worktree path for {}: {}", change.id, e);
                                        // Keep existing progress
                                    }
                                }
                            }

                            // Check which worktrees are not ahead of base (for MergeWait auto-clear)
                            let mut worktree_not_ahead_ids = std::collections::HashSet::new();
                            // Check which worktrees are archived but not merged (for MergeWait restoration)
                            let mut merge_wait_ids = std::collections::HashSet::new();

                            // Get base branch (current branch in main repo)
                            if let Ok(Some(base_branch)) = crate::vcs::git::commands::get_current_branch(&refresh_repo_root).await {
                                // For each change with a worktree, check if worktree branch is ahead of base
                                for (change_id, wt_path) in &worktree_paths {
                                    // Get the branch name for this worktree
                                    if let Ok(Some(worktree_branch)) = crate::vcs::git::commands::get_current_branch(wt_path).await {
                                        // Count commits ahead
                                        match crate::vcs::git::commands::count_commits_ahead(
                                            &refresh_repo_root,
                                            &base_branch,
                                            &worktree_branch
                                        ).await {
                                            Ok(0) => {
                                                // Worktree is not ahead (0 commits), mark for auto-clear
                                                worktree_not_ahead_ids.insert(change_id.clone());
                                            }
                                            Ok(_) => {
                                                // Worktree is ahead, keep MergeWait if present
                                            }
                                            Err(e) => {
                                                debug!("Failed to count commits ahead for {}: {}", change_id, e);
                                                // On error, don't auto-clear (safe default)
                                            }
                                        }
                                    }

                                    // Detect WorkspaceState::Archived for MergeWait restoration
                                    match crate::execution::state::detect_workspace_state(change_id, wt_path, &base_branch).await {
                                        Ok(crate::execution::state::WorkspaceState::Archived) => {
                                            // Worktree is archived but not merged, restore MergeWait
                                            merge_wait_ids.insert(change_id.clone());
                                            debug!("Detected MergeWait for '{}': archive complete, waiting for merge", change_id);
                                        }
                                        Ok(_) => {
                                            // Other states, do nothing
                                        }
                                        Err(e) => {
                                            debug!("Failed to detect workspace state for {}: {}", change_id, e);
                                            // On error, skip detection (safe default)
                                        }
                                    }
                                }
                            }

                            if refresh_tx
                                .send(OrchestratorEvent::ChangesRefreshed {
                                    changes,
                                    rejected_changes,
                                    committed_change_ids,
                                    uncommitted_file_change_ids,
                                    worktree_change_ids,
                                    worktree_paths,
                                    worktree_not_ahead_ids,
                                    merge_wait_ids,
                                })
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Err(e) => {
                            let _ = refresh_tx
                                .send(OrchestratorEvent::Log(LogEntry::error(format!(
                                    "Refresh failed: {}",
                                    e
                                ))))
                                .await;
                        }
                    }

                    // Refresh worktrees with conflict check (if in Worktrees view)
                    // We do this in the background without blocking
                    let wt_refresh_tx = refresh_tx.clone();
                    let wt_refresh_repo_root = refresh_repo_root.clone();
                    tokio::spawn(async move {
                        match load_worktrees_with_conflict_check(&wt_refresh_repo_root).await {
                            Ok(worktrees) => {
                                let _ = wt_refresh_tx
                                    .send(OrchestratorEvent::WorktreesRefreshed { worktrees })
                                    .await;
                            }
                            Err(e) => {
                                debug!("Failed to refresh worktrees: {}", e);
                                // Don't spam logs on refresh failures
                            }
                        }
                    });

                    log_deduplicator::maybe_log_summary();
                }
            }
        }
    });

    // External lifecycle reporting is derived from typed TUI state, never from
    // rendered screen contents. Unchanged states are deduplicated by the
    // dispatcher, so publishing once per frame is cheap and non-blocking.
    let lifecycle_workspace = repo_root.display().to_string();
    let publish_lifecycle_state = |app: &AppState| {
        if !lifecycle.is_enabled() {
            return;
        }
        let snapshot = TuiLifecycleSnapshot::from_app(app);
        lifecycle.publish_state(
            snapshot.lifecycle_state(),
            snapshot.lifecycle_context(&lifecycle_workspace),
        );
    };

    publish_lifecycle_state(&app);

    loop {
        // Increment spinner frame for animation (updates every 100ms)
        app.spinner_frame = (app.spinner_frame + 1) % SPINNER_CHARS.len();

        // Draw the UI
        terminal.draw(|frame| render(frame, &mut app))?;

        // Handle events with timeout
        if event::poll(Duration::from_millis(100))? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    // Create context for key event handling
                    let mut key_ctx = KeyEventContext {
                        app: &mut app,
                        terminal,
                        repo_root: &repo_root,
                        config: &config,
                        worktree_base_dir: &worktree_base_dir,
                        tx: &tx,
                        cmd_tx: &cmd_tx,
                        ai_runner: &ai_runner,
                        supervisor: &supervisor,
                    };

                    // Handle key event using helper
                    match handle_key_event(key, &mut key_ctx).await {
                        Ok(Some(cmd)) => {
                            // Send command to command channel for processing
                            let _ = cmd_tx.send(cmd).await;
                        }
                        Ok(None) => {
                            // No command to execute
                        }
                        Err(e) => {
                            app.add_log(LogEntry::error(format!("Key handling error: {}", e)));
                        }
                    }

                    // The interaction expressed intent; the shared service owns
                    // the write. Draining here — target-scoped, under the same
                    // guard event reconciliation takes — is what stops a stale
                    // cached row from resurrecting a mark a concurrent event
                    // already revoked.
                    apply_pending_mark_writes(&mut app, &operator_service).await;

                    // Check if app should quit (set by Ctrl+C)
                    if app.should_quit {
                        break;
                    }
                }
                Event::Mouse(mouse) => {
                    match mouse.kind {
                        MouseEventKind::ScrollUp => {
                            // Scroll logs up (show older entries) - 3 lines at a time
                            app.scroll_logs_up(3);
                        }
                        MouseEventKind::ScrollDown => {
                            // Scroll logs down (show newer entries) - 3 lines at a time
                            app.scroll_logs_down(3);
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }

        // Authoritative deliveries from the process-lifetime dispatch owner —
        // runner-local producers, accepted command outcomes, and orchestration
        // runs alike. The reducer transition, the core mode transition, and the
        // `/api/v2` projection already happened; this frontend reads the result
        // and renders it.
        //
        // Painting only: an orchestrator event never produces a command. Every
        // transition an event implies is dispatched by the scheduler from the
        // reducer-owned intent the same event already recorded.
        while let Ok(event) = frontend_rx.try_recv() {
            sync_reducer_display_caches(&mut app, &shared_state, &event).await;
            app.handle_orchestrator_event(event);
        }

        // Presentation-only refresh observations. They are drained on their own
        // because they own no reducer transition: nothing above needs to run for
        // them, and nothing below may change because of them.
        while let Ok(observation) = refresh_observation_rx.try_recv() {
            app.adopt_workspace_dirty_observation(observation);
        }

        // TUI command submissions. The coordinator work runs off this loop, so
        // neither the application gate nor a termination waiter is ever awaited
        // inside event processing or rendering; accepted outcomes return through
        // the authoritative dispatch above.
        while let Ok(cmd) = cmd_rx.try_recv() {
            let mut cmd_ctx = TuiCommandContext {
                app: &mut app,
                tx: &tx,
                application: &application,
                submissions: &submission_tx,
                feedback: &feedback_tx,
                worktree_service: &worktree_service,
            };

            if let Err(e) = handle_tui_command(cmd, &mut cmd_ctx, &shared_state).await {
                app.add_log(LogEntry::error(format!("Command handling error: {}", e)));
            }
        }

        // Wording for commands the worker settled since the last frame. The
        // accepted state itself already arrived through the dispatch above.
        while let Ok(settled) = feedback_rx.try_recv() {
            crate::tui::command_handlers::apply_command_feedback(&mut app, settled);
        }

        // The mode every frontend projects, read back once per frame. Commands
        // and lifecycle events both move it inside the dispatch boundary, so the
        // TUI adopts it rather than maintaining a second opinion about whether
        // this process is running.
        app.adopt_core_mode(core_mode.get());

        // The eligibility set is a TUI observation, so it is republished once
        // per frame instead of at every place the TUI can change it.
        app.publish_parallel_runtime();

        publish_lifecycle_state(&app);

        // An external SIGINT/SIGTERM is drained here as an ordinary quit
        // request, so it reaches the same cleanup below that a keypress does.
        if external_shutdown.is_requested() {
            app.should_quit = true;
        }

        if app.should_quit {
            break;
        }
    }

    // Cleanup: cancel all TUI-scoped tasks and force-stop local orchestration launched by this TUI.
    cancel_token.cancel();

    // Wait for tasks to finish gracefully. Remote mode has no local orchestrator handle here;
    // remote server-side work is stopped only by explicit Stop/ForceStop commands.
    refresh_handle.abort();
    // Remote mode has no local run, so the supervisor holds no handle and no
    // scope and this is a no-op: closing a remote TUI client still sends no stop.
    //
    // The outcome is not discarded. Cleanup that could not prove the owned
    // process groups empty means detached descendants may still be mutating the
    // managed worktree, and reporting a clean exit there would tell the operator
    // the opposite of what happened.
    supervisor
        .shutdown_run(LOCAL_ORCHESTRATOR_SHUTDOWN_GRACE)
        .await
        .into_exit_result()
}

#[cfg(test)]
mod tests {
    use super::{
        is_refresh_root_usable, observe_workspace_dirty, refresh_local_changes,
        should_apply_event_to_tui_reducer, shutdown_local_orchestrator_task,
        LocalOrchestratorShutdownOutcome,
    };
    use super::{AppState, OrchestratorEvent, TuiRefreshObservation};
    use crate::events::{ExecutionEvent, RejectionOutcome, StalledBlocker};
    use crate::openspec::{Change, ProposalMetadata};
    use crate::vcs::WorkspaceStatus;
    use std::collections::{HashMap, HashSet};
    use std::path::{Path, PathBuf};
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::mpsc;
    use tokio_util::sync::CancellationToken;

    fn sample_change() -> Change {
        Change {
            id: "change-a".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: ProposalMetadata::default(),
        }
    }

    fn empty_changes_refreshed_event() -> ExecutionEvent {
        ExecutionEvent::ChangesRefreshed {
            changes: vec![sample_change()],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::new(),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::new(),
            worktree_paths: HashMap::<String, PathBuf>::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        }
    }

    fn stalled_blocker() -> StalledBlocker {
        StalledBlocker::acceptance_external(
            "pending_verification",
            "managed verification job still running",
        )
    }

    /// A boundary run's events reach this frontend already applied.
    ///
    /// The regression this pins: the loop used to write the reducer for every
    /// event it received, including the ones the orchestration boundary had
    /// already applied. One `ApplyCompleted` then advanced the apply count
    /// twice — once per frontend path — which is exactly what an authoritative
    /// remote snapshot cannot survive.
    #[tokio::test]
    async fn frontend_delivery_does_not_reapply_the_reducer() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;
        use crate::tui::events::TuiEventSink;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let (frontend_tx, mut frontend_rx) = mpsc::channel::<OrchestratorEvent>(16);
        let sinks: Vec<Arc<dyn EventSink>> = vec![Arc::new(TuiEventSink::new(frontend_tx))];

        for event in [
            ExecutionEvent::ApplyStarted {
                change_id: "change-a".to_string(),
                command: "apply".to_string(),
            },
            ExecutionEvent::ApplyCompleted {
                change_id: "change-a".to_string(),
                revision: String::new(),
            },
        ] {
            crate::events::dispatch_event(&shared_state, &sinks, event).await;
        }
        assert_eq!(shared_state.read().await.apply_count("change-a"), 1);

        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());
        while let Ok(event) = frontend_rx.try_recv() {
            super::sync_reducer_display_caches(&mut app, &shared_state, &event).await;
        }

        assert_eq!(
            shared_state.read().await.apply_count("change-a"),
            1,
            "the frontend applied a delivered event a second time"
        );
    }

    /// A TUI-local producer's event is applied once, by this loop, and reaches
    /// the other frontends through the same authoritative dispatch.
    #[cfg(feature = "web-monitoring")]
    #[tokio::test]
    async fn tui_local_producer_events_are_dispatched_once_to_every_frontend() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;
        use crate::web::state::{WebEventSink, WebState};

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let web_state = Arc::new(WebState::new(&[]));
        web_state.set_shared_state(shared_state.clone()).await;
        let projection = web_state.remote_control().projection();
        let local_sinks: Vec<Arc<dyn EventSink>> =
            vec![Arc::new(WebEventSink::new(web_state.clone()))];

        let event = ExecutionEvent::ApplyCompleted {
            change_id: "change-a".to_string(),
            revision: String::new(),
        };
        crate::events::dispatch_event(&shared_state, &local_sinks, event.clone()).await;

        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());
        super::sync_reducer_display_caches(&mut app, &shared_state, &event).await;

        assert_eq!(
            shared_state.read().await.apply_count("change-a"),
            1,
            "a locally produced event must be applied exactly once"
        );
        let (_, _, sequence) = projection.snapshot();
        assert_eq!(
            sequence, 1,
            "a locally produced event must reach the v2 stream exactly once"
        );
    }

    /// An acceptance blocker whose external prerequisite claim is complete, so
    /// the reducer classifies it as canonical `blocked`.
    fn external_blocker() -> StalledBlocker {
        StalledBlocker::acceptance_external(
            "pending_verification",
            "docker image pull failed: lookup registry-1.docker.io i/o timeout",
        )
    }

    /// A reported hold with no verifiable unblock condition, which the reducer
    /// keeps on the `stalled` path instead of promoting to external `blocked`.
    fn unvalidated_blocker() -> StalledBlocker {
        StalledBlocker {
            category: "no_progress".to_string(),
            phase: "acceptance".to_string(),
            gate: "acceptance_review".to_string(),
            error_summary: "no semantic progress across the retry budget".to_string(),
            evidence: vec!["tasks.md unchanged across two iterations".to_string()],
            unblock_condition: None,
            prerequisite_owner: None,
            next_action: "operator review".to_string(),
            resumable: true,
            worktree_preserved: true,
        }
    }

    /// A persistent TUI holds `Running` while every remaining change waits, and
    /// external lifecycle reporting must say `blocked` rather than `working`.
    ///
    /// The path is deliberately traversed end to end — event dispatch, reducer
    /// blocker classification, display-cache synchronization, snapshot
    /// projection — because the bug lived in the seam between the reducer's
    /// canonical row status and the frontend snapshot, not in either alone.
    #[tokio::test]
    async fn running_tui_projects_blocked_for_reducer_blocked_and_stalled_rows() {
        use crate::events::EventSink;
        use crate::lifecycle_integration::LifecycleState;
        use crate::orchestration::state::OrchestratorState;
        use crate::tui::lifecycle::TuiLifecycleSnapshot;
        use crate::tui::types::AppExecutionMode;

        for (blocker, expected_status) in [
            (external_blocker(), "blocked"),
            (unvalidated_blocker(), "stalled"),
        ] {
            let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
                vec!["change-a".to_string()],
                10,
            )));
            let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
            let mut app = AppState::new(vec![sample_change()]);
            app.set_shared_state(shared_state.clone());
            app.execution_mode = AppExecutionMode::Running;

            for event in [
                ExecutionEvent::AcceptanceStarted {
                    change_id: "change-a".to_string(),
                    command: "accept".to_string(),
                },
                ExecutionEvent::AcceptanceGated {
                    change_id: "change-a".to_string(),
                    blocker: blocker.clone(),
                },
            ] {
                crate::events::dispatch_event(&shared_state, &sinks, event.clone()).await;
                super::sync_reducer_display_caches(&mut app, &shared_state, &event).await;
            }

            assert_eq!(
                app.changes[0].display_status_cache, expected_status,
                "reducer classification must reach the TUI row for {blocker:?}"
            );
            assert_eq!(
                app.execution_mode,
                AppExecutionMode::Running,
                "the persistent process stays Running while it waits"
            );
            assert_eq!(
                TuiLifecycleSnapshot::from_app(&app).lifecycle_state(),
                LifecycleState::Blocked,
                "a {expected_status}-only wait must report blocked"
            );
        }
    }

    /// Once work is active or queued again, the same still-`Running` TUI reports
    /// `working` even while a blocked row remains on screen.
    #[tokio::test]
    async fn active_or_queued_reducer_row_restores_working_lifecycle() {
        use crate::events::EventSink;
        use crate::lifecycle_integration::LifecycleState;
        use crate::orchestration::state::{OrchestratorState, ReducerCommand};
        use crate::tui::lifecycle::TuiLifecycleSnapshot;
        use crate::tui::types::AppExecutionMode;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string(), "change-b".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        let mut change_b = sample_change();
        change_b.id = "change-b".to_string();
        let mut app = AppState::new(vec![sample_change(), change_b]);
        app.set_shared_state(shared_state.clone());
        app.execution_mode = AppExecutionMode::Running;

        let gated = ExecutionEvent::AcceptanceGated {
            change_id: "change-a".to_string(),
            blocker: external_blocker(),
        };
        crate::events::dispatch_event(&shared_state, &sinks, gated.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &gated).await;
        assert_eq!(
            TuiLifecycleSnapshot::from_app(&app).lifecycle_state(),
            LifecycleState::Blocked
        );

        // A queued sibling keeps work admitted for dispatch.
        shared_state
            .write()
            .await
            .apply_command(ReducerCommand::AddToQueue("change-b".to_string()));
        let refresh = empty_changes_refreshed_event();
        crate::events::dispatch_event(&shared_state, &sinks, refresh.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &refresh).await;
        assert_eq!(app.changes[0].display_status_cache, "blocked");
        assert_eq!(app.changes[1].display_status_cache, "queued");
        assert_eq!(
            TuiLifecycleSnapshot::from_app(&app).lifecycle_state(),
            LifecycleState::Working,
            "a queued row alongside a blocked row must report working"
        );

        // And so does an actively executing sibling.
        let started = ExecutionEvent::ApplyStarted {
            change_id: "change-b".to_string(),
            command: "apply".to_string(),
        };
        crate::events::dispatch_event(&shared_state, &sinks, started.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &started).await;
        assert_eq!(app.changes[1].display_status_cache, "applying");
        assert_eq!(
            TuiLifecycleSnapshot::from_app(&app).lifecycle_state(),
            LifecycleState::Working,
            "an active row alongside a blocked row must report working"
        );
    }

    /// The production ordering that used to repaint a healthy Archive.
    ///
    /// `ArchiveStarted` → reducer-cache synchronization → a `ChangesRefreshed`
    /// whose `merge_wait_ids` carries the same change. The archive commit is
    /// real by then, so repository inspection legitimately reports an
    /// archived-but-not-integrated workspace — but Archive has not returned, and
    /// the row must not tell the operator that manual intervention is due. The
    /// reducer refuses the downgrade; the TUI's own refresh handling must too.
    #[tokio::test]
    async fn archive_refresh_preserves_reducer_owned_archiving_row() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());
        app.changes[0].selected = true;
        app.publish_execution_marks();

        let archiving = ExecutionEvent::ArchiveStarted {
            change_id: "change-a".to_string(),
            command: "archive".to_string(),
        };
        crate::events::dispatch_event(&shared_state, &sinks, archiving.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &archiving).await;
        app.handle_orchestrator_event(archiving);
        assert_eq!(app.changes[0].display_status_cache, "archiving");

        let queued_before = shared_state.read().await.queued_change_ids();

        // The five-second scan sees the archive commit that Archive itself just
        // created, with the change not yet integrated into base.
        let refresh = ExecutionEvent::ChangesRefreshed {
            changes: vec![sample_change()],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::from(["change-a".to_string()]),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["change-a".to_string()]),
            worktree_paths: HashMap::<String, PathBuf>::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::from(["change-a".to_string()]),
        };
        crate::events::dispatch_event(&shared_state, &sinks, refresh.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &refresh).await;
        app.handle_orchestrator_event(refresh);

        assert_eq!(
            app.changes[0].display_status_cache, "archiving",
            "refresh merge-wait evidence repainted an in-flight Archive row"
        );
        assert_eq!(
            shared_state.read().await.display_status("change-a"),
            "archiving",
            "the reducer must still own the active archive lifecycle"
        );
        assert_eq!(
            shared_state.read().await.queued_change_ids(),
            queued_before,
            "a presentation-only refresh must not change queue intent"
        );
        assert!(
            app.changes[0].selected,
            "a presentation-only refresh must not clear the execution mark"
        );
    }

    // ========================================================================
    // Changes row layout: reducer archive-completion synchronization
    //
    // Integration evidence: a real `OrchestratorState`, real event dispatch, and
    // the real TUI cache-synchronization and refresh paths. The reducer is what
    // owns the archive milestone; these prove the TUI reads it rather than
    // inferring "post-archive" from the `resolving` display string.
    // ========================================================================

    /// The reducer records archive completion while truthfully advancing the row
    /// to a live post-archive status, and the TUI adopts both facts at once.
    #[tokio::test]
    async fn tui_change_row_layout_archive_sync_adopts_the_reducer_archive_record() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());

        assert!(
            !app.changes[0].archive_complete_cache,
            "no archive is on record before the event"
        );

        let archived = ExecutionEvent::ChangeArchived("change-a".to_string());
        crate::events::dispatch_event(&shared_state, &sinks, archived.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &archived).await;

        // The reducer's own view: archived, and already moved on to post-archive
        // resolve handling. Neither fact is derivable from the other.
        assert!(shared_state.read().await.is_archived("change-a"));
        assert_eq!(
            app.changes[0].display_status_cache, "resolving",
            "the row must show the reducer's truthful post-archive status"
        );
        assert!(
            app.changes[0].archive_complete_cache,
            "the archive milestone must reach the row as presentation evidence"
        );
        assert_eq!(
            app.reducer_archived_changes(),
            &HashSet::from(["change-a".to_string()])
        );
    }

    /// One `ChangesRefreshed` event carrying `change-a` as an active change.
    fn archive_refresh_event() -> ExecutionEvent {
        ExecutionEvent::ChangesRefreshed {
            changes: vec![sample_change()],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::from(["change-a".to_string()]),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["change-a".to_string()]),
            worktree_paths: HashMap::<String, PathBuf>::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::from(["change-a".to_string()]),
        }
    }

    /// A row the refresh pass *constructs* adopts the retained archive evidence.
    ///
    /// The regression this pins: `ChangeState::from_change` knows nothing about
    /// the reducer, so a row built during refresh came back with no archive
    /// evidence and would render an empty `[ ]` for a change the reducer had
    /// already archived. The app-level snapshot is what closes that, and it has to
    /// be reapplied inside the refresh pass rather than one reducer sync later —
    /// refresh handling runs *after* cache synchronization in the run loop, so
    /// anything it leaves wrong is what the next frame draws.
    #[tokio::test]
    async fn tui_change_row_layout_archive_sync_survives_refresh_reconstruction() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        // No rows yet: the refresh pass below is what materializes this one.
        let mut app = AppState::new(Vec::new());
        app.set_shared_state(shared_state.clone());

        let archived = ExecutionEvent::ChangeArchived("change-a".to_string());
        crate::events::dispatch_event(&shared_state, &sinks, archived.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &archived).await;
        assert!(app.changes.is_empty());
        assert_eq!(
            app.reducer_archived_changes(),
            &HashSet::from(["change-a".to_string()]),
            "the snapshot is retained even with no row to apply it to"
        );

        let refresh = archive_refresh_event();
        crate::events::dispatch_event(&shared_state, &sinks, refresh.clone()).await;
        app.handle_orchestrator_event(refresh.clone());

        assert_eq!(app.changes.len(), 1, "refresh constructed the row");
        assert!(
            app.changes[0].archive_complete_cache,
            "refresh reconstruction must reapply the retained archive evidence \
             in the same pass, not one reducer sync later"
        );

        // And the following reducer sync agrees rather than correcting it.
        super::sync_reducer_display_caches(&mut app, &shared_state, &refresh).await;
        assert!(app.changes[0].archive_complete_cache);
    }

    /// Refresh must not use a reactivated proposal directory to retire the
    /// archive evidence either.
    ///
    /// Refresh resets a row it observes as `archived` back to `not queued` when the
    /// proposal is present again. That reset is display-status work; the reducer's
    /// archive record is not refresh's to revoke, so the checkbox stays hidden.
    #[tokio::test]
    async fn tui_change_row_layout_archive_sync_refresh_does_not_revoke_the_archive_record() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());

        let archived = ExecutionEvent::ChangeArchived("change-a".to_string());
        crate::events::dispatch_event(&shared_state, &sinks, archived.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &archived).await;

        // Post-archive merge readiness parks the row on a base-lane wait, which
        // is a live non-terminal status and not a terminal one.
        let deferred = ExecutionEvent::MergeDeferred {
            change_id: "change-a".to_string(),
            reason: "waiting for base".to_string(),
            auto_resumable: false,
        };
        crate::events::dispatch_event(&shared_state, &sinks, deferred.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &deferred).await;
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert!(app.changes[0].archive_complete_cache);

        // The row's own refresh reset path, reached by presenting it as archived
        // with the proposal directory present again and no merge-wait evidence to
        // restore the terminal status.
        app.changes[0].set_display_status_cache("archived");
        let refresh = ExecutionEvent::ChangesRefreshed {
            changes: vec![sample_change()],
            rejected_changes: Vec::new(),
            committed_change_ids: HashSet::from(["change-a".to_string()]),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["change-a".to_string()]),
            worktree_paths: HashMap::<String, PathBuf>::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::new(),
        };
        app.handle_orchestrator_event(refresh);

        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "refresh still owns the display-status reset"
        );
        assert!(
            app.changes[0].archive_complete_cache,
            "but it must not clear the reducer's archive record"
        );
    }

    /// A `resolving` row with no reducer archive record stays a plain active row.
    ///
    /// This is the control for the whole design: a fresh process that resolves a
    /// retry shows `resolving` without having archived anything, and inferring
    /// post-archive state from that string would retire a live run candidate.
    #[tokio::test]
    async fn tui_change_row_layout_archive_sync_leaves_a_fresh_resolving_row_alone() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());

        let resolving = ExecutionEvent::ResolveStarted {
            change_id: "change-a".to_string(),
            command: "resolve".to_string(),
        };
        crate::events::dispatch_event(&shared_state, &sinks, resolving.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &resolving).await;

        assert_eq!(app.changes[0].display_status_cache, "resolving");
        assert!(
            !shared_state.read().await.is_archived("change-a"),
            "no archive happened in this process"
        );
        assert!(
            !app.changes[0].archive_complete_cache,
            "an identical display status must not manufacture archive evidence"
        );
    }

    /// The exact observed force-stop order must leave `accepting` behind.
    ///
    /// `AcceptanceStarted` → authoritative `Stopped` dispatch → reducer-cache
    /// synchronization → local stopped handling → a later `ChangesRefreshed`.
    /// Before the reducer owned the stop, step three re-read an untouched
    /// `accepting`, and step five could restore it even after the agent process
    /// and the scheduler had already stopped.
    #[tokio::test]
    async fn stopped_reducer_sync_prevents_accepting_resurrection() {
        use crate::events::EventSink;
        use crate::orchestration::state::OrchestratorState;
        use crate::tui::types::AppExecutionMode;

        let shared_state = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            10,
        )));
        let sinks: Vec<Arc<dyn EventSink>> = Vec::new();
        let mut app = AppState::new(vec![sample_change()]);
        app.set_shared_state(shared_state.clone());
        app.execution_mode = AppExecutionMode::Running;
        // The operator marked this change for execution; a stop must not clear
        // the mark, because F5 resume is what converts it back into intent.
        app.changes[0].selected = true;
        app.publish_execution_marks();

        let accepting = ExecutionEvent::AcceptanceStarted {
            change_id: "change-a".to_string(),
            command: "accept".to_string(),
        };
        crate::events::dispatch_event(&shared_state, &sinks, accepting.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &accepting).await;
        assert_eq!(app.changes[0].display_status_cache, "accepting");

        let stopped = ExecutionEvent::Stopped;
        crate::events::dispatch_event(&shared_state, &sinks, stopped.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &stopped).await;
        app.handle_orchestrator_event(stopped);

        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "the reducer-derived stop did not reach the TUI row"
        );
        assert_eq!(app.execution_mode, AppExecutionMode::Stopped);

        // The refresh scan still sees the workspace the stopped run left behind.
        let refresh = ExecutionEvent::ChangesRefreshed {
            changes: vec![sample_change()],
            rejected_changes: Vec::new(),
            // Committed and clean, so the row stays parallel-eligible and the
            // separate ineligibility cleanup cannot be what clears its mark.
            committed_change_ids: HashSet::from(["change-a".to_string()]),
            uncommitted_file_change_ids: HashSet::new(),
            worktree_change_ids: HashSet::from(["change-a".to_string()]),
            worktree_paths: HashMap::<String, PathBuf>::new(),
            worktree_not_ahead_ids: HashSet::new(),
            merge_wait_ids: HashSet::from(["change-a".to_string()]),
        };
        crate::events::dispatch_event(&shared_state, &sinks, refresh.clone()).await;
        super::sync_reducer_display_caches(&mut app, &shared_state, &refresh).await;
        app.handle_orchestrator_event(refresh);

        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "a later refresh restored an interrupted status after the run stopped"
        );
        assert_eq!(
            shared_state.read().await.display_status("change-a"),
            "not queued"
        );
        assert!(
            app.changes[0].selected,
            "the execution mark must survive so the row stays resumable"
        );
    }

    #[test]
    fn tui_reducer_sync_includes_running_lifecycle_display_events() {
        let reducer_visible_events = vec![
            ExecutionEvent::ProcessingStarted("change-a".to_string()),
            ExecutionEvent::ProcessingError {
                id: "change-a".to_string(),
                error: "boom".to_string(),
            },
            ExecutionEvent::ApplyStarted {
                change_id: "change-a".to_string(),
                command: "apply".to_string(),
            },
            ExecutionEvent::ApplyCompleted {
                change_id: "change-a".to_string(),
                revision: "rev-a".to_string(),
            },
            ExecutionEvent::ApplyFailed {
                change_id: "change-a".to_string(),
                error: "boom".to_string(),
            },
            ExecutionEvent::AcceptanceStarted {
                change_id: "change-a".to_string(),
                command: "accept".to_string(),
            },
            ExecutionEvent::AcceptanceCompleted {
                change_id: "change-a".to_string(),
            },
            ExecutionEvent::AcceptanceFailed {
                change_id: "change-a".to_string(),
                error: "boom".to_string(),
            },
            ExecutionEvent::ArchiveStarted {
                change_id: "change-a".to_string(),
                command: "archive".to_string(),
            },
            ExecutionEvent::ArchiveResumed {
                change_id: "change-a".to_string(),
                reason: Some("resume".to_string()),
                summary: Some("resume archive".to_string()),
            },
            ExecutionEvent::ArchiveRetryScheduled {
                change_id: "change-a".to_string(),
                attempt: 1,
                max_attempts: 2,
                reason: Some("retry".to_string()),
                summary: Some("retry archive".to_string()),
            },
            ExecutionEvent::ChangeArchived("change-a".to_string()),
            ExecutionEvent::ArchiveFailed {
                change_id: "change-a".to_string(),
                error: "boom".to_string(),
                reason: Some("failed".to_string()),
                summary: Some("archive failed".to_string()),
            },
            ExecutionEvent::MergeDeferred {
                change_id: "change-a".to_string(),
                reason: "dirty base".to_string(),
                auto_resumable: true,
            },
            ExecutionEvent::MergeCompleted {
                change_id: "change-a".to_string(),
                revision: "rev-a".to_string(),
            },
            ExecutionEvent::ResolveStarted {
                change_id: "change-a".to_string(),
                command: "resolve".to_string(),
            },
            ExecutionEvent::ResolveCompleted {
                change_id: "change-a".to_string(),
                worktree_change_ids: None,
            },
            ExecutionEvent::ResolveFailed {
                change_id: "change-a".to_string(),
                error: "boom".to_string(),
            },
            ExecutionEvent::WorkspaceStatusUpdated {
                change_id: "change-a".to_string(),
                workspace_name: "ws-a".to_string(),
                status: WorkspaceStatus::Applying,
            },
            ExecutionEvent::RejectionReviewCompleted {
                change_id: "change-a".to_string(),
                outcome: RejectionOutcome::Resume,
            },
            ExecutionEvent::RejectionReviewFailed {
                change_id: "change-a".to_string(),
                error: "boom".to_string(),
            },
            ExecutionEvent::DependencyBlocked {
                change_id: "change-a".to_string(),
                dependency_ids: vec!["dep".to_string()],
            },
            ExecutionEvent::DependencyResolved {
                change_id: "change-a".to_string(),
            },
            ExecutionEvent::AcceptanceGated {
                change_id: "change-a".to_string(),
                blocker: stalled_blocker(),
            },
            ExecutionEvent::ExecutionBlocked {
                change_id: "change-a".to_string(),
                blocker: stalled_blocker(),
            },
            ExecutionEvent::ChangeDequeued {
                change_id: "change-a".to_string(),
            },
            ExecutionEvent::ChangeStopped {
                change_id: "change-a".to_string(),
            },
            ExecutionEvent::Stopped,
            empty_changes_refreshed_event(),
        ];

        for event in reducer_visible_events {
            assert!(
                should_apply_event_to_tui_reducer(&event),
                "event should sync to TUI reducer before display snapshot: {event:?}"
            );
        }
    }

    #[test]
    fn tui_reducer_sync_excludes_presentation_only_events() {
        let presentation_events = vec![
            ExecutionEvent::ApplyOutput {
                change_id: "change-a".to_string(),
                output: "chunk".to_string(),
                iteration: Some(1),
            },
            ExecutionEvent::ProgressUpdated {
                change_id: "change-a".to_string(),
                completed: 1,
                total: 2,
            },
            ExecutionEvent::Log(crate::events::LogEntry::info("hello")),
            ExecutionEvent::WorktreesRefreshed { worktrees: vec![] },
        ];

        for event in presentation_events {
            assert!(
                !should_apply_event_to_tui_reducer(&event),
                "presentation-only event should not sync to TUI reducer: {event:?}"
            );
        }
    }

    #[test]
    fn refresh_root_usable_for_existing_directory() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        assert!(is_refresh_root_usable(temp_dir.path()));
    }

    #[test]
    fn refresh_root_not_usable_for_missing_directory() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let missing_path = temp_dir.path().join("missing-root");
        assert!(!is_refresh_root_usable(&missing_path));
    }

    #[test]
    fn stale_refresh_root_sets_warned_once_and_resets_when_root_recovers() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let missing_path = temp_dir.path().join("missing-root");
        let mut warned = false;

        assert!(super::should_skip_local_refresh(&missing_path, &mut warned));
        assert!(warned, "first stale root check should set warned flag");

        assert!(super::should_skip_local_refresh(&missing_path, &mut warned));
        assert!(warned, "second stale root check keeps warned flag set");

        assert!(!super::should_skip_local_refresh(
            temp_dir.path(),
            &mut warned
        ));
        assert!(!warned, "usable root should reset warned flag");
    }

    #[test]
    fn local_refresh_not_skipped_for_existing_root() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let mut warned = false;

        assert!(!super::should_skip_local_refresh(
            temp_dir.path(),
            &mut warned
        ));
        assert!(
            !warned,
            "existing root should not trigger stale warning suppression"
        );
    }

    #[test]
    fn refresh_local_changes_uses_explicit_repo_root_for_active_and_rejected_rows() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let repo_dir = tempfile::tempdir().expect("repo tempdir");
        let other_dir = tempfile::tempdir().expect("cwd tempdir");
        let changes_dir = repo_dir.path().join("openspec").join("changes");

        let active_dir = changes_dir.join("change-active");
        std::fs::create_dir_all(&active_dir).expect("active dir");
        std::fs::write(active_dir.join("proposal.md"), "# proposal").expect("active proposal");
        std::fs::write(active_dir.join("tasks.md"), "- [ ] task").expect("active tasks");

        let rejected_dir = changes_dir.join("change-rejected");
        std::fs::create_dir_all(&rejected_dir).expect("rejected dir");
        std::fs::write(rejected_dir.join("proposal.md"), "# proposal").expect("rejected proposal");
        std::fs::write(rejected_dir.join("tasks.md"), "- [ ] task").expect("rejected tasks");
        std::fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED").expect("rejected marker");

        let original_dir = std::env::current_dir().expect("cwd");
        std::env::set_current_dir(other_dir.path()).expect("set cwd elsewhere");

        let (active, rejected) = refresh_local_changes(repo_dir.path()).expect("refresh succeeds");

        std::env::set_current_dir(original_dir).expect("restore cwd");

        assert_eq!(
            active.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(),
            vec!["change-active"]
        );
        assert_eq!(
            rejected.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(),
            vec!["change-rejected"]
        );
    }

    async fn run_git_ok(cwd: &Path, args: &[&str]) {
        let output = tokio::process::Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .await
            .expect("git command should start");
        assert!(
            output.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// A committed repository with deterministic identity, so `git status` has a
    /// HEAD to compare against and inherits no developer configuration.
    async fn init_dirty_state_repo(root: &Path) {
        run_git_ok(root, &["init", "-b", "main"]).await;
        run_git_ok(root, &["config", "user.email", "test@example.com"]).await;
        run_git_ok(root, &["config", "user.name", "Test User"]).await;
        std::fs::write(root.join("tracked.txt"), "base\n").expect("tracked file");
        run_git_ok(root, &["add", "."]).await;
        run_git_ok(root, &["commit", "-m", "base"]).await;
    }

    /// One refresh tick's observation, reduced to the fact the header renders.
    async fn observed_dirty(root: &Path) -> Option<bool> {
        let mut warned = false;
        observe_workspace_dirty(root, &mut warned)
            .await
            .map(|observation| match observation {
                TuiRefreshObservation::WorkspaceDirty { dirty } => dirty,
            })
    }

    /// Every form of operator work the badge is supposed to catch, and the
    /// return to clean that removes it again — on one real repository.
    #[tokio::test]
    async fn refresh_workspace_dirty_observes_staged_unstaged_and_untracked_work() {
        let repo = tempfile::tempdir().expect("repo tempdir");
        init_dirty_state_repo(repo.path()).await;

        assert_eq!(
            observed_dirty(repo.path()).await,
            Some(false),
            "a freshly committed repository is clean"
        );

        // Staged.
        std::fs::write(repo.path().join("staged.txt"), "staged\n").expect("staged file");
        run_git_ok(repo.path(), &["add", "staged.txt"]).await;
        assert_eq!(
            observed_dirty(repo.path()).await,
            Some(true),
            "a staged change is dirty"
        );

        run_git_ok(repo.path(), &["reset"]).await;
        std::fs::remove_file(repo.path().join("staged.txt")).expect("remove staged file");
        assert_eq!(observed_dirty(repo.path()).await, Some(false));

        // Unstaged tracked-file change, then the clean-after-dirty transition.
        std::fs::write(repo.path().join("tracked.txt"), "edited\n").expect("edit tracked file");
        assert_eq!(
            observed_dirty(repo.path()).await,
            Some(true),
            "an unstaged tracked-file change is dirty"
        );
        run_git_ok(repo.path(), &["checkout", "--", "tracked.txt"]).await;
        assert_eq!(
            observed_dirty(repo.path()).await,
            Some(false),
            "a later successful observation reports the workspace clean again"
        );

        // Untracked, under configuration that would otherwise suppress it.
        run_git_ok(repo.path(), &["config", "status.showUntrackedFiles", "no"]).await;
        std::fs::write(repo.path().join("untracked.txt"), "new\n").expect("untracked file");
        assert_eq!(
            observed_dirty(repo.path()).await,
            Some(true),
            "status.showUntrackedFiles=no must not make untracked work report as clean"
        );
    }

    /// Generated content is not operator work, so it must not raise the badge.
    #[tokio::test]
    async fn refresh_workspace_dirty_excludes_ignored_files() {
        let repo = tempfile::tempdir().expect("repo tempdir");
        init_dirty_state_repo(repo.path()).await;
        std::fs::write(repo.path().join(".gitignore"), "generated/\n").expect("gitignore");
        run_git_ok(repo.path(), &["add", ".gitignore"]).await;
        run_git_ok(repo.path(), &["commit", "-m", "ignore generated"]).await;

        std::fs::create_dir_all(repo.path().join("generated")).expect("generated dir");
        std::fs::write(repo.path().join("generated").join("out.txt"), "built\n")
            .expect("generated file");

        assert_eq!(
            observed_dirty(repo.path()).await,
            Some(false),
            "ignored files alone are not dirty"
        );
    }

    /// The badge reports the root the TUI captured at startup. A later process
    /// current-directory change is not allowed to retarget it.
    // The guard must span the awaits: it is what keeps a concurrent test from
    // seeing the process current directory this test moves.
    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn refresh_workspace_dirty_uses_the_captured_root_not_the_process_cwd() {
        let _lock = crate::test_support::cwd_lock()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let captured = tempfile::tempdir().expect("captured tempdir");
        let other = tempfile::tempdir().expect("other tempdir");
        init_dirty_state_repo(captured.path()).await;
        init_dirty_state_repo(other.path()).await;
        std::fs::write(captured.path().join("untracked.txt"), "work\n").expect("dirty file");

        let original_dir = std::env::current_dir().expect("cwd");
        std::env::set_current_dir(other.path()).expect("set cwd elsewhere");

        let from_captured = observed_dirty(captured.path()).await;
        let from_other = observed_dirty(other.path()).await;

        std::env::set_current_dir(original_dir).expect("restore cwd");

        assert_eq!(
            from_captured,
            Some(true),
            "the captured root is dirty and must be what the header reports"
        );
        assert_eq!(
            from_other,
            Some(false),
            "the process current directory is clean, which is not the observed fact"
        );
    }

    /// A failed read has no answer, so it publishes nothing and the last
    /// successful observation stands. The warning is bounded per failure episode.
    #[tokio::test]
    async fn refresh_workspace_dirty_failure_preserves_the_last_successful_observation() {
        let repo = tempfile::tempdir().expect("repo tempdir");
        init_dirty_state_repo(repo.path()).await;
        std::fs::write(repo.path().join("untracked.txt"), "work\n").expect("dirty file");

        let mut app = AppState::new(vec![sample_change()]);
        let mut warned = false;
        let observation = observe_workspace_dirty(repo.path(), &mut warned)
            .await
            .expect("a readable repository observes");
        app.adopt_workspace_dirty_observation(observation);
        assert_eq!(
            app.workspace_dirty(),
            crate::tui::types::WorkspaceDirtyState::Dirty
        );
        assert!(!warned, "a successful read never warns");

        // A directory that is not a Git repository at all: the read fails.
        let unreadable = tempfile::tempdir().expect("non-repo tempdir");
        assert!(
            observe_workspace_dirty(unreadable.path(), &mut warned)
                .await
                .is_none(),
            "a failed read must publish no observation"
        );
        assert!(warned, "the first failure of an episode warns");
        assert!(observe_workspace_dirty(unreadable.path(), &mut warned)
            .await
            .is_none());
        assert!(
            warned,
            "the repeated failure stays inside the same bounded warning"
        );
        assert_eq!(
            app.workspace_dirty(),
            crate::tui::types::WorkspaceDirtyState::Dirty,
            "the failed reads must not have replaced the observation with clean"
        );

        // Recovery re-arms the bound, so a new failure episode is reported.
        let recovered = observe_workspace_dirty(repo.path(), &mut warned)
            .await
            .expect("the readable repository observes again");
        app.adopt_workspace_dirty_observation(recovered);
        assert!(!warned, "a success closes the failure episode");
        assert_eq!(
            app.workspace_dirty(),
            crate::tui::types::WorkspaceDirtyState::Dirty
        );
    }

    #[tokio::test]
    async fn shutdown_local_orchestrator_cancels_and_aborts_non_finishing_task() {
        let token = CancellationToken::new();
        let task_token = token.clone();
        let (cancelled_tx, cancelled_rx) = tokio::sync::oneshot::channel();
        let (post_abort_tx, mut post_abort_rx) = tokio::sync::mpsc::channel::<()>(1);

        let handle = tokio::spawn(async move {
            task_token.cancelled().await;
            let _ = cancelled_tx.send(());
            tokio::time::sleep(Duration::from_secs(60)).await;
            loop {
                let _ = post_abort_tx.send(()).await;
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
            #[allow(unreachable_code)]
            Ok(())
        });

        let outcome = shutdown_local_orchestrator_task(
            Some(handle),
            Some(token),
            None,
            Duration::from_millis(10),
        )
        .await;

        assert_eq!(
            outcome,
            LocalOrchestratorShutdownOutcome::AbortedAfterTimeout
        );
        assert!(
            cancelled_rx.await.is_ok(),
            "shutdown should cancel orchestrator token"
        );
        tokio::task::yield_now().await;
        let post_cleanup_event =
            tokio::time::timeout(Duration::from_millis(80), post_abort_rx.recv()).await;
        assert!(
            !matches!(post_cleanup_event, Ok(Some(()))),
            "aborted local orchestrator must not keep sending events after cleanup"
        );
    }

    #[tokio::test]
    async fn shutdown_local_orchestrator_without_handle_is_noop() {
        let outcome =
            shutdown_local_orchestrator_task(None, None, None, Duration::from_millis(1)).await;

        assert_eq!(outcome, LocalOrchestratorShutdownOutcome::NoTask);
    }

    /// Local quit is a cancellation boundary for the run this TUI started.
    ///
    /// Three things had to hold together and previously did not: the command
    /// scope must close at cancellation time rather than after a grace period,
    /// that grace must not expire before the scheduler's own cancellation
    /// boundary has had its chance, and a timeout must force-clean the retained
    /// process identities *before* the task is aborted — because abort destroys
    /// the only in-task path to them and is not cleanup evidence by itself.
    ///
    /// The real process boundary is covered by
    /// `run_scope_tui_quit_cleans_process_group_after_timeout` in
    /// `tests/process_cleanup_test.rs`; this pins the control flow.
    #[tokio::test]
    async fn local_tui_shutdown_waits_for_run_command_scope() {
        use crate::ai_command_runner::RunCommandScope;
        use crate::tui::orchestrator::PARALLEL_CANCELLATION_CLEANUP_DEADLINE;

        // The grace must not undercut the scheduler's outer cancellation
        // boundary, or the TUI aborts the very cleanup it is waiting for.
        assert!(
            super::LOCAL_ORCHESTRATOR_SHUTDOWN_GRACE >= PARALLEL_CANCELLATION_CLEANUP_DEADLINE,
            "local shutdown grace {:?} undercuts the scheduler boundary {:?}",
            super::LOCAL_ORCHESTRATOR_SHUTDOWN_GRACE,
            PARALLEL_CANCELLATION_CLEANUP_DEADLINE
        );

        // Graceful completion: the scope closes at cancellation time, and the
        // task is joined rather than aborted.
        let scope = RunCommandScope::new();
        let token = CancellationToken::new();
        let task_token = token.clone();
        let handle = tokio::spawn(async move {
            task_token.cancelled().await;
            Ok(())
        });
        let outcome = shutdown_local_orchestrator_task(
            Some(handle),
            Some(token),
            Some(scope.clone()),
            Duration::from_secs(5),
        )
        .await;
        assert_eq!(outcome, LocalOrchestratorShutdownOutcome::Graceful);
        assert!(
            scope.is_closed() && scope.cancel_token().is_cancelled(),
            "quit closes run command admission immediately, not after the grace period"
        );

        // Timeout escalation: a retained owned identity is force-cleaned and
        // verified before the task is aborted.
        let dead = std::process::Command::new("sh")
            .arg("-c")
            .arg("exit 0")
            .spawn()
            .expect("spawn");
        let pid = dead.id();
        let mut dead = dead;
        let _ = dead.wait();

        let scope = RunCommandScope::new();
        scope
            .register_unproven_for_test("apply", Some("change-a"), pid)
            .release_confirmed();
        assert_eq!(scope.retained_process_ids(), vec![pid]);

        let token = CancellationToken::new();
        let handle = tokio::spawn(async move {
            std::future::pending::<()>().await;
            Ok(())
        });
        let outcome = shutdown_local_orchestrator_task(
            Some(handle),
            Some(token),
            Some(scope.clone()),
            Duration::from_millis(20),
        )
        .await;
        assert_eq!(
            outcome,
            LocalOrchestratorShutdownOutcome::AbortedAfterTimeout,
            "timeout stays distinguishable from graceful completion"
        );
        assert!(
            scope.retained_process_ids().is_empty(),
            "retained owned identities must be cleaned and verified before task abort"
        );

        // Remote mode: no local run means no handle and no scope, and nothing
        // here reaches the remote server.
        assert_eq!(
            shutdown_local_orchestrator_task(None, None, None, Duration::from_millis(1)).await,
            LocalOrchestratorShutdownOutcome::NoTask
        );
    }
}