scud-cli 1.67.0

Fast, simple task master for AI-driven development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
//! Swarm mode - Parallel execution with multiple strategies
//!
//! Executes tasks using parallel agents with two main modes:
//!
//! ## Wave Mode (default)
//! Executes tasks in dependency-order waves using parallel agents.
//! After each wave, runs backpressure validation (build, lint, test).
//!
//! Flow:
//! 1. [Optional] Research phase: Smart model analyzes tasks, may expand complex ones
//! 2. Build phase: Fast models execute tasks in parallel rounds
//! 3. Validate phase: Runs backpressure tests (compile, lint, test), smart model fixes issues
//! 4. Repeat for next wave
//!
//! ## Beads Mode (`--swarm-mode beads`)
//! Continuous ready-task polling inspired by Beads/Gas Town patterns.
//! Tasks execute immediately when dependencies are met, no batch waiting.
//!
//! Flow:
//! 1. Query for ready tasks (all dependencies Done)
//! 2. Claim task (mark in-progress)
//! 3. Spawn agent
//! 4. Immediately loop back to step 1 (no waiting for batch)
//!
//! Usage:
//!   scud swarm --tag <tag>                           # Wave mode with tmux (default)
//!   scud swarm --tag <tag> --swarm-mode beads        # Beads continuous execution
//!   scud swarm --tag <tag> --swarm-mode extensions   # Wave mode with async subprocesses
//!   scud swarm --tag <tag> --no-research             # Skip research, use tasks as-is
//!   scud swarm --tag <tag> --no-validate             # Skip backpressure validation

pub mod beads;
pub mod events;
pub mod publisher;
pub mod runtime;
pub mod session;
pub mod transcript;
pub mod zmq_client;

/// Re-export backpressure module for backward compatibility.
///
/// The canonical location is now [`crate::backpressure`], but this re-export
/// maintains the old path `scud::commands::swarm::backpressure` for existing code.
pub use crate::backpressure;

use anyhow::Result;
use colored::Colorize;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use self::runtime::SwarmRuntime;
use crate::commands::helpers::resolve_group_tag;
use crate::commands::spawn::agent;
use crate::commands::spawn::headless::{self, store::SessionStatus, StreamStore};
use crate::commands::spawn::hooks;
use crate::commands::spawn::monitor::{self, SpawnSession};
use crate::commands::spawn::terminal::{self, Harness};
use crate::commands::spawn::tui;
use crate::models::phase::Phase;
use crate::models::task::{Task, TaskStatus};
use crate::storage::Storage;
use std::path::Path;

use self::session::{acquire_session_lock, RoundState, SwarmSession, WaveState, WaveSummary};
use crate::agents::AgentDef;
use crate::attribution::{attribute_failure, AttributionConfidence};
use crate::backpressure::{BackpressureConfig, ValidationResult};
use crate::commands::task_selection::{count_in_progress_tasks, is_actionable_pending_task};
use crate::transcript_watcher::TranscriptWatcher;

/// Swarm execution mode
pub use crate::SwarmMode;

/// Configuration for a swarm execution session.
pub struct SwarmConfig {
    pub project_root: Option<PathBuf>,
    pub tag: Option<String>,
    pub round_size: usize,
    pub all_tags: bool,
    pub harness_arg: String,
    pub swarm_mode: SwarmMode,
    pub dry_run: bool,
    pub session_name: Option<String>,
    pub no_research: bool,
    pub no_validate: bool,
    pub review: bool,
    pub review_all: bool,
    pub no_repair: bool,
    pub max_repair_attempts: usize,
    pub no_worktree: bool,
    pub salvo_dir: Option<PathBuf>,
    pub stale_timeout_minutes: Option<u64>,
    pub idle_timeout_minutes: u64,
    pub no_publish_events: bool,
    pub pause_flag: Option<Arc<AtomicBool>>,
    pub stop_flag: Option<Arc<AtomicBool>>,
}

/// Main entry point for the swarm command
pub async fn run(config: SwarmConfig) -> Result<()> {
    // Destructure config for use throughout the function
    let SwarmConfig {
        project_root,
        tag,
        round_size,
        all_tags,
        harness_arg,
        swarm_mode,
        dry_run,
        session_name,
        no_research,
        no_validate,
        review,
        review_all,
        no_repair,
        max_repair_attempts,
        no_worktree,
        salvo_dir,
        stale_timeout_minutes,
        idle_timeout_minutes,
        no_publish_events,
        pause_flag,
        stop_flag,
    } = config;

    let tag = tag.as_deref();
    let harness_arg = &harness_arg;
    let effective_tag = tag.unwrap_or("default");

    if round_size == 0 {
        anyhow::bail!("--round-size must be at least 1");
    }

    let storage = Storage::new(project_root.clone());

    if !storage.is_initialized() {
        anyhow::bail!("SCUD not initialized. Run: scud init");
    }

    let runtime = SwarmRuntime::from(swarm_mode);
    runtime.ensure_requirements()?;

    // Determine phase tag
    let phase_tag = if all_tags {
        "all".to_string()
    } else {
        resolve_group_tag(&storage, tag, true)?
    };

    // Acquire session lock to prevent concurrent swarm runs on same tag
    // Lock is held for the duration of the function and released on drop
    let _session_lock = if !dry_run {
        Some(acquire_session_lock(project_root.as_ref(), &phase_tag)?)
    } else {
        None
    };

    // Parse harness and validate binary exists
    let harness = Harness::parse(harness_arg)?;
    terminal::find_harness_binary(harness)?;

    // Generate session name
    let session_name = session_name.unwrap_or_else(|| format!("swarm-{}", effective_tag));

    // Get working directory
    let original_working_dir = project_root
        .clone()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Determine actual working directory (may be a salvo worktree)
    let (working_dir, is_salvo_worktree, main_project_root) = if !no_worktree && !all_tags {
        if let Some(tag_name) = tag {
            match crate::commands::salvo::ensure_worktree(
                &original_working_dir,
                tag_name,
                salvo_dir.as_deref(),
            ) {
                Ok(wt_path) => (wt_path, true, Some(original_working_dir.clone())),
                Err(e) => {
                    eprintln!("Warning: Could not create salvo worktree: {}", e);
                    eprintln!("Running in-place (use --no-worktree to suppress this warning)");
                    (original_working_dir.clone(), false, None)
                }
            }
        } else {
            (original_working_dir.clone(), false, None)
        }
    } else {
        (original_working_dir.clone(), false, None)
    };

    // Load backpressure configuration
    let bp_config = BackpressureConfig::load(project_root.as_ref())?;

    // Start transcript watcher in background thread
    if !dry_run {
        let watcher_session = session_name.clone();
        let watcher_root = working_dir.clone();
        let _watcher_handle = std::thread::spawn(move || {
            let db = std::sync::Arc::new(crate::db::Database::new(&watcher_root));
            if db.initialize().is_err() {
                return;
            }
            let watcher = TranscriptWatcher::new(&watcher_root, db);
            if let Err(e) = watcher.watch(&watcher_session) {
                eprintln!("Transcript watcher error: {}", e);
            }
        });
    }

    // Display header
    println!("{}", "SCUD Swarm Mode".cyan().bold());
    println!("{}", "".repeat(50));
    println!("{:<20} {}", "Tag:".dimmed(), phase_tag.green());
    println!(
        "{:<20} {}",
        "Round size:".dimmed(),
        round_size.to_string().cyan()
    );
    println!(
        "{:<20} {}",
        "Research:".dimmed(),
        if no_research {
            "skip".yellow()
        } else {
            "enabled".green()
        }
    );
    println!(
        "{:<20} {}",
        "Validation:".dimmed(),
        if no_validate {
            "skip".yellow()
        } else {
            "enabled".green()
        }
    );
    let mode_label = match runtime {
        SwarmRuntime::Tmux => runtime.display_label().cyan(),
        SwarmRuntime::Extensions => runtime.display_label().green(),
        SwarmRuntime::Server => runtime.display_label().magenta(),
        SwarmRuntime::Headless => runtime.display_label().green(),
        SwarmRuntime::Beads => runtime.display_label().yellow(),
    };
    println!("{:<20} {}", "Mode:".dimmed(), mode_label);
    println!("{:<20} {}", "Harness:".dimmed(), harness.name().cyan());
    println!(
        "{:<20} {}",
        "Review:".dimmed(),
        if review_all {
            "all tasks".green()
        } else if review {
            "sample (3 per wave)".green()
        } else {
            "disabled".yellow()
        }
    );
    println!(
        "{:<20} {}",
        "Repair:".dimmed(),
        if no_repair {
            "disabled".yellow()
        } else {
            format!("up to {} attempts", max_repair_attempts).green()
        }
    );

    if !bp_config.commands.is_empty() && !no_validate {
        println!(
            "{:<20} {}",
            "Backpressure:".dimmed(),
            bp_config.commands.join(", ").dimmed()
        );
    }
    println!();

    if dry_run {
        return run_dry_run(project_root, &phase_tag, round_size, all_tags);
    }

    // Install hooks if needed
    if !hooks::hooks_installed(&working_dir) {
        println!("{}", "Installing Claude Code hooks...".dimmed());
        if let Err(e) = hooks::install_hooks(&working_dir) {
            println!(
                "  {} Hook installation: {}",
                "!".yellow(),
                e.to_string().dimmed()
            );
        } else {
            println!("  {} Hooks installed", "".green());
        }
    }

    // Initialize swarm session
    let terminal_mode = runtime.terminal_label();
    let mut swarm_session = SwarmSession::new(
        &session_name,
        &phase_tag,
        terminal_mode,
        &working_dir.to_string_lossy(),
        round_size,
    );

    // EventWriter will be created later in the function

    // Compute stale timeout duration
    let stale_timeout = stale_timeout_minutes.map(|m| Duration::from_secs(m * 60));

    // Create EventWriter for SQLite event logging (Phase 1b)
    // Include ZMQ publisher if not disabled
    let event_writer =
        events::EventWriter::new_with_zmq(&working_dir, &session_name, !no_publish_events).ok();

    // Create status tracking for control commands
    let status_state = Arc::new(std::sync::Mutex::new(
        crate::commands::swarm::publisher::SwarmStatus {
            state: "running".to_string(),
            current_wave: 0,
            total_waves: 0,
            tasks_completed: 0,
            tasks_total: 0,
        },
    ));

    // Start heartbeat background task for connection liveness detection
    let heartbeat_handle = if event_writer.is_some() {
        let working_dir = working_dir.clone();
        let session_name = session_name.clone();
        let stop_flag = Arc::new(AtomicBool::new(false));
        let stop_flag_clone = Arc::clone(&stop_flag);

        let handle = thread::spawn(move || {
            let writer = match events::EventWriter::new(&working_dir, &session_name) {
                Ok(w) => w,
                Err(e) => {
                    eprintln!("Failed to create heartbeat EventWriter: {}", e);
                    return;
                }
            };

            while !stop_flag_clone.load(Ordering::Relaxed) {
                if let Err(e) = writer.log_heartbeat() {
                    eprintln!("Heartbeat logging error: {}", e);
                }
                thread::sleep(Duration::from_secs(5));
            }
        });

        Some((handle, stop_flag))
    } else {
        None
    };

    // Detect orphan in-progress tasks (tasks with no running tmux window)
    // Only applicable in tmux mode
    let all_phases = storage.load_tasks()?;
    if runtime.is_tmux() {
        let orphans = find_orphan_tasks(&all_phases, &phase_tag, all_tags, &session_name);

        if !orphans.is_empty() {
            println!();
            println!(
                "{}",
                "Detected orphan in-progress tasks (no tmux window):".yellow()
            );
            for (task_id, tag) in &orphans {
                println!(
                    "  {} {} (tag: {})",
                    "*".yellow(),
                    task_id.cyan(),
                    tag.dimmed()
                );
            }
            println!();

            // Prompt user for action
            let choices = vec![
                "Reset to pending and re-run",
                "Kill existing windows (if any) and restart",
                "Skip and continue (leave as in-progress)",
                "Abort",
            ];

            let selection = dialoguer::Select::new()
                .with_prompt("How should orphan tasks be handled?")
                .items(&choices)
                .default(0)
                .interact()?;

            match selection {
                0 => {
                    // Reset to pending
                    for (task_id, tag) in &orphans {
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Pending);
                                storage.update_group(tag, &phase)?;
                                println!("  {} {} -> pending", "v".green(), task_id);
                            }
                        }
                    }
                }
                1 => {
                    // Kill and restart - first try to kill any matching windows
                    for (task_id, _) in &orphans {
                        let window_name = format!("task-{}", task_id);
                        let _ = terminal::kill_tmux_window(&session_name, &window_name);
                    }
                    // Reset to pending so they'll be picked up
                    for (task_id, tag) in &orphans {
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Pending);
                                storage.update_group(tag, &phase)?;
                                println!(
                                    "  {} {} -> pending (will re-spawn)",
                                    "v".green(),
                                    task_id
                                );
                            }
                        }
                    }
                }
                2 => {
                    // Skip - do nothing, leave as in-progress
                    println!("{}", "Leaving orphan tasks as in-progress.".dimmed());
                }
                3 => {
                    // Abort
                    anyhow::bail!("Aborted by user");
                }
                _ => {}
            }
            println!();
        }
    }

    // === BEADS MODE: Continuous execution ===
    // If beads mode is selected, run the continuous polling loop instead of waves
    if runtime.is_beads() {
        let beads_config = beads::BeadsConfig {
            max_concurrent: round_size, // Reuse round_size as max concurrent
            poll_interval: Duration::from_secs(3),
        };

        // Check tmux availability for beads mode (uses tmux by default)
        let result = beads::run_beads_loop(
            &storage,
            &phase_tag,
            all_tags,
            &working_dir,
            &session_name,
            harness,
            &beads_config,
            &mut swarm_session,
        )?;

        // Save session state
        session::save_session(project_root.as_ref(), &swarm_session)?;

        // Final summary
        println!();
        println!("{}", "Beads Session Summary".blue().bold());
        println!("{}", "".repeat(40).blue());
        println!(
            "  Tasks completed: {}",
            result.tasks_completed.to_string().green()
        );
        println!(
            "  Tasks failed:    {}",
            if result.tasks_failed > 0 {
                result.tasks_failed.to_string().red()
            } else {
                "0".to_string().green()
            }
        );
        println!(
            "  Duration:        {}",
            format!("{:.1}s", result.total_duration.as_secs_f64()).cyan()
        );

        // Stop heartbeat background task
        if let Some((handle, stop_flag)) = heartbeat_handle {
            stop_flag.store(true, Ordering::Relaxed);
            let _ = handle.join();
        }

        return Ok(());
    }

    // === WAVE MODE: Batch execution ===
    // Main loop: execute waves until all tasks done
    let mut wave_number = 1;
    loop {
        // Check pause/stop flags from control commands
        if let Some(ref pause_flag) = pause_flag {
            while pause_flag.load(Ordering::SeqCst) {
                // Handle any pending control requests while paused
                #[cfg(feature = "zmq")]
                if let Some(ref writer) = &event_writer {
                    if let Some(zmq_publisher) = writer.zmq_publisher() {
                        let _ = zmq_publisher.handle_control_request(
                            pause_flag,
                            stop_flag
                                .as_ref()
                                .unwrap_or(&Arc::new(AtomicBool::new(false))),
                            &|| status_state.lock().unwrap().clone(),
                        );
                    }
                }

                std::thread::sleep(Duration::from_millis(100));
                if let Some(ref stop_flag) = stop_flag {
                    if stop_flag.load(Ordering::SeqCst) {
                        println!();
                        println!("{}", "Swarm stopped by control command".yellow());
                        break;
                    }
                }
            }
        }

        if let Some(ref stop_flag) = stop_flag {
            if stop_flag.load(Ordering::SeqCst) {
                println!();
                println!("{}", "Swarm stopped by control command".yellow());

                // Update status
                {
                    let mut status = status_state.lock().unwrap();
                    status.state = "stopped".to_string();
                }

                break;
            }
        }

        // Load fresh task state (must reload each iteration to see completed tasks)
        let all_phases = storage.load_tasks()?;

        // Compute waves from current state
        let waves = compute_waves_from_tasks(&all_phases, &phase_tag, all_tags)?;

        // Update status for control commands
        {
            let mut status = status_state.lock().unwrap();
            status.current_wave = wave_number;
            status.total_waves = waves.len();
            status.tasks_total = waves.iter().map(|w| w.len()).sum();
            status.tasks_completed = all_phases
                .values()
                .flat_map(|phase| &phase.tasks)
                .filter(|task| matches!(task.status, TaskStatus::Done))
                .count();
            status.state = if pause_flag
                .as_ref()
                .is_some_and(|f| f.load(Ordering::SeqCst))
            {
                "paused".to_string()
            } else {
                "running".to_string()
            };
        }

        if waves.is_empty() {
            println!();
            println!("{}", "All tasks complete!".green().bold());

            // Update status
            {
                let mut status = status_state.lock().unwrap();
                status.state = "completed".to_string();
            }

            // Publish swarm completed event
            if let Some(ref writer) = &event_writer {
                let _ =
                    writer.publish_event(&publisher::ZmqEvent::SwarmCompleted { success: true });
                let _ = writer.log_swarm_completed(true);
            }

            break;
        }

        // Get first wave (tasks with no pending dependencies)
        let wave_tasks = &waves[0];

        if wave_tasks.is_empty() {
            println!();
            println!("{}", "No ready tasks in current wave.".yellow());

            let in_progress_count = count_in_progress_tasks(&all_phases, &phase_tag, all_tags);
            if in_progress_count > 0 {
                // Check for stale in-progress tasks whose tmux windows are gone (1d)
                if runtime.is_tmux() {
                    let orphans =
                        find_orphan_tasks(&all_phases, &phase_tag, all_tags, &session_name);
                    for (task_id, tag) in &orphans {
                        println!(
                            "  {} {} has no tmux window, resetting to pending",
                            "".yellow(),
                            task_id.cyan()
                        );
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Pending);
                                let _ = storage.update_group(tag, &phase);
                            }
                        }
                    }
                    if !orphans.is_empty() {
                        continue; // Re-check waves with reset tasks
                    }
                }

                println!(
                    "Waiting for {} in-progress task(s) to complete...",
                    in_progress_count.to_string().cyan()
                );
                thread::sleep(Duration::from_secs(10));
                continue;
            } else {
                println!("Check for blocked tasks: scud list --status blocked");
                break;
            }
        }

        println!();
        println!(
            "{} {} - {} task(s)",
            "Wave".blue().bold(),
            wave_number.to_string().cyan(),
            wave_tasks.len()
        );
        println!("{}", "-".repeat(40).blue());

        // Track wave state
        let mut wave_state = WaveState::new(wave_number);
        let wave_start = std::time::Instant::now();

        // Emit wave started event
        if let Some(ref writer) = event_writer {
            let _ = writer.log_wave_started(wave_number, wave_tasks.len());
        }

        // === PHASE 1: RESEARCH (optional, first wave only) ===
        if !no_research && wave_number == 1 {
            println!();
            println!("  {} Analyzing tasks...", "Research:".magenta());
            // TODO: Smart model could expand complex tasks here
            println!("    {} Task analysis complete", "".green());
        }

        // === PHASE 2: BUILD ===
        let num_rounds = wave_tasks.len().div_ceil(round_size);
        for (round_idx, round_tasks) in wave_tasks.chunks(round_size).enumerate() {
            println!();
            println!(
                "  {} {}/{} - {} task(s)",
                "Round".yellow(),
                round_idx + 1,
                num_rounds,
                round_tasks.len()
            );

            // Spawn agents for this round based on swarm mode
            // Note: Agents self-orient using scud CLI commands (scud list, scud show, etc.)
            let round_state = runtime
                .run_round(
                    &storage,
                    round_tasks,
                    &working_dir,
                    &session_name,
                    round_idx,
                    harness,
                    stale_timeout,
                    idle_timeout_minutes,
                    event_writer.as_ref(),
                )
                .await?;

            // Create/update spawn proxy for monitor visibility (tmux mode only)
            if runtime.is_tmux() {
                let _proxy_path = create_and_update_spawn_proxy(
                    &storage,
                    project_root.as_ref(),
                    &session_name,
                    &phase_tag,
                    &working_dir,
                    &swarm_session,
                    Some(&round_state),
                )?;
            }

            wave_state.rounds.push(round_state.clone());
            println!("    {} Round {} complete", "".green(), round_idx + 1);
        }

        // === PHASE 3: VALIDATE (optional) ===
        if !no_validate && !bp_config.commands.is_empty() {
            println!();
            println!("  {} Running backpressure checks...", "Validate:".magenta());

            let validation_result = backpressure::run_validation(&working_dir, &bp_config)?;

            if validation_result.all_passed {
                println!("    {} All checks passed", "".green());

                // Emit validation passed event
                if let Some(ref writer) = event_writer {
                    let _ = writer.log_validation_passed();
                }

                // Mark all tasks as done
                for (task_id, tag) in wave_state.task_tags() {
                    if let Ok(mut phase) = storage.load_group(&tag) {
                        if let Some(task) = phase.get_task_mut(&task_id) {
                            task.set_status(TaskStatus::Done);
                            let _ = storage.update_group(&tag, &phase);
                        }
                    }
                }
            } else {
                println!("    {} Some checks failed:", "!".yellow());
                for failure in &validation_result.failures {
                    println!("      - {}", failure.red());
                }

                // Emit validation failed event
                if let Some(ref writer) = event_writer {
                    let _ = writer.log_validation_failed(&validation_result.failures);
                }

                if no_repair {
                    // Old behavior: mark all tasks as failed
                    let task_tags = wave_state.task_tags();
                    for (task_id, tag) in &task_tags {
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Failed);
                                let _ = storage.update_group(tag, &phase);
                            }
                        }
                    }
                    println!(
                        "    {} Marked {} task(s) as failed",
                        "!".yellow(),
                        task_tags.len()
                    );
                } else {
                    // New behavior: run repair loop
                    let repaired = run_repair_loop(
                        &storage,
                        &working_dir,
                        &session_name,
                        &bp_config,
                        &wave_state,
                        &validation_result,
                        max_repair_attempts,
                    )?;

                    if !repaired {
                        println!("    {} Wave failed after repair attempts", "!".red());
                    }
                }
            }

            wave_state.validation = Some(validation_result);
        }

        // Generate wave summary (just what was done - not context accumulation)
        let summary = WaveSummary {
            wave_number,
            tasks_completed: wave_state.all_task_ids(),
            files_changed: collect_changed_files(&working_dir, wave_state.start_commit.as_deref())
                .unwrap_or_default(),
        };
        wave_state.summary = Some(summary.clone());

        // === PHASE 4: REVIEW (optional) ===
        if (review || review_all) && !dry_run {
            // Build task list for review
            let wave_tasks: Vec<(String, String)> = wave_state
                .task_tags()
                .iter()
                .filter_map(|(id, tag)| {
                    storage
                        .load_group(tag)
                        .ok()
                        .and_then(|phase| phase.get_task(id).map(|t| (id.clone(), t.title.clone())))
                })
                .collect();

            if !wave_tasks.is_empty() {
                let review_result = spawn_reviewer(
                    &working_dir,
                    &session_name,
                    &summary,
                    &wave_tasks,
                    review_all,
                )?;

                if !review_result.all_passed && !review_result.tasks_to_improve.is_empty() {
                    println!(
                        "    {} Reviewer found issues in: {}",
                        "!".yellow(),
                        review_result.tasks_to_improve.join(", ")
                    );

                    // Spawn improvement agents for flagged tasks
                    for task_id in &review_result.tasks_to_improve {
                        // Find task and spawn builder to improve
                        if let Some((task, _tag)) =
                            find_task_with_tag(&storage, task_id, &wave_state.task_tags())
                        {
                            let prompt = format!(
                                "Improve SCUD task {}: {}\n\nThe reviewer flagged this task for improvements. \
                                 Review the implementation and make it better. When done: scud set-status {} done",
                                task.id, task.title, task.id
                            );

                            // Use builder agent for improvements
                            if let Some(agent_def) = AgentDef::try_load("builder", &working_dir) {
                                let harness = agent_def.harness()?;
                                let model = agent_def.model();

                                let spawn_config = terminal::SpawnConfig {
                                    task_id: &format!("improve-{}", task_id),
                                    prompt: &prompt,
                                    working_dir: &working_dir,
                                    session_name: &session_name,
                                    harness,
                                    model,
                                    task_list_id: None,
                                };
                                terminal::spawn_tmux_agent(&spawn_config)?;

                                println!(
                                    "    {} Spawned improvement agent for {}",
                                    "".green(),
                                    task_id
                                );
                            }
                        }
                    }
                } else {
                    println!("    {} Review complete, all tasks approved", "".green());
                }
            }
        }

        // Emit wave completed event
        if let Some(ref writer) = event_writer {
            let _ = writer.log_wave_completed(wave_number, wave_start.elapsed().as_millis() as u64);
        }

        // Save session state
        swarm_session.waves.push(wave_state);
        session::save_session(project_root.as_ref(), &swarm_session)?;

        // Also save spawn-format session for TUI refresh
        {
            let spawn_session = swarm_session.to_spawn_session();
            monitor::save_session(project_root.as_ref(), &spawn_session)?;
        }

        wave_number += 1;
    }

    // Publish swarm completed event (successful completion)
    if let Some(ref writer) = &event_writer {
        let _ = writer.publish_event(&publisher::ZmqEvent::SwarmCompleted { success: true });
        let _ = writer.log_swarm_completed(true);
    }

    // Final summary
    // Final bridge update for spawn monitor/TUI compatibility
    create_and_update_spawn_proxy(
        &storage,
        project_root.as_ref(),
        &session_name,
        &phase_tag,
        &working_dir,
        &swarm_session,
        None, // Final update - include all rounds
    )?;

    println!();
    println!("{}", "Swarm Session Summary".blue().bold());
    println!("{}", "".repeat(40).blue());
    println!(
        "  Waves completed: {}",
        swarm_session.waves.len().to_string().green()
    );

    let total_tasks: usize = swarm_session
        .waves
        .iter()
        .flat_map(|w| &w.rounds)
        .map(|r| r.task_ids.len())
        .sum();
    println!("  Tasks executed: {}", total_tasks.to_string().green());

    println!("  {} Spawn proxy updated for monitor/TUI", "".green());

    // Auto-sync worktree results back to main
    if is_salvo_worktree {
        if let (Some(main_root), Some(tag_name)) = (&main_project_root, &tag) {
            if let Err(e) = crate::commands::salvo::sync_to_main(main_root, &working_dir, tag_name)
            {
                eprintln!("Warning: Failed to sync salvo back to main: {}", e);
                eprintln!("Run manually: scud salvo sync {}", tag_name);
            }
        }
    }

    // Stop heartbeat background task
    if let Some((handle, stop_flag)) = heartbeat_handle {
        stop_flag.store(true, Ordering::Relaxed);
        if let Err(e) = handle.join() {
            eprintln!("Heartbeat thread join error: {:?}", e);
        }
    }

    Ok(())
}

fn create_and_update_spawn_proxy(
    storage: &Storage,
    project_root: Option<&PathBuf>,
    session_name: &str,
    phase_tag: &str,
    working_dir: &Path,
    swarm_session: &SwarmSession,
    latest_round: Option<&RoundState>,
) -> Result<Option<PathBuf>> {
    let all_phases = storage.load_tasks()?;

    // Try to load existing proxy session, or create new one
    let mut spawn_session = match monitor::load_session(project_root, session_name) {
        Ok(existing) => existing,
        Err(_) => SpawnSession::new(
            session_name,
            phase_tag,
            "tmux",
            &working_dir.to_string_lossy(),
        ),
    };

    // Get tasks to add (either from latest round or all tasks)
    let tasks_to_add: Vec<String> = match latest_round {
        Some(round) => round.task_ids.clone(),
        None => swarm_session
            .waves
            .iter()
            .flat_map(|w| w.all_task_ids())
            .collect(),
    };

    // Add new agents (skip duplicates)
    let existing_task_ids: std::collections::HashSet<String> = spawn_session
        .agents
        .iter()
        .map(|a| a.task_id.clone())
        .collect();

    for task_id in &tasks_to_add {
        if !existing_task_ids.contains(task_id) {
            if let Some((title, tag)) = find_task_title_tag(&all_phases, task_id) {
                spawn_session.add_agent(task_id, &title, &tag);
            }
        }
    }

    let session_file = monitor::save_session(project_root, &spawn_session)?;
    Ok(Some(session_file))
}

fn find_task_title_tag(
    phases: &HashMap<String, crate::models::phase::Phase>,
    task_id: &str,
) -> Option<(String, String)> {
    for (tag, phase) in phases {
        if let Some(task) = phase.get_task(task_id) {
            return Some((task.title.clone(), tag.clone()));
        }
    }
    None
}

/// Task info for wave computation
#[derive(Clone)]
struct TaskInfo<'a> {
    task: &'a Task,
    tag: String,
}

/// Compute execution waves from current task state
fn compute_waves_from_tasks<'a>(
    all_phases: &'a HashMap<String, Phase>,
    phase_tag: &str,
    all_tags: bool,
) -> Result<Vec<Vec<TaskInfo<'a>>>> {
    use std::collections::HashSet;

    let mut actionable: Vec<TaskInfo<'a>> = Vec::new();

    let phase_tags: Vec<&String> = if all_tags {
        all_phases.keys().collect()
    } else {
        all_phases
            .keys()
            .filter(|t| t.as_str() == phase_tag)
            .collect()
    };

    for tag in phase_tags {
        if let Some(phase) = all_phases.get(tag) {
            for task in &phase.tasks {
                if is_actionable_pending_task(task, phase) {
                    actionable.push(TaskInfo {
                        task,
                        tag: tag.clone(),
                    });
                }
            }
        }
    }

    if actionable.is_empty() {
        return Ok(Vec::new());
    }

    // Kahn's algorithm for wave computation
    let task_ids: HashSet<String> = actionable.iter().map(|t| t.task.id.clone()).collect();
    let mut in_degree: HashMap<String, usize> = HashMap::new();
    let mut dependents: HashMap<String, Vec<String>> = HashMap::new();

    // Collect in-progress task IDs for blocking check
    let in_progress_ids: HashSet<String> = {
        let tags: Vec<&str> = if all_tags {
            all_phases.keys().map(|s| s.as_str()).collect()
        } else {
            vec![phase_tag]
        };

        tags.iter()
            .filter_map(|tag| all_phases.get(*tag))
            .flat_map(|phase| &phase.tasks)
            .filter(|t| t.status == TaskStatus::InProgress)
            .map(|t| t.id.clone())
            .collect()
    };

    for info in &actionable {
        in_degree.entry(info.task.id.clone()).or_insert(0);
        for dep in &info.task.dependencies {
            if task_ids.contains(dep) {
                // Dependency is pending - will be in a wave
                *in_degree.entry(info.task.id.clone()).or_insert(0) += 1;
                dependents
                    .entry(dep.clone())
                    .or_default()
                    .push(info.task.id.clone());
            } else if in_progress_ids.contains(dep) {
                // Dependency is in-progress - block this task
                // Set very high in-degree so it never becomes ready
                *in_degree.entry(info.task.id.clone()).or_insert(0) += 1000;
            }
            // If dep is Done/Failed/etc, it's satisfied - do nothing
        }
    }

    let mut waves: Vec<Vec<TaskInfo<'a>>> = Vec::new();
    let mut remaining = in_degree.clone();

    while !remaining.is_empty() {
        let ready: Vec<String> = remaining
            .iter()
            .filter(|(_, &deg)| deg == 0)
            .map(|(id, _)| id.clone())
            .collect();

        if ready.is_empty() {
            break; // Circular dependency
        }

        let wave: Vec<TaskInfo<'a>> = actionable
            .iter()
            .filter(|t| ready.contains(&t.task.id))
            .cloned()
            .collect();

        for task_id in &ready {
            remaining.remove(task_id);
            if let Some(deps) = dependents.get(task_id) {
                for dep_id in deps {
                    if let Some(deg) = remaining.get_mut(dep_id) {
                        *deg = deg.saturating_sub(1);
                    }
                }
            }
        }

        waves.push(wave);
    }

    Ok(waves)
}

/// Check if a tmux window exists for a task
fn tmux_window_exists_for_task(session_name: &str, task_id: &str) -> bool {
    let window_name = format!("task-{}", task_id);
    terminal::tmux_window_exists(session_name, &window_name)
}

/// Find in-progress tasks that have no running tmux window (orphans)
fn find_orphan_tasks(
    all_phases: &HashMap<String, Phase>,
    phase_tag: &str,
    all_tags: bool,
    session_name: &str,
) -> Vec<(String, String)> {
    // (task_id, tag) pairs
    let tags: Vec<&str> = if all_tags {
        all_phases.keys().map(|s| s.as_str()).collect()
    } else {
        vec![phase_tag]
    };

    let mut orphans = Vec::new();

    for tag in tags {
        if let Some(phase) = all_phases.get(tag) {
            for task in &phase.tasks {
                if task.status == TaskStatus::InProgress
                    && !tmux_window_exists_for_task(session_name, &task.id)
                {
                    orphans.push((task.id.clone(), tag.to_string()));
                }
            }
        }
    }

    orphans
}

/// Mark a batch of tasks as in-progress in storage.
fn mark_tasks_in_progress(storage: &Storage, tasks: &[TaskInfo]) {
    for info in tasks {
        if let Ok(mut phase) = storage.load_group(&info.tag) {
            if let Some(task) = phase.get_task_mut(&info.task.id) {
                task.set_status(TaskStatus::InProgress);
                let _ = storage.update_group(&info.tag, &phase);
            }
        }
    }
}

fn execute_round(
    storage: &Storage,
    tasks: &[TaskInfo],
    working_dir: &std::path::Path,
    session_name: &str,
    round_idx: usize,
    default_harness: Harness,
    event_writer: Option<&events::EventWriter>,
) -> Result<RoundState> {
    let mut round_state = RoundState::new(round_idx);

    for info in tasks.iter() {
        // Resolve agent config (harness, model, prompt) from task's agent_type
        let config =
            agent::resolve_agent_config(info.task, &info.tag, default_harness, None, working_dir);

        // Warn if agent type was specified but definition not found
        if info.task.agent_type.is_some() && !config.from_agent_def {
            println!(
                "    {} Agent '{}' not found, using defaults",
                "!".yellow(),
                info.task.agent_type.as_deref().unwrap_or("unknown")
            );
        }

        let spawn_config = terminal::SpawnConfig {
            task_id: &info.task.id,
            prompt: &config.prompt,
            working_dir,
            session_name,
            harness: config.harness,
            model: config.model.as_deref(),
            task_list_id: None,
        };
        match terminal::spawn_tmux_agent(&spawn_config) {
            Ok(window_index) => {
                println!(
                    "    {} Spawned: {} | {} [{}] {}:{}",
                    "".green(),
                    info.task.id.cyan(),
                    info.task.title.dimmed(),
                    config.display_info().dimmed(),
                    session_name.dimmed(),
                    window_index.dimmed()
                );
                round_state.task_ids.push(info.task.id.clone());
                round_state.tags.push(info.tag.clone());

                // Emit spawn event
                if let Some(writer) = event_writer {
                    let _ = writer.log_spawned(&info.task.id);
                }

                if let Ok(mut phase) = storage.load_group(&info.tag) {
                    if let Some(task) = phase.get_task_mut(&info.task.id) {
                        task.set_status(TaskStatus::InProgress);
                        let _ = storage.update_group(&info.tag, &phase);
                    }
                }
            }
            Err(e) => {
                println!("    {} Failed: {} - {}", "".red(), info.task.id.red(), e);
                round_state.failures.push(info.task.id.clone());
            }
        }

        thread::sleep(Duration::from_millis(500));
    }

    Ok(round_state)
}

/// Execute a round using extension-based subprocesses (no tmux)
async fn execute_round_extensions<'a>(
    storage: &Storage,
    tasks: &[TaskInfo<'a>],
    working_dir: &std::path::Path,
    round_idx: usize,
    default_harness: Harness,
) -> Result<RoundState> {
    // Convert TaskInfo to WaveAgent format
    let wave_agents: Vec<session::WaveAgent> = tasks
        .iter()
        .map(|info| session::WaveAgent::new(info.task.clone(), &info.tag))
        .collect();

    mark_tasks_in_progress(storage, tasks);

    let result =
        session::execute_wave_async(&wave_agents, working_dir, round_idx, default_harness).await?;

    // Print results
    for agent_result in &result.agent_results {
        if agent_result.success {
            println!(
                "    {} Completed: {} ({}ms)",
                "".green(),
                agent_result.task_id.cyan(),
                agent_result.duration_ms
            );
        } else {
            println!(
                "    {} Failed: {} (exit code: {:?})",
                "".red(),
                agent_result.task_id.red(),
                agent_result.exit_code
            );
        }
    }

    // Update task statuses based on results
    for agent_result in &result.agent_results {
        // Find the task's tag
        if let Some(info) = tasks.iter().find(|t| t.task.id == agent_result.task_id) {
            if let Ok(mut phase) = storage.load_group(&info.tag) {
                if let Some(task) = phase.get_task_mut(&agent_result.task_id) {
                    // The agent itself should update the status via scud set-status
                    // But if it failed to start, mark it as failed
                    if !agent_result.success && agent_result.exit_code.is_none() {
                        task.set_status(TaskStatus::Failed);
                        let _ = storage.update_group(&info.tag, &phase);
                    }
                }
            }
        }
    }

    Ok(result.round_state)
}

/// Execute a round using OpenCode Server mode
async fn execute_round_server<'a>(
    storage: &Storage,
    tasks: &[TaskInfo<'a>],
    working_dir: &std::path::Path,
    round_idx: usize,
) -> Result<RoundState> {
    use crate::opencode::AgentOrchestrator;
    use tokio::sync::mpsc;

    // Mark tasks as in-progress before spawning
    for info in tasks {
        if let Ok(mut phase) = storage.load_group(&info.tag) {
            if let Some(task) = phase.get_task_mut(&info.task.id) {
                task.set_status(TaskStatus::InProgress);
                let _ = storage.update_group(&info.tag, &phase);
            }
        }
    }
    // Create event channel
    let (event_tx, _event_rx) = mpsc::channel(1000);

    // Create orchestrator
    let mut orchestrator = AgentOrchestrator::new(event_tx.clone()).await?;

    // Resolve model from config
    let config_path = working_dir.join(".scud").join("config.toml");
    let config = crate::config::Config::load(&config_path).unwrap_or_default();
    let model_str = config.swarm_model().to_string();
    let provider_str = config.swarm.direct_api_provider.clone();

    // Spawn all agents
    for info in tasks {
        let prompt = generate_server_prompt(info.task, &info.tag, working_dir);

        let model = Some((provider_str.as_str(), model_str.as_str()));

        match orchestrator
            .spawn_agent(info.task, &info.tag, &prompt, model)
            .await
        {
            Ok(_) => {
                println!(
                    "    {} Spawned: {} | {} [server/{}/{}]",
                    "".green(),
                    info.task.id.cyan(),
                    info.task.title.dimmed(),
                    provider_str,
                    model_str,
                );
            }
            Err(e) => {
                println!("    {} Failed to spawn {}: {}", "".red(), info.task.id, e);
            }
        }
    }

    // Drop our sender so we can detect when orchestrator is done
    drop(event_tx);

    // Collect results
    let results = orchestrator.wait_all().await;

    // Cleanup
    orchestrator.cleanup().await;

    let result = results;

    // Build round state from results
    let mut round_state = RoundState::new(round_idx);

    for agent_result in &result {
        if agent_result.success {
            println!(
                "    {} Completed: {} ({}ms)",
                "".green(),
                agent_result.task_id.cyan(),
                agent_result.duration_ms
            );
            round_state.task_ids.push(agent_result.task_id.clone());
        } else {
            println!(
                "    {} Failed: {} (exit code: {:?})",
                "".red(),
                agent_result.task_id.red(),
                agent_result.exit_code
            );
            round_state.failures.push(agent_result.task_id.clone());
        }
    }

    // Add tags for successful tasks
    for task_id in &round_state.task_ids {
        if let Some(info) = tasks.iter().find(|t| t.task.id == *task_id) {
            round_state.tags.push(info.tag.clone());
        }
    }

    // Update task statuses based on results
    for agent_result in &result {
        if let Some(info) = tasks.iter().find(|t| t.task.id == agent_result.task_id) {
            if let Ok(mut phase) = storage.load_group(&info.tag) {
                if let Some(task) = phase.get_task_mut(&agent_result.task_id) {
                    // If failed without exit code, mark as failed
                    if !agent_result.success && agent_result.exit_code.is_none() {
                        task.set_status(TaskStatus::Failed);
                        let _ = storage.update_group(&info.tag, &phase);
                    }
                }
            }
        }
    }

    Ok(round_state)
}

/// Execute a round using spawn's headless streaming infrastructure (no tmux)
///
/// Uses the headless runner from `spawn::headless` to capture streaming JSON
/// events from Claude Code or OpenCode agents without requiring tmux.
async fn execute_round_headless(
    storage: &Storage,
    tasks: &[TaskInfo<'_>],
    working_dir: &std::path::Path,
    round_idx: usize,
    default_harness: Harness,
    event_writer: Option<&events::EventWriter>,
) -> Result<RoundState> {
    use crate::commands::attach::{save_session_metadata, SessionMetadata};

    let mut round_state = RoundState::new(round_idx);

    // Create stream store for this round
    let store = StreamStore::new();

    // Mark tasks as in-progress and spawn agents
    for info in tasks {
        // Resolve agent config (harness, model, prompt) from task's agent_type
        let config =
            agent::resolve_agent_config(info.task, &info.tag, default_harness, None, working_dir);

        // Create session in store
        store.create_session(&info.task.id, &info.tag);

        // Create a runner for this task's specific harness
        let runner = match headless::create_runner(config.harness) {
            Ok(r) => r,
            Err(e) => {
                println!(
                    "    {} Failed to create runner for {}: {}",
                    "".red(),
                    info.task.id.red(),
                    e
                );
                round_state.failures.push(info.task.id.clone());
                continue;
            }
        };

        // Spawn headless session
        let spawn_result = runner
            .start(
                &info.task.id,
                &config.prompt,
                working_dir,
                config.model.as_deref(),
            )
            .await;

        match spawn_result {
            Ok(mut session_handle) => {
                // Set PID in store
                if let Some(pid) = session_handle.pid() {
                    store.set_pid(&info.task.id, pid);
                }

                println!(
                    "    {} Spawned (headless): {} | {} [{}]",
                    "".green(),
                    info.task.id.cyan(),
                    info.task.title.dimmed(),
                    config.display_info().dimmed(),
                );

                round_state.task_ids.push(info.task.id.clone());
                round_state.tags.push(info.tag.clone());

                // Emit spawn event
                if let Some(writer) = event_writer {
                    let _ = writer.log_spawned(&info.task.id);
                }

                // Mark task as in-progress
                if let Ok(mut phase) = storage.load_group(&info.tag) {
                    if let Some(task) = phase.get_task_mut(&info.task.id) {
                        task.set_status(TaskStatus::InProgress);
                        let _ = storage.update_group(&info.tag, &phase);
                    }
                }

                // Spawn background task to collect events
                let store_clone = store.clone();
                let task_id = info.task.id.clone();
                let tag = info.tag.clone();
                let working_dir_clone = working_dir.to_path_buf();
                let harness_name = config.harness.name().to_string();

                tokio::spawn(async move {
                    let mut saw_terminal_event = false;
                    while let Some(event) = session_handle.events.recv().await {
                        if matches!(
                            event.kind,
                            headless::StreamEventKind::Complete { .. }
                                | headless::StreamEventKind::Error { .. }
                        ) {
                            saw_terminal_event = true;
                        }

                        // Check for session ID assignment
                        if let headless::StreamEventKind::SessionAssigned { ref session_id } =
                            event.kind
                        {
                            store_clone.set_session_id(&task_id, session_id);

                            // Save session metadata for `scud attach` continuation
                            let metadata =
                                SessionMetadata::new(&task_id, session_id, &tag, &harness_name);
                            let _ = save_session_metadata(&working_dir_clone, &metadata);
                        }

                        store_clone.push_event(&task_id, event);
                    }

                    // Wait for process to complete. If the harness exited without a terminal
                    // stream event, synthesize one so rounds cannot get stuck indefinitely.
                    let wait_ok = session_handle.wait().await.unwrap_or(false);
                    if !saw_terminal_event {
                        if wait_ok {
                            store_clone.push_event(&task_id, headless::StreamEvent::complete(true));
                        } else {
                            store_clone.push_event(
                                &task_id,
                                headless::StreamEvent::error(
                                    "Agent process exited without completion event".to_string(),
                                ),
                            );
                        }
                    } else if !wait_ok {
                        // Even if we saw a "complete" stream event, trust the process exit code.
                        store_clone.push_event(
                            &task_id,
                            headless::StreamEvent::error(
                                "Agent process exited with non-zero status".to_string(),
                            ),
                        );
                    }
                });
            }
            Err(e) => {
                println!(
                    "    {} Failed (headless): {} - {}",
                    "".red(),
                    info.task.id.red(),
                    e
                );
                round_state.failures.push(info.task.id.clone());

                // Record error in store
                store.push_event(&info.task.id, headless::StreamEvent::error(e.to_string()));
            }
        }

        // Small delay between spawns to avoid overwhelming the system
        tokio::time::sleep(Duration::from_millis(200)).await;
    }

    // Wait for all tasks to complete by polling the store
    let max_wait = Duration::from_secs(3600); // 1 hour max
    let start = std::time::Instant::now();
    let total_tasks = round_state.task_ids.len();
    let mut poll_count = 0u32;
    // Track how many display lines we printed last time (for ANSI overwrite)
    let mut prev_display_lines = 0usize;

    loop {
        // Fast initial polling (2s for first 5 polls), then slow (5s)
        let poll_interval = if poll_count < 5 {
            Duration::from_secs(2)
        } else {
            Duration::from_secs(5)
        };
        poll_count += 1;

        // Small initial delay to let agents start producing output
        if poll_count == 1 {
            tokio::time::sleep(Duration::from_secs(2)).await;
        }

        let active_tasks = store.active_tasks();
        let active_count = active_tasks.len();
        if active_count == 0 {
            break;
        }

        if start.elapsed() > max_wait {
            println!(
                "    {} Timeout waiting for {} tasks",
                "!".yellow(),
                active_count
            );
            break;
        }

        // Move cursor up to overwrite previous display (if any)
        if prev_display_lines > 0 {
            // Move up N lines and clear each one
            for _ in 0..prev_display_lines {
                print!("\x1b[A\x1b[2K");
            }
        }

        // Build display lines, then print them all
        let mut display = Vec::new();
        let completed = total_tasks - active_count;
        let elapsed = start.elapsed().as_secs();

        display.push(format!(
            "\n    ─── {} {}/{} done ({} active) · {}s ───",
            "".blue(),
            completed,
            total_tasks,
            active_count,
            format_duration(elapsed),
        ));

        // Show ALL tasks in this round with their current status
        for task_id in &round_state.task_ids {
            let status = store.get_status(task_id);
            let elapsed_task = store.get_elapsed_secs(task_id).unwrap_or(0);
            let stats = store
                .session_stats(task_id)
                .map(|(events, _)| format!("{}ev", events))
                .unwrap_or_default();

            let (icon, status_str) = match &status {
                Some(SessionStatus::Completed) => ("".green(), "done".green()),
                Some(SessionStatus::Failed) => ("".red(), "fail".red()),
                Some(SessionStatus::Running) => ("".blue(), "run".blue()),
                Some(SessionStatus::Starting) => ("".yellow(), "init".yellow()),
                None => ("?".dimmed(), "?".dimmed()),
            };

            // For active tasks, show last tool activity; for done tasks, just show stats
            let detail = match &status {
                Some(SessionStatus::Running) | Some(SessionStatus::Starting) => {
                    // Prefer tool line, fall back to last output line
                    let tool_line = store.get_last_tool_line(task_id);
                    let activity = tool_line
                        .or_else(|| store.get_output(task_id, 1).into_iter().next())
                        .unwrap_or_default();
                    let trimmed = if activity.len() > 60 {
                        format!("{}", &activity[..59])
                    } else {
                        activity
                    };
                    if trimmed.is_empty() {
                        format!("{}s {}", format_duration(elapsed_task), stats)
                    } else {
                        format!("{}s {} {}", format_duration(elapsed_task), stats, trimmed)
                    }
                }
                _ => {
                    format!("{}s {}", format_duration(elapsed_task), stats)
                }
            };

            display.push(format!(
                "      {} {:>5} [{}] {}",
                icon,
                task_id.cyan(),
                status_str,
                detail.dimmed(),
            ));
        }

        // Print and track line count for next overwrite
        prev_display_lines = display.len();
        for line in &display {
            println!("{}", line);
        }

        tokio::time::sleep(poll_interval).await;
    }

    // Final summary (printed once, not overwritten)
    let elapsed = start.elapsed().as_secs();
    let successes = round_state
        .task_ids
        .iter()
        .filter(|id| matches!(store.get_status(id), Some(SessionStatus::Completed)))
        .count();
    let failures = round_state
        .task_ids
        .iter()
        .filter(|id| matches!(store.get_status(id), Some(SessionStatus::Failed)))
        .count();
    println!(
        "\n    ─── Round complete: {} ok, {} failed, {} total in {}s ───",
        format!("{}", successes).green(),
        format!("{}", failures).red(),
        total_tasks,
        format_duration(elapsed),
    );
    // Show details for failed tasks only
    for task_id in &round_state.task_ids {
        if matches!(store.get_status(task_id), Some(SessionStatus::Failed)) {
            println!("      {} {} — last output:", "".red(), task_id.red());
            let output = store.get_all_output(task_id);
            for line in output.iter().rev().take(5).rev() {
                let trimmed = if line.len() > 80 {
                    format!("{}", &line[..79])
                } else {
                    line.clone()
                };
                if !trimmed.is_empty() {
                    println!("        {}", trimmed.dimmed());
                }
            }
        }
    }

    // Emit completion events
    for task_id in &round_state.task_ids {
        if let Some(writer) = event_writer {
            let success = matches!(store.get_status(task_id), Some(SessionStatus::Completed));
            let _ = writer.log_completed(task_id, success, start.elapsed().as_millis() as u64);
        }
    }

    Ok(round_state)
}

/// Format seconds into compact human-readable duration (e.g., "45s", "2m30s", "1h05m")
fn format_duration(secs: u64) -> String {
    if secs < 60 {
        format!("{}", secs)
    } else if secs < 3600 {
        format!("{}m{:02}", secs / 60, secs % 60)
    } else {
        format!("{}h{:02}m", secs / 3600, (secs % 3600) / 60)
    }
}

/// Generate prompt for server mode (similar to extensions but optimized for OpenCode)
fn generate_server_prompt(task: &Task, tag: &str, working_dir: &std::path::Path) -> String {
    let details = task
        .details
        .as_ref()
        .map(|d| format!("\n\n## Details\n\n{}", d))
        .unwrap_or_default();

    let test_strategy = task
        .test_strategy
        .as_ref()
        .map(|t| format!("\n\n## Test Strategy\n\n{}", t))
        .unwrap_or_default();

    format!(
        r#"You are working on task [{id}] in phase "{tag}".

## Task: {title}

{description}{details}{test_strategy}

## Instructions

1. Implement the task requirements
2. Test your changes
3. When complete, run: `scud set-status {id} done --tag {tag}`

Working directory: {working_dir}
"#,
        id = task.id,
        tag = tag,
        title = task.title,
        description = task.description,
        details = details,
        test_strategy = test_strategy,
        working_dir = working_dir.display(),
    )
}

fn wait_for_round_completion(
    storage: &Storage,
    tasks: &[TaskInfo],
    session_name: &str,
    stale_timeout: Option<Duration>,
    idle_timeout_minutes: u64,
    event_writer: Option<&events::EventWriter>,
) -> Result<()> {
    use std::collections::HashSet;
    use std::io::Write;
    use std::time::Instant;

    let task_ids: Vec<String> = tasks.iter().map(|t| t.task.id.clone()).collect();
    let task_tags: HashMap<String, String> = tasks
        .iter()
        .map(|t| (t.task.id.clone(), t.tag.clone()))
        .collect();

    let round_start = Instant::now();
    let mut completed_tasks: HashSet<String> = HashSet::new();
    let spinner_chars = ['', '', '', '', '', '', '', '', '', ''];
    let mut spin_idx: usize = 0;
    let mut last_orphan_check = Instant::now();

    // Track per-task content hashes for heartbeat (1c)
    let mut last_content_hashes: HashMap<String, u64> = HashMap::new();
    let mut last_activity: HashMap<String, Instant> = HashMap::new();
    for task_id in &task_ids {
        last_activity.insert(task_id.clone(), Instant::now());
    }

    loop {
        let mut still_running: Vec<String> = Vec::new();

        for task_id in &task_ids {
            if completed_tasks.contains(task_id) {
                continue;
            }

            if let Some(tag) = task_tags.get(task_id) {
                if let Ok(phase) = storage.load_group(tag) {
                    if let Some(task) = phase.get_task(task_id) {
                        if task.status == TaskStatus::InProgress
                            || task.status == TaskStatus::Pending
                        {
                            still_running.push(task_id.clone());
                        } else {
                            // Task just completed
                            completed_tasks.insert(task_id.clone());
                            let elapsed = round_start.elapsed().as_secs();
                            let status_icon = if task.status == TaskStatus::Done {
                                "".green()
                            } else {
                                "".red()
                            };
                            // Clear the status line, then print completion
                            print!("\r{}\r", " ".repeat(80));
                            println!(
                                "    {} {} completed ({}s)",
                                status_icon,
                                task_id.cyan(),
                                elapsed
                            );
                            // Emit completion event (1b)
                            if let Some(writer) = event_writer {
                                let success = task.status == TaskStatus::Done;
                                let _ = writer.log_completed(
                                    task_id,
                                    success,
                                    round_start.elapsed().as_millis() as u64,
                                );
                            }
                        }
                    }
                }
            }
        }

        if still_running.is_empty() {
            // Clear status line
            print!("\r{}\r", " ".repeat(80));
            let _ = std::io::stdout().flush();
            break;
        }

        // Periodic orphan detection (1e): every 30s, check if tmux windows still exist
        if last_orphan_check.elapsed() >= Duration::from_secs(30) {
            last_orphan_check = Instant::now();
            for task_id in &still_running {
                if !tmux_window_exists_for_task(session_name, task_id) {
                    // Agent died - tmux window gone but task still InProgress
                    print!("\r{}\r", " ".repeat(80));
                    println!(
                        "    {} {} agent died (tmux window gone), marking failed",
                        "".yellow(),
                        task_id.cyan()
                    );
                    // Mark as Failed
                    if let Some(tag) = task_tags.get(task_id) {
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Failed);
                                let _ = storage.update_group(tag, &phase);
                            }
                        }
                    }
                    completed_tasks.insert(task_id.clone());
                    // Emit failed event
                    if let Some(writer) = event_writer {
                        let event = events::AgentEvent::new(
                            writer.session_id(),
                            task_id,
                            events::EventKind::Failed {
                                reason: "agent window disappeared".to_string(),
                            },
                        );
                        let _ = writer.write(&event);
                    }
                }
            }
        }

        // Stale task timeout (1d): check if any task exceeded the threshold
        if let Some(timeout) = stale_timeout {
            if round_start.elapsed() >= timeout {
                for task_id in &still_running {
                    // Cross-reference with tmux window existence
                    if !tmux_window_exists_for_task(session_name, task_id) {
                        print!("\r{}\r", " ".repeat(80));
                        println!(
                            "    {} {} stale (timeout + no tmux window), resetting to pending",
                            "".yellow(),
                            task_id.cyan()
                        );
                        if let Some(tag) = task_tags.get(task_id) {
                            if let Ok(mut phase) = storage.load_group(tag) {
                                if let Some(task) = phase.get_task_mut(task_id) {
                                    task.set_status(TaskStatus::Pending);
                                    let _ = storage.update_group(tag, &phase);
                                }
                            }
                        }
                        completed_tasks.insert(task_id.clone());
                    }
                }
            }
        }

        // Heartbeat check (1c): poll tmux panes for activity
        for task_id in &still_running {
            if completed_tasks.contains(task_id) {
                continue;
            }
            let window_name = format!("task-{}", task_id);
            let window_target = format!("{}:{}", session_name, window_name);
            if let Ok(output) = std::process::Command::new("tmux")
                .args(["capture-pane", "-t", &window_target, "-p", "-S", "-20"])
                .output()
            {
                if output.status.success() {
                    let content = String::from_utf8_lossy(&output.stdout);
                    let hash = {
                        use std::hash::{Hash, Hasher};
                        let mut hasher = std::collections::hash_map::DefaultHasher::new();
                        content.hash(&mut hasher);
                        hasher.finish()
                    };
                    let prev_hash = last_content_hashes.get(task_id).copied();
                    if prev_hash.is_none() || prev_hash != Some(hash) {
                        last_activity.insert(task_id.clone(), Instant::now());
                    }
                    last_content_hashes.insert(task_id.clone(), hash);
                }
            }
        }

        // Idle timeout failure detection: if agent has been idle AND shows shell prompt
        let idle_timeout = Duration::from_secs(idle_timeout_minutes * 60);
        for task_id in &still_running {
            if completed_tasks.contains(task_id) {
                continue;
            }

            // Check if this task has been idle long enough
            let is_idle_timeout = last_activity
                .get(task_id)
                .map(|t| t.elapsed() > idle_timeout)
                .unwrap_or(false);

            if !is_idle_timeout {
                continue;
            }

            // Check if the pane shows a shell prompt (process exited)
            let window_name = format!("task-{}", task_id);
            if terminal::tmux_pane_shows_prompt(session_name, &window_name) {
                print!("\r{}\r", " ".repeat(80));
                println!(
                    "    {} {} agent idle with shell prompt, marking failed",
                    "".yellow(),
                    task_id.cyan()
                );

                // Mark as Failed
                if let Some(tag) = task_tags.get(task_id) {
                    if let Ok(mut phase) = storage.load_group(tag) {
                        if let Some(task) = phase.get_task_mut(task_id) {
                            task.set_status(TaskStatus::Failed);
                            let _ = storage.update_group(tag, &phase);
                        }
                    }
                }
                completed_tasks.insert(task_id.clone());

                // Emit failed event
                if let Some(writer) = event_writer {
                    let event = events::AgentEvent::new(
                        writer.session_id(),
                        task_id,
                        events::EventKind::Failed {
                            reason: "agent idle with shell prompt (process crashed)".to_string(),
                        },
                    );
                    let _ = writer.write(&event);
                }
            }
        }

        // Print status line (1a)
        let elapsed = round_start.elapsed().as_secs();
        let spinner = spinner_chars[spin_idx % spinner_chars.len()];
        spin_idx += 1;

        // Check for idle agents
        let idle_agents: Vec<&String> = still_running
            .iter()
            .filter(|id| {
                !completed_tasks.contains(*id)
                    && last_activity
                        .get(*id)
                        .map(|t| t.elapsed() > Duration::from_secs(60))
                        .unwrap_or(false)
            })
            .collect();

        let running_count = still_running
            .iter()
            .filter(|id| !completed_tasks.contains(*id))
            .count();

        let status = if running_count <= 2 {
            let names: Vec<&str> = still_running
                .iter()
                .filter(|id| !completed_tasks.contains(*id))
                .map(|s| s.as_str())
                .collect();
            format!("{} running: {}", running_count, names.join(", "))
        } else {
            format!("{} running", running_count)
        };

        let idle_note = if !idle_agents.is_empty() {
            format!(" ({} idle >60s)", idle_agents.len())
        } else {
            String::new()
        };

        print!(
            "\r    Waiting... [{}] {} {}s{}",
            status, spinner, elapsed, idle_note
        );
        let _ = std::io::stdout().flush();

        thread::sleep(Duration::from_secs(5));
    }

    Ok(())
}

fn collect_changed_files(
    working_dir: &std::path::Path,
    start_commit: Option<&str>,
) -> Result<Vec<String>> {
    use std::process::Command;

    // Construct the commit range: start_commit..HEAD or fallback to HEAD~1..HEAD
    let range = match start_commit {
        Some(commit) => format!("{}..HEAD", commit),
        None => "HEAD~1..HEAD".to_string(),
    };

    let output = Command::new("git")
        .current_dir(working_dir)
        .args(["diff", "--name-only", &range])
        .output()?;

    let files: Vec<String> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|s| s.to_string())
        .collect();

    Ok(files)
}

fn run_dry_run(
    project_root: Option<PathBuf>,
    phase_tag: &str,
    round_size: usize,
    all_tags: bool,
) -> Result<()> {
    let storage = Storage::new(project_root);
    let all_phases = storage.load_tasks()?;

    let waves = compute_waves_from_tasks(&all_phases, phase_tag, all_tags)?;

    println!("{}", "Execution Plan (dry-run)".yellow().bold());
    println!("{}", "".repeat(50).yellow());
    println!();

    let mut total_tasks = 0;
    let mut total_rounds = 0;

    for (wave_idx, wave) in waves.iter().enumerate() {
        let rounds = wave.len().div_ceil(round_size);
        total_tasks += wave.len();
        total_rounds += rounds;

        println!(
            "{} {} - {} task(s), {} round(s)",
            "Wave".blue().bold(),
            wave_idx + 1,
            wave.len(),
            rounds
        );

        for (round_idx, chunk) in wave.chunks(round_size).enumerate() {
            println!("  {} {}:", "Round".yellow(), round_idx + 1);
            for info in chunk {
                println!(
                    "    {} {} | {}",
                    "".white(),
                    info.task.id.cyan(),
                    info.task.title
                );
            }
        }
        println!();
    }

    println!("{}", "Summary".blue().bold());
    println!("{}", "-".repeat(30).blue());
    println!("  Total waves:  {}", waves.len());
    println!("  Total tasks:  {}", total_tasks);
    println!("  Total rounds: {}", total_rounds);

    if total_rounds > 0 {
        let speedup = total_tasks as f64 / total_rounds as f64;
        println!("  Speedup:      {}", format!("{:.1}x", speedup).green());
    }

    println!();
    println!("{}", "No agents spawned (dry-run mode).".yellow());

    Ok(())
}

// ============================================================================
// Review Agent Support
// ============================================================================

/// Result of a review operation
#[derive(Debug)]
pub struct ReviewResult {
    /// Whether all reviewed tasks passed
    pub all_passed: bool,
    /// Task IDs that need improvement
    pub tasks_to_improve: Vec<String>,
}

/// Spawn a reviewer agent and wait for it to complete
#[allow(dead_code)]
pub fn spawn_reviewer(
    working_dir: &std::path::Path,
    session_name: &str,
    summary: &WaveSummary,
    wave_tasks: &[(String, String)], // (id, title)
    review_all: bool,
) -> Result<ReviewResult> {
    println!();
    println!("  {} Spawning reviewer agent...", "Review:".magenta());

    let prompt = agent::generate_review_prompt(summary, wave_tasks, review_all);

    // Load reviewer agent definition for harness/model
    let agent_def = AgentDef::try_load("reviewer", working_dir).unwrap_or_else(|| {
        // Fallback: claude/opus
        AgentDef {
            agent: crate::agents::AgentMeta {
                name: "reviewer".to_string(),
                description: "Code reviewer".to_string(),
            },
            model: crate::agents::ModelConfig {
                harness: "claude".to_string(),
                model: Some("opus".to_string()),
            },
            prompt: Default::default(),
        }
    });

    let harness = agent_def.harness()?;
    let model = agent_def.model();

    // Spawn reviewer
    let spawn_config = terminal::SpawnConfig {
        task_id: &format!("review-wave-{}", summary.wave_number),
        prompt: &prompt,
        working_dir,
        session_name,
        harness,
        model,
        task_list_id: None,
    };
    terminal::spawn_tmux_agent(&spawn_config)?;

    println!(
        "    {} Reviewer spawned, waiting for completion...",
        "".green()
    );

    // Wait for reviewer to complete by watching for output file
    wait_for_review_completion(working_dir, summary.wave_number)
}

/// Wait for the review to complete by polling for marker file
fn wait_for_review_completion(
    working_dir: &std::path::Path,
    wave_number: usize,
) -> Result<ReviewResult> {
    let marker_path = working_dir
        .join(".scud")
        .join(format!("review-complete-{}", wave_number));

    let timeout = Duration::from_secs(1800); // 30 minute timeout
    let start = std::time::Instant::now();

    loop {
        if start.elapsed() > timeout {
            println!("    {} Review timed out after 30 minutes", "!".yellow());
            return Ok(ReviewResult {
                all_passed: true, // Assume pass on timeout
                tasks_to_improve: vec![],
            });
        }

        if marker_path.exists() {
            let content = std::fs::read_to_string(&marker_path)?;
            std::fs::remove_file(&marker_path)?; // Clean up

            let all_passed = content.contains("ALL_PASS");
            let tasks_to_improve = if content.contains("IMPROVE_TASKS:") {
                content
                    .lines()
                    .find(|l| l.starts_with("IMPROVE_TASKS:"))
                    .map(|l| {
                        l.strip_prefix("IMPROVE_TASKS:")
                            .unwrap_or("")
                            .split(',')
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect()
                    })
                    .unwrap_or_default()
            } else {
                vec![]
            };

            println!("    {} Review complete", "".green());
            if !all_passed {
                println!(
                    "    {} Tasks needing improvement: {}",
                    "!".yellow(),
                    tasks_to_improve.join(", ")
                );
            }

            return Ok(ReviewResult {
                all_passed,
                tasks_to_improve,
            });
        }

        thread::sleep(Duration::from_secs(5));
    }
}

// ============================================================================
// Repair Loop Support
// ============================================================================

/// Run repair loop for failed validation
#[allow(dead_code)]
#[allow(clippy::too_many_arguments)]
pub fn run_repair_loop(
    storage: &Storage,
    working_dir: &std::path::Path,
    session_name: &str,
    bp_config: &BackpressureConfig,
    wave_state: &WaveState,
    validation_result: &ValidationResult,
    max_attempts: usize,
) -> Result<bool> {
    let wave_tasks = wave_state.all_task_ids();
    let task_tags = wave_state.task_tags();

    println!();
    println!("  {} Analyzing failure attribution...", "Repair:".magenta());

    // Get the first failed command for attribution
    let failed_cmd = validation_result.results.iter().find(|r| !r.passed);
    let failed_cmd = match failed_cmd {
        Some(cmd) => cmd,
        None => return Ok(true), // No failures? Shouldn't happen
    };

    // Attribute the failure
    let attribution = attribute_failure(
        working_dir,
        &failed_cmd.stderr,
        &failed_cmd.stdout,
        &wave_tasks,
        wave_state.start_commit.as_deref(),
    )?;

    match attribution.confidence {
        AttributionConfidence::High => {
            println!(
                "    {} High confidence: task {} responsible",
                "".green(),
                attribution.responsible_tasks.join(", ")
            );
        }
        AttributionConfidence::Medium => {
            println!(
                "    {} Medium confidence: tasks {} may be responsible",
                "~".yellow(),
                attribution.responsible_tasks.join(", ")
            );
        }
        AttributionConfidence::Low => {
            println!(
                "    {} Low confidence: cannot determine specific task",
                "!".red()
            );
        }
    }

    // Mark cleared tasks as done
    for task_id in &attribution.cleared_tasks {
        if let Some(tag) = task_tags
            .iter()
            .find(|(id, _)| id == task_id)
            .map(|(_, t)| t)
        {
            if let Ok(mut phase) = storage.load_group(tag) {
                if let Some(task) = phase.get_task_mut(task_id) {
                    task.set_status(TaskStatus::Done);
                    let _ = storage.update_group(tag, &phase);
                    println!("    {} Cleared: {} (not responsible)", "".green(), task_id);
                }
            }
        }
    }

    // Collect task info for batch repair
    let mut task_infos: Vec<(String, String, Vec<String>)> = Vec::new();
    for task_id in &attribution.responsible_tasks {
        let (task, _tag) = match find_task_with_tag(storage, task_id, &task_tags) {
            Some(t) => t,
            None => continue,
        };

        let task_files = crate::attribution::get_task_changed_files(
            working_dir,
            task_id,
            wave_state.start_commit.as_deref(),
        )
        .unwrap_or_default()
        .into_iter()
        .collect();

        task_infos.push((task_id.clone(), task.title.clone(), task_files));
    }

    // Parse error locations for the prompt
    let error_locations: Vec<(String, Option<u32>)> =
        crate::attribution::parse_error_locations(&failed_cmd.stderr, &failed_cmd.stdout);

    // Attempt batch repairs
    for attempt in 1..=max_attempts {
        println!();
        println!(
            "  {} Batch repair attempt {}/{}",
            "Repair:".magenta(),
            attempt,
            max_attempts
        );

        // Generate batch repair prompt
        let prompt = agent::generate_batch_repair_prompt(
            &task_infos,
            &failed_cmd.command,
            &format!("{}\n{}", failed_cmd.stderr, failed_cmd.stdout),
            &error_locations,
        );

        // Spawn single batch repairer
        spawn_batch_repairer(working_dir, session_name, &prompt)?;

        // Wait for batch repair completion
        let repair_result = wait_for_batch_repair_completion(working_dir)?;

        match repair_result {
            BatchRepairResult::Success(fixed_tasks) => {
                // Re-run validation
                println!();
                println!("  {} Re-running validation...", "Validate:".magenta());
                let new_result = crate::backpressure::run_validation(working_dir, bp_config)?;

                if new_result.all_passed {
                    println!("    {} Validation passed after batch repair!", "".green());

                    // Mark all responsible tasks as done
                    for task_id in &attribution.responsible_tasks {
                        if let Some(tag) = task_tags
                            .iter()
                            .find(|(id, _)| id == task_id)
                            .map(|(_, t)| t)
                        {
                            if let Ok(mut phase) = storage.load_group(tag) {
                                if let Some(task) = phase.get_task_mut(task_id) {
                                    task.set_status(TaskStatus::Done);
                                    let _ = storage.update_group(tag, &phase);
                                }
                            }
                        }
                    }

                    return Ok(true);
                }

                println!(
                    "    {} Validation still failing (fixed: {}), will retry...",
                    "!".yellow(),
                    fixed_tasks.join(", ")
                );
            }
            BatchRepairResult::Partial(fixed, blocked) => {
                // Mark fixed tasks as done, blocked as blocked
                for task_id in &fixed {
                    if let Some(tag) = task_tags
                        .iter()
                        .find(|(id, _)| id == task_id)
                        .map(|(_, t)| t)
                    {
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Done);
                                let _ = storage.update_group(tag, &phase);
                                println!("    {} Fixed: {}", "".green(), task_id);
                            }
                        }
                    }
                }
                for task_id in &blocked {
                    if let Some(tag) = task_tags
                        .iter()
                        .find(|(id, _)| id == task_id)
                        .map(|(_, t)| t)
                    {
                        if let Ok(mut phase) = storage.load_group(tag) {
                            if let Some(task) = phase.get_task_mut(task_id) {
                                task.set_status(TaskStatus::Blocked);
                                let _ = storage.update_group(tag, &phase);
                                println!("    {} Blocked: {}", "!".yellow(), task_id);
                            }
                        }
                    }
                }

                // Re-run validation
                let new_result = crate::backpressure::run_validation(working_dir, bp_config)?;
                if new_result.all_passed {
                    println!("    {} Validation passed!", "".green());
                    return Ok(true);
                }
            }
            BatchRepairResult::Blocked(reason) => {
                println!("    {} Batch repair blocked: {}", "!".red(), reason);
            }
            BatchRepairResult::Timeout => {
                println!("    {} Batch repair timed out", "!".yellow());
            }
        }
    }

    // Max attempts reached - mark responsible tasks as failed
    println!();
    println!("  {} Max repair attempts reached", "!".red());

    for task_id in &attribution.responsible_tasks {
        if let Some(tag) = task_tags
            .iter()
            .find(|(id, _)| id == task_id)
            .map(|(_, t)| t)
        {
            if let Ok(mut phase) = storage.load_group(tag) {
                if let Some(task) = phase.get_task_mut(task_id) {
                    task.set_status(TaskStatus::Failed);
                    let _ = storage.update_group(tag, &phase);
                    println!("    {} Marked failed: {}", "".red(), task_id);
                }
            }
        }
    }

    Ok(false)
}

/// Spawn a repairer agent for a specific task (kept as fallback for single-task scenarios)
#[allow(dead_code)]
fn spawn_repairer(
    working_dir: &std::path::Path,
    session_name: &str,
    task_id: &str,
    prompt: &str,
) -> Result<()> {
    // Load repairer agent definition
    let agent_def = AgentDef::try_load("repairer", working_dir).unwrap_or_else(|| AgentDef {
        agent: crate::agents::AgentMeta {
            name: "repairer".to_string(),
            description: "Repair agent".to_string(),
        },
        model: crate::agents::ModelConfig {
            harness: "claude".to_string(),
            model: Some("opus".to_string()),
        },
        prompt: Default::default(),
    });

    let harness = agent_def.harness()?;
    let model = agent_def.model();

    let spawn_config = terminal::SpawnConfig {
        task_id: &format!("repair-{}", task_id),
        prompt,
        working_dir,
        session_name,
        harness,
        model,
        task_list_id: None,
    };
    terminal::spawn_tmux_agent(&spawn_config)?;

    println!("    {} Spawned repairer for {}", "".green(), task_id);
    Ok(())
}

/// Wait for a repair to complete by polling for marker file (kept as fallback for single-task scenarios)
#[allow(dead_code)]
fn wait_for_repair_completion_task(working_dir: &std::path::Path, task_id: &str) -> Result<bool> {
    let marker_path = working_dir
        .join(".scud")
        .join(format!("repair-complete-{}", task_id));

    let timeout = Duration::from_secs(1800); // 30 minute timeout
    let start = std::time::Instant::now();

    loop {
        if start.elapsed() > timeout {
            println!("    {} Repair timed out for {}", "!".yellow(), task_id);
            return Ok(false);
        }

        if marker_path.exists() {
            let content = std::fs::read_to_string(&marker_path)?;
            std::fs::remove_file(&marker_path)?;

            let success = content.contains("SUCCESS");
            if success {
                println!("    {} Repair completed for {}", "".green(), task_id);
            } else {
                println!("    {} Repair blocked for {}", "!".yellow(), task_id);
            }

            return Ok(success);
        }

        thread::sleep(Duration::from_secs(5));
    }
}

/// Result of a batch repair attempt
enum BatchRepairResult {
    Success(Vec<String>),              // All fixed, list of task IDs
    Partial(Vec<String>, Vec<String>), // Some fixed, some blocked
    Blocked(String),                   // Completely blocked with reason
    Timeout,                           // Timed out
}

/// Spawn a batch repairer agent
fn spawn_batch_repairer(
    working_dir: &std::path::Path,
    session_name: &str,
    prompt: &str,
) -> Result<()> {
    // Load repairer agent definition
    let agent_def = AgentDef::try_load("repairer", working_dir).unwrap_or_else(|| AgentDef {
        agent: crate::agents::AgentMeta {
            name: "batch-repairer".to_string(),
            description: "Batch repair agent".to_string(),
        },
        model: crate::agents::ModelConfig {
            harness: "claude".to_string(),
            model: Some("opus".to_string()),
        },
        prompt: Default::default(),
    });

    let harness = agent_def.harness()?;
    let model = agent_def.model();

    let spawn_config = terminal::SpawnConfig {
        task_id: "batch-repair",
        prompt,
        working_dir,
        session_name,
        harness,
        model,
        task_list_id: None,
    };
    terminal::spawn_tmux_agent(&spawn_config)?;

    println!("    {} Spawned batch repairer", "".green());
    Ok(())
}

/// Wait for batch repair to complete by polling for marker file
fn wait_for_batch_repair_completion(working_dir: &std::path::Path) -> Result<BatchRepairResult> {
    let marker_path = working_dir.join(".scud").join("batch-repair-complete");

    let timeout = Duration::from_secs(2700); // 45 minute timeout for batch
    let start = std::time::Instant::now();

    loop {
        if start.elapsed() > timeout {
            return Ok(BatchRepairResult::Timeout);
        }

        if marker_path.exists() {
            let content = std::fs::read_to_string(&marker_path)?;
            let _ = std::fs::remove_file(&marker_path); // Clean up

            // Parse the marker file
            if content.contains("SUCCESS") {
                let fixed = parse_task_list(&content, "FIXED_TASKS:");
                return Ok(BatchRepairResult::Success(fixed));
            } else if content.contains("PARTIAL") {
                let fixed = parse_task_list(&content, "FIXED_TASKS:");
                let blocked = parse_task_list(&content, "BLOCKED_TASKS:");
                return Ok(BatchRepairResult::Partial(fixed, blocked));
            } else if content.contains("BLOCKED") {
                let reason = content
                    .lines()
                    .find(|l| l.starts_with("REASON:"))
                    .map(|l| l.trim_start_matches("REASON:").trim().to_string())
                    .unwrap_or_else(|| "Unknown reason".to_string());
                return Ok(BatchRepairResult::Blocked(reason));
            }
        }

        thread::sleep(Duration::from_secs(5));
    }
}

/// Parse comma-separated task list from marker file line
fn parse_task_list(content: &str, prefix: &str) -> Vec<String> {
    content
        .lines()
        .find(|l| l.starts_with(prefix))
        .map(|l| {
            l.trim_start_matches(prefix)
                .trim()
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect()
        })
        .unwrap_or_default()
}

/// Find a task by ID along with its tag
fn find_task_with_tag(
    storage: &Storage,
    task_id: &str,
    task_tags: &[(String, String)],
) -> Option<(Task, String)> {
    let tag = task_tags.iter().find(|(id, _)| id == task_id)?.1.clone();
    let phase = storage.load_group(&tag).ok()?;
    let task = phase.get_task(task_id)?.clone();
    Some((task, tag))
}