orch-cli 0.89.3

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
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
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
//! Core tick loop phases.
//!
//! The engine ticks every ~10 seconds. Each tick runs six sequential phases:
//! 1. Poll tmux for finished sessions
//! 2. Recover stuck in-progress tasks
//! 3. Route and dispatch:
//!    - 3a. Route new tasks to agents
//!    - 3b. Dispatch routed tasks (spawn agents)
//! 4. Unblock parents whose children are all done
//! 5. Run cron job scheduler

use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Status};
use crate::channels::capture::CaptureService;
use crate::config;
use crate::engine::cooldown::{
    github_circuit_remaining_secs, is_agent_in_cooldown, is_github_circuit_open,
    is_model_in_cooldown, record_agent_failure_with_message, record_silence_detection,
    set_agent_cooldown, set_model_cooldown, SILENCE_AGENT_COOLDOWN_SECS,
    SILENCE_EXTENDED_COOLDOWN_SECS,
};
use crate::engine::dispatch_guard::DispatchGuard;
use crate::engine::jobs;
use crate::engine::router::{get_route_result, AllAgentsCooledError, RouteResultError, Router};
use crate::engine::runner::{TaskRunner, WeightSignal};
use crate::engine::tasks::{is_internal_id, TaskManager};
use crate::repo_context::REPO_CONTEXT;
use crate::store::TaskStore;
use crate::tmux::TmuxManager;
use dashmap::{DashMap, DashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::{Instant, SystemTime};
use tokio::sync::{mpsc, Semaphore};

/// Unix timestamp when the engine process started.
/// Used to identify tmux sessions from previous runs.
static ENGINE_START_TIME: LazyLock<u64> = LazyLock::new(|| {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
});

/// Flag to ensure startup cleanup only runs once.
static STARTUP_CLEANUP_DONE: AtomicBool = AtomicBool::new(false);

/// Per outer engine-loop quota for expensive routing calls.
///
/// `tick()` runs once per active project. Without a quota shared by all those
/// project ticks, `router.max_tasks_per_tick = 1` still permits one slow LLM
/// routing call per project plus one global sweep route per project, multiplying
/// 45s router timeouts into multi-minute watchdog stalls.
pub(crate) struct RoutingTickQuota {
    remaining: usize,
}

impl RoutingTickQuota {
    pub(crate) fn new(max: usize) -> Self {
        Self { remaining: max }
    }

    fn is_exhausted(&self) -> bool {
        self.remaining == 0
    }

    fn remaining(&self) -> usize {
        self.remaining
    }

    fn consume_one(&mut self) -> bool {
        if self.remaining == 0 {
            return false;
        }
        self.remaining -= 1;
        true
    }
}

/// Cleanup stale tmux sessions from previous engine runs.
/// Called once at startup to kill sessions created before this process started.
async fn startup_cleanup(tmux: &TmuxManager) {
    // Use compare_exchange to ensure this only runs once across all threads
    if STARTUP_CLEANUP_DONE
        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
        .is_err()
    {
        return;
    }

    let start_time = *ENGINE_START_TIME;
    tracing::info!(
        start_time,
        "running startup cleanup for stale tmux sessions"
    );

    match tmux.kill_stale_sessions(start_time).await {
        Ok(killed) => {
            if killed > 0 {
                tracing::info!(killed, "startup cleanup killed stale sessions");
            } else {
                tracing::debug!("no stale tmux sessions found on startup");
            }
        }
        Err(e) => {
            tracing::warn!(error = %e, "failed to run startup cleanup");
        }
    }
}

use super::EngineConfig;
use crate::store::{set_review_session_expected, store_set_by_id, store_touch_updated_at};

async fn recover_routed_blocked_dispatch(
    backend: &Arc<dyn ExternalBackend>,
    store: &Arc<TaskStore>,
    task_manager: &Arc<TaskManager>,
    repo: &str,
    task: &ExternalTask,
    timing: &StuckTaskTiming,
) {
    tracing::warn!(
        task_id = task.id.0,
        age_mins = timing.age.num_minutes(),
        threshold_mins = timing.threshold / 60,
        "recovering routed task: dispatch blocked by stale tmux session → new"
    );

    let resolved_store_id = match store.resolve_task_id(repo, &task.id.0).await {
        Ok(Some(id)) => Some(id),
        Ok(None) => {
            tracing::warn!(
                task_id = %task.id.0,
                repo,
                "resolve_task_id returned None during routed-task recovery"
            );
            None
        }
        Err(e) => {
            tracing::error!(
                task_id = %task.id.0,
                repo,
                error = %e,
                "resolve_task_id failed during routed-task recovery"
            );
            None
        }
    };

    if let Some(store_id) = resolved_store_id {
        if let Err(e) = store_set_by_id(
            &Some(store),
            store_id,
            &[
                ("agent", serde_json::Value::Null),
                ("model", serde_json::Value::Null),
                ("route_attempts", serde_json::json!(0)),
            ],
        )
        .await
        {
            tracing::warn!(
                task_id = task.id.0,
                ?e,
                "failed to clear routing fields for routed stuck task — will retry next tick"
            );
            return;
        }
        finalize_open_runs_for_recovery(
            store,
            store_id,
            "stuck-task recovery: stale session blocking dispatch killed",
        )
        .await;
    }

    if let Err(e) = task_manager.update_task_status(&task.id, Status::New).await {
        tracing::warn!(
            task_id = task.id.0,
            ?e,
            "failed to reset routed stuck task status"
        );
        return;
    }

    crate::store::store_log_activity(
        &Some(Arc::clone(store)),
        repo,
        &task.id.0,
        "rerouted",
        Some("routed"),
        Some("new"),
        None::<&str>,
        None::<&str>,
        Some(&serde_json::json!({
            "failure_reason": "routed_blocked_by_existing_session",
            "age_minutes": timing.age.num_minutes(),
            "had_session": true,
        })),
    )
    .await;

    if !is_internal_id(&task.id.0) {
        let backend_clone = Arc::clone(backend);
        let task_id_clone = task.id.clone();
        let body = format!(
            "[{}] recovered: stuck routed task — existing tmux session blocked dispatch for {}m; cleared route for retry{}",
            chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
            timing.age.num_minutes(),
            crate::engine::orch_footer()
        );
        tokio::spawn(async move {
            if let Err(e) = backend_clone.post_comment(&task_id_clone, &body).await {
                tracing::warn!(
                    task_id = task_id_clone.0,
                    ?e,
                    "failed to post routed-task recovery comment"
                );
            }
        });
    }
}

/// Phase 1 of tick: poll tmux for finished sessions and clean them up.
pub(crate) async fn tick_check_session_completions(
    tmux: &Arc<TmuxManager>,
    repo: &str,
    capture: &Arc<CaptureService>,
    store: &Arc<TaskStore>,
) -> anyhow::Result<()> {
    let _span = tracing::info_span!("engine.tick.phase1.sessions").entered();
    let session_snapshot = tmux.snapshot().await;
    // Derive the short project name from repo (owner/repo -> repo), matching
    // TmuxManager::session_name's derivation exactly (including the ".git" strip)
    // so a repo configured with a ".git" suffix doesn't silently fail to match
    // its own live sessions here — leaving stuck-task recovery as the only
    // (later, coarser-grained) safety net for this repo's session completions.
    let repo_name = repo
        .rsplit('/')
        .next()
        .unwrap_or(repo)
        .trim_end_matches(".git");
    for (session, active) in session_snapshot {
        // Only handle sessions that belong to this repo/project.
        if session.project != repo_name {
            continue;
        }

        if !active {
            tracing::info!(
                session = %session.name,
                task_id = %session.task_id,
                "session completed, collecting results"
            );
            // Touch the store.updated_at immediately when we observe a completed
            // session so the stuck-task recovery phase doesn't incorrectly
            // reclaim this task while the runner is still finishing
            // post-processing (race: session observed dead → tick reclaim).
            // Best-effort: no-ops if the task isn't present in the store.
            //
            // session.task_id uses hyphens (e.g. "internal-63714") because the
            // tmux session name sanitizes colons to hyphens. resolve_task_id only
            // handles "internal:" prefix, so we must convert back before touching.
            // Review sessions carry a "-review" suffix tracked under the main task.
            let store_task_id = {
                let base = session
                    .task_id
                    .strip_suffix("-review")
                    .unwrap_or(&session.task_id);
                if let Some(n) = base.strip_prefix("internal-") {
                    format!("internal:{n}")
                } else {
                    base.to_string()
                }
            };
            store_touch_updated_at(&Some(Arc::clone(store)), repo, &store_task_id).await;
            // Unregister from capture service using the task id the capture service
            // was registered under (task id without project prefix).
            capture.unregister_session(repo, &session.task_id).await;
            // Kill the actual tmux session name we discovered (do not reconstruct)
            if let Err(e) = tmux.kill_session(&session.name).await {
                tracing::debug!(
                    session = %session.name,
                    ?e,
                    "kill_session failed (session may already be gone)"
                );
            }
        }
    }
    Ok(())
}

#[derive(Debug)]
struct StuckTaskTiming {
    has_session: bool,
    age: chrono::Duration,
    threshold: u64,
}

#[allow(clippy::too_many_arguments)]
fn stuck_task_timing_from_map(
    tmux: &Arc<TmuxManager>,
    repo: &str,
    session_task_id: &str,
    updated_at: &str,
    config: &EngineConfig,
    parse_error_message: &'static str,
    session_map: &std::collections::HashMap<String, bool>,
) -> Option<StuckTaskTiming> {
    let session_name = tmux.session_name(repo, session_task_id);
    // A session is "running" if it appears in the map with alive=true.
    let has_session = session_map.get(&session_name).copied().unwrap_or(false);
    let threshold = if has_session {
        config.stuck_timeout
    } else {
        config.no_session_stuck_timeout
    };

    let updated = match chrono::DateTime::parse_from_rfc3339(updated_at) {
        Ok(dt) => dt.with_timezone(&chrono::Utc),
        Err(e) => {
            tracing::warn!(
                task_id = session_task_id,
                updated_at,
                ?e,
                error_message = parse_error_message,
                "cannot parse updated_at"
            );
            return None;
        }
    };

    let raw_age = chrono::Utc::now() - updated;
    // Host suspend (laptop sleep) freezes the process just like it freezes the agent
    // running inside it — that frozen time is not evidence of a hang. Discount any
    // detected suspend/resume gaps that occurred since this task was last touched.
    let suspended = super::suspend::suspended_duration_since(updated);
    let age = (raw_age - suspended).max(chrono::Duration::zero());
    if age.num_seconds() <= threshold as i64 {
        return None;
    }

    Some(StuckTaskTiming {
        has_session,
        age,
        threshold,
    })
}

/// Finalize any open `task_runs` rows for a task during recovery paths.
/// Best-effort: logs a warning on failure but does not block recovery.
async fn finalize_open_runs_for_recovery(store: &TaskStore, store_id: i64, reason: &str) {
    if let Err(e) = store
        .finalize_incomplete_runs(store_id, "aborted", reason)
        .await
    {
        tracing::warn!(
            store_id,
            error = %e,
            reason,
            "failed to finalize incomplete runs during recovery"
        );
    }
}

/// Phase 1b of tick: detect agents that have produced no output since session start
/// and have exceeded the silence grace period.
///
/// Only triggers on complete silence (agent never produced any output). Agents that
/// produced output then went quiet (e.g. long tool calls) are NOT affected.
///
/// On silence: kills the tmux session, applies model-level cooldown, resets the task
/// to `New` so the router picks a different agent/model.
pub(crate) async fn tick_detect_silent_agents(
    tmux: &Arc<TmuxManager>,
    repo: &str,
    capture: &Arc<CaptureService>,
    backend: &Arc<dyn ExternalBackend>,
    task_manager: &Arc<TaskManager>,
    config: &EngineConfig,
    store: &Arc<TaskStore>,
) -> anyhow::Result<()> {
    let _span = tracing::info_span!("engine.tick.phase1b.silence").entered();
    let grace = std::time::Duration::from_secs(config.silence_grace_period);
    let silent_sessions = capture.get_silent_sessions_for_repo(repo, grace).await;

    for (task_id, session_name, silence_age_secs) in silent_sessions {
        let use_backend = should_use_backend(&task_id);
        // Look up agent + model from the store so we can cooldown the right model.
        let store_task = match store.resolve_task_id(repo, &task_id).await {
            Ok(Some(store_id)) => match store.get(store_id).await {
                Ok(task) => Some(task),
                Err(e) => {
                    tracing::warn!(
                        task_id,
                        repo,
                        store_id,
                        operation = "store.get",
                        error = %e,
                        "silence detection: db error fetching task — agent/model cooldown will be skipped"
                    );
                    None
                }
            },
            Ok(None) => {
                tracing::debug!(
                    task_id,
                    repo,
                    operation = "resolve_task_id",
                    "silence detection: task not found in store (may have been cleaned up)"
                );
                None
            }
            Err(e) => {
                tracing::warn!(
                    task_id,
                    repo,
                    operation = "resolve_task_id",
                    error = %e,
                    "silence detection: db error resolving task id — agent/model cooldown will be skipped"
                );
                None
            }
        };
        let agent_name = store_task
            .as_ref()
            .and_then(|t| t.agent.clone())
            .unwrap_or_default();
        let model_name = store_task
            .as_ref()
            .and_then(|t| t.model.clone())
            .unwrap_or_default();

        tracing::warn!(
            task_id,
            agent = %agent_name,
            model = %model_name,
            silence_age_secs,
            grace_secs = config.silence_grace_period,
            cooldown_secs = config.silence_cooldown,
            "agent silent since session start — killing session, cooling down model + agent, failing over"
        );

        // 1. Kill the tmux session
        if let Err(e) = tmux.kill_session(&session_name).await {
            tracing::debug!(
                task_id,
                ?e,
                "kill_session failed for silent agent (may already be gone)"
            );
        }

        // 2. Unregister from capture
        capture.unregister_session(repo, &task_id).await;

        // Finalize any open audit run so the task_runs row is not orphaned
        if let Some(store_id) = store_task.as_ref().map(|t| t.id) {
            finalize_open_runs_for_recovery(store, store_id, "silence detection: session killed")
                .await;
        }

        let mut extended_note = String::new();

        // 3. Cooldown the specific model (not the whole agent)
        if !agent_name.is_empty() && !model_name.is_empty() {
            set_model_cooldown(
                &agent_name,
                &model_name,
                config.silence_cooldown,
                "silence_detected",
            )
            .await;
            if let Some(result) = record_silence_detection(&agent_name, &model_name).await {
                if result.extended_cooldown_applied {
                    extended_note = format!(
                        " ({} silences in 24h -> extended cooldown {}s)",
                        result.count, SILENCE_EXTENDED_COOLDOWN_SECS
                    );
                }
            }
        }

        // 3b. Short agent-level cooldown to force router to pick a different agent.
        // Without this, the router picks the same agent with a different model,
        // looping through all models (~2 min each) before the long agent cooldown kicks in.
        if !agent_name.is_empty() {
            set_agent_cooldown(&agent_name, SILENCE_AGENT_COOLDOWN_SECS).await;
        }

        // 4. Pick a fallback agent and set to Routed (not New) to preserve progress.
        // Setting to New would clear routing state and trigger a full LLM re-routing
        // cycle, losing intermediate context. Routed skips re-routing and re-dispatches
        // directly with the chosen fallback agent.
        let task_eid = ExternalId(task_id.clone());

        // Build available agents list and reroute chain for failover
        let available: Vec<String> = crate::engine::configured_agents()
            .into_iter()
            .filter(|a| crate::cmd_cache::command_exists(a))
            .collect();
        let chain = crate::engine::runner::response::get_reroute_chain(
            &task_id,
            &Some(Arc::clone(store)),
            repo,
        )
        .await;
        let chain = crate::engine::runner::response::update_reroute_chain(
            &task_id,
            &agent_name,
            &chain,
            &Some(Arc::clone(store)),
            repo,
        )
        .await;

        let (next_status, next_agent) = if let Some(fallback) =
            crate::engine::runner::response::pick_fallback_agent(&agent_name, &chain, &available)
        {
            tracing::info!(
                task_id,
                from = %agent_name,
                to = %fallback,
                "silence detection: failover to different agent, setting routed"
            );
            (Status::Routed, Some(fallback))
        } else {
            tracing::warn!(
                task_id,
                "silence detection: no fallback agents available, resetting to new for re-routing"
            );
            (Status::New, None)
        };

        if use_backend {
            if let Some(ref st) = store_task {
                // Fire-and-forget: label removals are cosmetic — tick should not block on them.
                let stale_labels: Vec<String> = st
                    .labels
                    .iter()
                    .filter(|l| {
                        l.starts_with("agent:")
                            || l.starts_with("complexity:")
                            || l.starts_with("model:")
                    })
                    .cloned()
                    .collect();
                if !stale_labels.is_empty() {
                    let backend_clone = Arc::clone(backend);
                    let task_eid_clone = task_eid.clone();
                    tokio::spawn(async move {
                        for label in &stale_labels {
                            if let Err(e) = backend_clone.remove_label(&task_eid_clone, label).await
                            {
                                tracing::warn!(task_id = task_eid_clone.0, label, error = %e, "failed to remove label during silence detection re-route");
                            }
                        }
                    });
                }
            }
        }

        if let Some(store_id) = store_task.as_ref().map(|t| t.id) {
            if let Some(ref fallback) = next_agent {
                // Write the fallback agent into the store so dispatch can proceed
                // directly without an LLM re-routing cycle. Clearing model forces
                // model_for_complexity to pick the best available model for the new agent.
                let _ = store_set_by_id(
                    &Some(store),
                    store_id,
                    &[
                        ("agent", serde_json::json!(fallback)),
                        ("model", serde_json::json!("")),
                        (
                            "last_error",
                            serde_json::json!(format!(
                                "silence detected after {}s, failing over to {}",
                                config.silence_grace_period, fallback
                            )),
                        ),
                    ],
                )
                .await;
            } else {
                let _ = store_set_by_id(
                    &Some(store),
                    store_id,
                    &[
                        ("agent", serde_json::Value::Null),
                        ("model", serde_json::Value::Null),
                        (
                            "last_error",
                            serde_json::json!(format!(
                                "silence detected after {}s, no fallback agents available",
                                config.silence_grace_period
                            )),
                        ),
                    ],
                )
                .await;
            }
        }

        if let Err(e) = task_manager
            .update_task_status(&task_eid, next_status)
            .await
        {
            tracing::warn!(task_id, ?e, "failed to update silent task status");
            continue;
        }

        // Log reroute activity
        let details = serde_json::json!({
            "failure_reason": "agent_silence",
            "silence_duration_secs": config.silence_grace_period,
            "cooldown_applied": !agent_name.is_empty() && !model_name.is_empty(),
            "fallback_available": next_agent.is_some(),
        });
        crate::store::store_log_activity(
            &Some(Arc::clone(store)),
            repo,
            &task_id,
            "rerouted",
            Some("in_progress"),
            Some(next_status.as_str()),
            next_agent.as_deref(),
            None,
            Some(&details),
        )
        .await;

        // 5. Post a comment explaining what happened
        let action = if let Some(ref fallback) = next_agent {
            format!("failing over to {fallback}")
        } else {
            "marking needs_review (no fallback agents)".to_string()
        };
        let comment = format!(
            "[{}] agent silent for {}s since session start — killed session, cooled down model `{}:{}` for {}s{}, agent `{}` for {}s, {}{}",
            chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
            config.silence_grace_period,
            agent_name,
            model_name,
            config.silence_cooldown,
            extended_note,
            agent_name,
            SILENCE_AGENT_COOLDOWN_SECS,
            action,
            crate::engine::orch_footer(),
        );
        if use_backend {
            // Fire-and-forget: comment is informational — tick should not block on it.
            let backend_clone = Arc::clone(backend);
            let task_eid_clone = task_eid.clone();
            tokio::spawn(async move {
                if let Err(e) = backend_clone.post_comment(&task_eid_clone, &comment).await {
                    tracing::warn!(
                        task_id = task_eid_clone.0,
                        ?e,
                        "failed to post silence detection comment"
                    );
                }
            });
        }
    }

    Ok(())
}

fn should_use_backend(task_id: &str) -> bool {
    !is_internal_id(task_id)
}

/// Phase 2 of tick: recover tasks stranded by missing or stale tmux state.
/// - `in_progress` tasks → reset to `New` when their session is missing or the run timed out
/// - `routed` tasks      → reset to `New` when an old live session keeps blocking re-dispatch
/// - `in_review` tasks   → reset to `NeedsReview` when the review session disappeared
#[allow(clippy::too_many_arguments)]
pub(crate) async fn tick_recover_stuck_tasks(
    backend: &Arc<dyn ExternalBackend>,
    tmux: &Arc<TmuxManager>,
    repo: &str,
    task_manager: &Arc<TaskManager>,
    config: &EngineConfig,
    store: &Arc<TaskStore>,
    session_map: &std::collections::HashMap<String, bool>,
    router: &Router,
    dispatching: &Arc<DashMap<String, String>>,
    auto_merge_in_flight: &Arc<DashSet<String>>,
) -> anyhow::Result<()> {
    let _span = tracing::info_span!("engine.tick.phase2.stuck_tasks").entered();

    let in_progress = match task_manager
        .list_external_by_status(Status::InProgress)
        .await
    {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::warn!(?e, "failed to list in_progress tasks for stuck recovery");
            vec![]
        }
    };
    for task in &in_progress {
        let Some(timing) = stuck_task_timing_from_map(
            tmux,
            repo,
            &task.id.0,
            &task.updated_at,
            config,
            "cannot parse updated_at, skipping stuck-task check",
            session_map,
        ) else {
            continue;
        };

        // A dead tmux session with no `updated_at` refresh in a long time normally means
        // the runner vanished (crashed, orch restarted). But it also matches the tail end
        // of a *successful* run: the session exits the instant the agent finishes, while
        // the runner is still polling for that exit (up to its own poll interval) and then
        // writing results. If the runner's dispatch guard for this task is still held, the
        // runner is alive and actively processing — let it finish rather than racing it.
        if !timing.has_session {
            let dispatch_key = format!("{repo}/{}", task.id.0);
            if dispatching.contains_key(&dispatch_key) {
                // Promoted from debug! to info!: the default log filter is "orch=info"
                // (see main.rs), so this line — the only direct evidence that the guard
                // check actually found and honored a held dispatch guard — was silently
                // dropped in production. Every prior occurrence of the reclaim race
                // (#3518/#3519/#3523/#3525/#3526) had to be diagnosed from timestamp
                // correlation alone because this and the "dispatch guard
                // claimed"/"released" lines never appeared in orch.log.
                tracing::info!(
                    task_id = task.id.0,
                    dispatch_key,
                    age_mins = timing.age.num_minutes(),
                    "skipping stuck-task reclaim: runner still actively processing this task"
                );
                continue;
            }
        }

        if timing.has_session {
            tracing::warn!(
                task_id = task.id.0,
                age_mins = timing.age.num_minutes(),
                threshold_mins = timing.threshold / 60,
                "recovering stuck task: timed out with active session → new"
            );
        } else {
            tracing::warn!(
                task_id = task.id.0,
                dispatch_key = format!("{repo}/{}", task.id.0),
                age_mins = timing.age.num_minutes(),
                threshold_mins = timing.threshold / 60,
                "recovering stuck task: no session found — reclaiming early → new"
            );
        }
        // For stuck tasks with an active session, record agent/model failure + cooldown so the
        // router picks a different agent/model on the next attempt. Without this, the router
        // sees the agent as healthy and selects it again, causing the hang to repeat.
        // (Mirrors the pattern in tick_detect_silent_agents lines 219–284.)
        let mut cached_store_id: Option<i64> = None;
        if timing.has_session {
            let store_task = match store.resolve_task_id(repo, &task.id.0).await {
                Ok(Some(store_id)) => {
                    cached_store_id = Some(store_id);
                    match store.get(store_id).await {
                        Ok(t) => Some(t),
                        Err(e) => {
                            tracing::warn!(task_id = task.id.0, error = %e, "failed to fetch task from store for stuck-task cooldown");
                            None
                        }
                    }
                }
                Ok(None) => None,
                Err(e) => {
                    tracing::warn!(task_id = task.id.0, error = %e, "failed to resolve task id for stuck-task cooldown");
                    None
                }
            };
            let agent_name = store_task
                .as_ref()
                .and_then(|t| t.agent.clone())
                .unwrap_or_default();
            let model_name = store_task
                .as_ref()
                .and_then(|t| t.model.clone())
                .unwrap_or_default();

            if !agent_name.is_empty() && !model_name.is_empty() {
                set_model_cooldown(
                    &agent_name,
                    &model_name,
                    config.silence_cooldown,
                    "silence_detected",
                )
                .await;
                record_agent_failure_with_message(
                    &agent_name,
                    &format!(
                        "stuck with active session after {}m",
                        timing.age.num_minutes()
                    ),
                )
                .await;
            }
            if !agent_name.is_empty() {
                set_agent_cooldown(&agent_name, SILENCE_AGENT_COOLDOWN_SECS).await;
            }
            tracing::warn!(
                task_id = task.id.0,
                agent = %agent_name,
                model = %model_name,
                cooldown_secs = config.silence_cooldown,
                "stuck-task cooldown applied — router will avoid this agent/model on next attempt"
            );
        }

        // Remove stale agent/model labels so the LLM router re-routes properly.
        // Fire-and-forget: cosmetic label operation, tick should not block on it.
        {
            let stale_labels: Vec<String> = task
                .labels
                .iter()
                .filter(|l| l.starts_with("agent:") || l.starts_with("model:"))
                .cloned()
                .collect();
            if !stale_labels.is_empty() {
                let backend_clone = Arc::clone(backend);
                let task_id_clone = task.id.clone();
                tokio::spawn(async move {
                    for label in &stale_labels {
                        if let Err(e) = backend_clone.remove_label(&task_id_clone, label).await {
                            tracing::warn!(task_id = task_id_clone.0, label, error = %e, "failed to remove stale routing label during stuck-task recovery");
                        }
                    }
                });
            }
        }
        let resolved_store_id = match cached_store_id {
            Some(id) => Some(id),
            None => match store.resolve_task_id(repo, &task.id.0).await {
                Ok(Some(id)) => Some(id),
                Ok(None) => {
                    tracing::warn!(
                        task_id = %task.id.0,
                        repo,
                        "resolve_task_id returned None during stuck-task recovery"
                    );
                    None
                }
                Err(e) => {
                    tracing::error!(
                        task_id = %task.id.0,
                        repo,
                        error = %e,
                        "resolve_task_id failed during stuck-task recovery"
                    );
                    None
                }
            },
        };
        if let Some(store_id) = resolved_store_id {
            if let Err(e) = store_set_by_id(
                &Some(store),
                store_id,
                &[
                    ("agent", serde_json::Value::Null),
                    ("model", serde_json::Value::Null),
                    ("route_attempts", serde_json::json!(0)),
                ],
            )
            .await
            {
                tracing::warn!(
                    task_id = task.id.0,
                    ?e,
                    "failed to clear routing fields for stuck task — will retry next tick"
                );
                continue;
            }
            finalize_open_runs_for_recovery(
                store,
                store_id,
                if timing.has_session {
                    "stuck-task recovery: active session killed"
                } else {
                    "stuck-task recovery: no session found"
                },
            )
            .await;
        }
        if let Err(e) = task_manager.update_task_status(&task.id, Status::New).await {
            tracing::warn!(task_id = task.id.0, ?e, "failed to reset stuck task status");
            continue;
        }

        // Log reroute activity for stuck task recovery
        let details = serde_json::json!({
            "failure_reason": if timing.has_session { "stuck_with_session" } else { "stuck_no_session" },
            "age_minutes": timing.age.num_minutes(),
            "had_session": timing.has_session,
        });
        crate::store::store_log_activity(
            &Some(Arc::clone(store)),
            repo,
            &task.id.0,
            "rerouted",
            Some("in_progress"),
            Some("new"),
            None::<&str>,
            None::<&str>,
            Some(&details),
        )
        .await;

        let reason = if timing.has_session {
            format!(
                "timed out after {}m with active session (cleared agent for re-routing)",
                timing.age.num_minutes()
            )
        } else {
            format!(
                "no session found — reclaiming early after {}m (cleared agent for re-routing)",
                timing.age.num_minutes()
            )
        };
        // Fire-and-forget: comment is informational — tick should not block on it.
        {
            let backend_clone = Arc::clone(backend);
            let task_id_clone = task.id.clone();
            let body = format!(
                "[{}] recovered: stuck in_progress — {}{}",
                chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
                reason,
                crate::engine::orch_footer()
            );
            tokio::spawn(async move {
                if let Err(e) = backend_clone.post_comment(&task_id_clone, &body).await {
                    tracing::warn!(
                        task_id = task_id_clone.0,
                        ?e,
                        "failed to post stuck-task recovery comment"
                    );
                }
            });
        }
    }

    let mut routed = match task_manager.list_external_by_status(Status::Routed).await {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::warn!(?e, "failed to list routed tasks for stuck recovery");
            vec![]
        }
    };
    match task_manager
        .list_internal_by_status(crate::store::TaskStatus::Routed)
        .await
    {
        Ok(tasks) => routed.extend(tasks),
        Err(e) => tracing::warn!(
            ?e,
            "failed to list internal routed tasks for stuck recovery"
        ),
    }
    for task in &routed {
        let Some(timing) = stuck_task_timing_from_map(
            tmux,
            repo,
            &task.id.0,
            &task.updated_at,
            config,
            "cannot parse updated_at, skipping routed stuck-task check",
            session_map,
        ) else {
            continue;
        };

        if !timing.has_session {
            continue;
        }

        let session_name = tmux.session_name(repo, &task.id.0);
        if let Err(e) = tmux.kill_session(&session_name).await {
            tracing::warn!(
                task_id = task.id.0,
                session = %session_name,
                error = %e,
                "failed to kill stale tmux session blocking routed task"
            );
            continue;
        }

        recover_routed_blocked_dispatch(backend, store, task_manager, repo, task, &timing).await;
    }

    // Global recovery for external tasks from repos that are not currently being ticked.
    // These tasks would otherwise remain in_progress forever if their project was removed
    // from active config and never enters this tick loop again.
    let all_external_in_progress = match store
        .list_all_by_status_global(crate::store::TaskStatus::InProgress)
        .await
    {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::warn!(
                ?e,
                "failed to list global in_progress tasks for cross-repo stuck recovery"
            );
            vec![]
        }
    };
    for task in all_external_in_progress
        .iter()
        .filter(|t| t.origin != "internal" && t.repo != repo)
    {
        let external_id = task
            .external_id
            .clone()
            .unwrap_or_else(|| task.id.to_string());
        let Some(timing) = stuck_task_timing_from_map(
            tmux,
            &task.repo,
            &external_id,
            &task.updated_at,
            config,
            "cannot parse updated_at, skipping cross-repo stuck-task check",
            session_map,
        ) else {
            continue;
        };

        // See the comment on the in-progress loop above: a dead session with a stale
        // `updated_at` also matches the tail end of a run that just finished successfully.
        // Skip the reclaim while the runner's dispatch guard for this task is still held.
        if !timing.has_session {
            let dispatch_key = format!("{}/{external_id}", task.repo);
            if dispatching.contains_key(&dispatch_key) {
                // See the same promotion note on the internal-task loop below: this was
                // debug! (silently dropped under the default "orch=info" filter), leaving
                // every prior reclaim-race occurrence undiagnosable from logs alone.
                tracing::info!(
                    task_id = task.id,
                    repo = %task.repo,
                    dispatch_key,
                    age_mins = timing.age.num_minutes(),
                    "skipping cross-repo stuck-task reclaim: runner still actively processing this task"
                );
                continue;
            }
        }

        if timing.has_session {
            tracing::warn!(
                task_id = task.id,
                repo = %task.repo,
                age_mins = timing.age.num_minutes(),
                threshold_mins = timing.threshold / 60,
                "recovering cross-repo stuck task: timed out with active session → new"
            );
        } else {
            tracing::warn!(
                task_id = task.id,
                repo = %task.repo,
                dispatch_key = format!("{}/{external_id}", task.repo),
                age_mins = timing.age.num_minutes(),
                threshold_mins = timing.threshold / 60,
                "recovering cross-repo stuck task: no session found — reclaiming early → new"
            );
        }

        if let Err(e) = store_set_by_id(
            &Some(store),
            task.id,
            &[
                ("agent", serde_json::Value::Null),
                ("model", serde_json::Value::Null),
                ("route_attempts", serde_json::json!(0)),
            ],
        )
        .await
        {
            tracing::warn!(
                task_id = task.id,
                repo = %task.repo,
                ?e,
                "failed to clear routing fields for cross-repo stuck task — will retry next tick"
            );
            continue;
        }

        finalize_open_runs_for_recovery(
            store,
            task.id,
            if timing.has_session {
                "stuck-task recovery: cross-repo active session killed"
            } else {
                "stuck-task recovery: cross-repo no session found"
            },
        )
        .await;

        if let Err(e) = store
            .update_status(task.id, crate::store::TaskStatus::New)
            .await
        {
            tracing::warn!(
                task_id = task.id,
                repo = %task.repo,
                ?e,
                "failed to reset cross-repo stuck task status"
            );
            continue;
        }

        let details = serde_json::json!({
            "failure_reason": if timing.has_session { "stuck_with_session" } else { "stuck_no_session" },
            "age_minutes": timing.age.num_minutes(),
            "had_session": timing.has_session,
            "scope": "cross_repo_global_sweep",
        });
        crate::store::store_log_activity(
            &Some(Arc::clone(store)),
            &task.repo,
            &external_id,
            "rerouted",
            Some("in_progress"),
            Some("new"),
            None::<&str>,
            None::<&str>,
            Some(&details),
        )
        .await;
    }

    // Recover internal (SQLite) tasks stuck in in_progress.
    // These have no GitHub labels or comments — just reset the DB status to New.
    use crate::store::TaskStatus as DbStatus;
    let internal_in_progress = match task_manager
        .list_internal_by_status(DbStatus::InProgress)
        .await
    {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::warn!(
                ?e,
                "failed to list internal in_progress tasks for stuck recovery"
            );
            vec![]
        }
    };
    for task in &internal_in_progress {
        let task_id = task.id.0.clone();
        let Some(timing) = stuck_task_timing_from_map(
            tmux,
            repo,
            &task_id,
            &task.updated_at,
            config,
            "cannot parse updated_at, skipping stuck internal-task check",
            session_map,
        ) else {
            continue;
        };

        // See the comment on the external in-progress loop above: a dead session with a
        // stale `updated_at` also matches the tail end of a run that just finished
        // successfully. Skip the reclaim while the runner's dispatch guard for this task
        // is still held — this is the exact race that discards completed daily/scheduled
        // internal tasks whose total runtime exceeds `no_session_stuck_timeout`.
        if !timing.has_session {
            let dispatch_key = format!("{repo}/{task_id}");
            if dispatching.contains_key(&dispatch_key) {
                // Promoted from debug! to info! (issue #3526): the default log filter is
                // "orch=info" (main.rs), so this line — along with the DispatchGuard
                // claim/release lines in dispatch_guard.rs and dispatch_tasks_for_repo —
                // never reached orch.log in production. Every occurrence of the reclaim
                // race (#3518, #3519, #3523, #3525, #3526) had to be reasoned about from
                // timestamp correlation across unrelated log lines instead of directly
                // observing whether the guard was held, because the one log line that
                // would prove it was silently filtered out. Promoting these closes that
                // observability gap so the next occurrence carries conclusive evidence.
                tracing::info!(
                    task_id,
                    dispatch_key,
                    age_mins = timing.age.num_minutes(),
                    "skipping stuck-task reclaim: runner still actively processing this task"
                );
                continue;
            }
        }

        if timing.has_session {
            tracing::warn!(
                task_id,
                age_mins = timing.age.num_minutes(),
                threshold_mins = timing.threshold / 60,
                "recovering stuck task: timed out with active session → new"
            );
        } else {
            tracing::warn!(
                task_id,
                dispatch_key = format!("{repo}/{task_id}"),
                age_mins = timing.age.num_minutes(),
                threshold_mins = timing.threshold / 60,
                "recovering stuck task: no session found — reclaiming early → new"
            );
        }
        // Apply agent/model cooldown for internal stuck tasks with active sessions,
        // mirroring the external path (lines 501-546). Without this, the router picks
        // the same agent/model that caused the hang, creating an infinite loop.
        let mut cached_store_id: Option<i64> = None;
        if timing.has_session {
            let store_task = match store.resolve_task_id(repo, &task_id).await {
                Ok(Some(store_id)) => {
                    cached_store_id = Some(store_id);
                    match store.get(store_id).await {
                        Ok(t) => Some(t),
                        Err(e) => {
                            tracing::warn!(task_id, error = %e, "failed to fetch task from store for stuck internal-task cooldown");
                            None
                        }
                    }
                }
                Ok(None) => None,
                Err(e) => {
                    tracing::warn!(task_id, error = %e, "failed to resolve task id for stuck internal-task cooldown");
                    None
                }
            };
            let agent_name = store_task
                .as_ref()
                .and_then(|t| t.agent.clone())
                .unwrap_or_default();
            let model_name = store_task
                .as_ref()
                .and_then(|t| t.model.clone())
                .unwrap_or_default();

            if !agent_name.is_empty() && !model_name.is_empty() {
                set_model_cooldown(
                    &agent_name,
                    &model_name,
                    config.silence_cooldown,
                    "silence_detected",
                )
                .await;
                record_agent_failure_with_message(
                    &agent_name,
                    &format!(
                        "internal task stuck with active session after {}m",
                        timing.age.num_minutes()
                    ),
                )
                .await;
            }
            if !agent_name.is_empty() {
                set_agent_cooldown(&agent_name, SILENCE_AGENT_COOLDOWN_SECS).await;
            }
            tracing::warn!(
                task_id,
                agent = %agent_name,
                model = %model_name,
                cooldown_secs = config.silence_cooldown,
                "internal stuck-task cooldown applied — router will avoid this agent/model on next attempt"
            );
        }
        // Reset routing state so the LLM router is used on the next attempt
        // (same reset that external tasks perform).
        let resolved_store_id = match cached_store_id {
            Some(id) => Some(id),
            None => match store.resolve_task_id(repo, &task_id).await {
                Ok(Some(id)) => Some(id),
                Ok(None) => {
                    tracing::warn!(
                        task_id = %task_id,
                        repo,
                        "resolve_task_id returned None during stuck internal-task recovery"
                    );
                    None
                }
                Err(e) => {
                    tracing::error!(
                        task_id = %task_id,
                        repo,
                        error = %e,
                        "resolve_task_id failed during stuck internal-task recovery"
                    );
                    None
                }
            },
        };
        if let Some(store_id) = resolved_store_id {
            if let Err(e) = store_set_by_id(
                &Some(store),
                store_id,
                &[
                    ("agent", serde_json::Value::Null),
                    ("model", serde_json::Value::Null),
                    ("route_attempts", serde_json::json!(0)),
                ],
            )
            .await
            {
                tracing::warn!(
                    task_id,
                    ?e,
                    "failed to clear routing fields for stuck internal task — will retry next tick"
                );
                continue;
            }
            finalize_open_runs_for_recovery(
                store,
                store_id,
                if timing.has_session {
                    "stuck-task recovery: internal active session killed"
                } else {
                    "stuck-task recovery: internal no session found"
                },
            )
            .await;
        }
        if let Err(e) = task_manager
            .update_task_status(&ExternalId(task_id.clone()), Status::New)
            .await
        {
            tracing::warn!(task_id, ?e, "failed to reset stuck internal task status");
        }
    }

    // Recover external tasks stuck in in_review.
    // Unlike in_progress recovery, we reset to NeedsReview (not New) so the review
    // agent re-triggers without clearing the routing state.
    let in_review = match task_manager.list_external_by_status(Status::InReview).await {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::warn!(?e, "failed to list in_review tasks for stuck recovery");
            vec![]
        }
    };
    // Read the stored in_review rows once to avoid per-task DB lookups for
    // `review_session_expected`. Build a set of external_ids that have the
    // flag set so the per-task loop can check it cheaply.
    let store_in_review = match store
        .list_by_status(repo, crate::store::TaskStatus::InReview)
        .await
    {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(
                ?e,
                "failed to list store in_review tasks for review_session_expected prefetch"
            );
            vec![]
        }
    };
    let review_expected_set: std::collections::HashSet<String> = store_in_review
        .into_iter()
        .filter(|t| t.review_session_expected)
        .filter_map(|t| t.external_id)
        .collect();
    for task in &in_review {
        if !review_expected_set.contains(&task.id.0) {
            tracing::debug!(
                task_id = task.id.0,
                "in_review task is waiting on PR review, skipping stuck-session recovery"
            );
            continue;
        }

        let review_task_id = format!("{}-review", task.id.0);
        // Use in_review_no_session_stuck_timeout instead of the standard
        // no_session_stuck_timeout. Review agents exit their tmux session on
        // normal completion before delivering the result to the engine, so a
        // short no-session timeout causes a race: the stuck recovery fires,
        // resets the task to needs_review, and the completed result arriving
        // moments later is discarded as stale. A longer threshold gives the
        // result delivery enough time to complete.
        let in_review_config = crate::engine::EngineConfig {
            no_session_stuck_timeout: config.in_review_no_session_stuck_timeout,
            ..config.clone()
        };
        let Some(timing) = stuck_task_timing_from_map(
            tmux,
            repo,
            &review_task_id,
            &task.updated_at,
            &in_review_config,
            "cannot parse updated_at, skipping stuck in_review check",
            session_map,
        ) else {
            continue;
        };

        tracing::warn!(
            task_id = task.id.0,
            age_mins = timing.age.num_minutes(),
            threshold_mins = timing.threshold / 60,
            "recovering stuck in_review task: no session found — resetting to needs_review"
        );
        if let Err(e) = task_manager
            .update_task_status(&task.id, Status::NeedsReview)
            .await
        {
            tracing::warn!(
                task_id = task.id.0,
                ?e,
                "failed to reset stuck in_review task status"
            );
            continue;
        } else {
            set_review_session_expected(store, repo, &task.id.0, false).await;
        }

        // Finalize any open review run row
        if let Ok(Some(store_id)) = store.resolve_task_id(repo, &task.id.0).await {
            finalize_open_runs_for_recovery(
                store,
                store_id,
                "stuck-task recovery: in_review session killed",
            )
            .await;
        }

        // Log activity for stuck in_review recovery
        let details = serde_json::json!({
            "failure_reason": "stuck_in_review",
            "age_minutes": timing.age.num_minutes(),
            "had_session": timing.has_session,
        });
        crate::store::store_log_activity(
            &Some(Arc::clone(store)),
            repo,
            &task.id.0,
            "rerouted",
            Some("in_review"),
            Some("needs_review"),
            None::<&str>,
            None::<&str>,
            Some(&details),
        )
        .await;
        if let Err(e) = backend
            .post_comment(
                &task.id,
                &format!(
                    "[{}] recovered: stuck in_review — no session found after {}m, resetting to needs_review{}",
                    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
                    timing.age.num_minutes(),
                    crate::engine::orch_footer()
                ),
            )
            .await
        {
            tracing::warn!(
                task_id = task.id.0,
                ?e,
                "failed to post stuck in_review recovery comment"
            );
        }
    }

    // Recover internal (SQLite) tasks stuck in in_review.
    let internal_in_review = match task_manager
        .list_internal_by_status(DbStatus::InReview)
        .await
    {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::warn!(
                ?e,
                "failed to list internal in_review tasks for stuck recovery"
            );
            vec![]
        }
    };
    for task in &internal_in_review {
        let task_id = task.id.0.clone();
        if !review_expected_set.contains(&task_id) {
            tracing::debug!(
                task_id,
                "internal in_review task is waiting on PR review, skipping stuck-session recovery"
            );
            continue;
        }

        let review_task_id = format!("{}-review", task_id);
        let in_review_config = crate::engine::EngineConfig {
            no_session_stuck_timeout: config.in_review_no_session_stuck_timeout,
            ..config.clone()
        };
        let Some(timing) = stuck_task_timing_from_map(
            tmux,
            repo,
            &review_task_id,
            &task.updated_at,
            &in_review_config,
            "cannot parse updated_at, skipping stuck internal in_review check",
            session_map,
        ) else {
            continue;
        };

        tracing::warn!(
            task_id,
            age_mins = timing.age.num_minutes(),
            threshold_mins = timing.threshold / 60,
            "recovering stuck internal in_review task: no session found — resetting to needs_review"
        );
        if let Err(e) = task_manager
            .update_task_status(&ExternalId(task_id.clone()), Status::NeedsReview)
            .await
        {
            tracing::warn!(
                task_id,
                ?e,
                "failed to reset stuck internal in_review task status"
            );
        } else {
            set_review_session_expected(store, repo, &task_id, false).await;
        }

        // Finalize any open review run row
        if let Ok(Some(store_id)) = store.resolve_task_id(repo, &task_id).await {
            finalize_open_runs_for_recovery(
                store,
                store_id,
                "stuck-task recovery: internal in_review session killed",
            )
            .await;
        }
    }

    // Global sweep for CI-failure blocked tasks from inactive or removed projects.
    // auto_unblock_blocked_tasks runs inside sync_tick and is scoped to the active repo.
    // Tasks blocked for projects no longer in orch config are never processed there.
    // This sweep covers all repos so stale CI-failure blocks are eventually resolved.
    if let Err(e) = crate::engine::sync::auto_unblock_ci_failure_blocked_tasks_global(
        task_manager,
        store,
        auto_merge_in_flight,
    )
    .await
    {
        tracing::warn!(err = %e, "global CI-failure blocked sweep failed");
    }

    // Global sweep for stale NeedsReview tasks from inactive or removed projects.
    // The refire/escalation logic in sync_tick's "5d" step is scoped to the active
    // repo, so a task that reaches NeedsReview for a repo later removed from the
    // active `projects:` list never refires or escalates to Blocked. This sweep
    // covers all repos, writing directly through the store to avoid the repo-scoped
    // `TaskManager` resolution failure (same pattern as the CI-failure sweep above).
    if let Err(e) = crate::engine::sync::refire_and_escalate_stale_needs_review_global(
        task_manager,
        store,
        router,
        dispatching,
    )
    .await
    {
        tracing::warn!(err = %e, "global NeedsReview refire/escalation sweep failed");
    }

    // Global sweep for rebroadcast-blocked tasks from inactive or removed projects.
    // The escalation sweep above (`refire_and_escalate_stale_needs_review_global`) that
    // *writes* this block_reason already runs across all repos, but the only recovery
    // path (`auto_recover_rebroadcast_blocked_tasks`) is scoped to the active repo via
    // `sync_tick` — so a task escalated for a repo later removed from the active
    // `projects:` list could never recover. This sweep covers all repos (same pattern
    // as the two sweeps above).
    if let Err(e) = crate::engine::sync::auto_recover_rebroadcast_blocked_tasks_global(
        router,
        task_manager,
        store,
    )
    .await
    {
        tracing::warn!(err = %e, "global rebroadcast-blocked recovery sweep failed");
    }

    Ok(())
}

/// Phase 3a of tick: route status:new tasks to an agent and transition them to status:routed.
pub(crate) async fn tick_route_tasks(
    backend: &Arc<dyn ExternalBackend>,
    task_manager: &Arc<TaskManager>,
    router: &mut Router,
    store: &Arc<TaskStore>,
    repo: &str,
    routing_quota: &mut RoutingTickQuota,
) -> anyhow::Result<()> {
    let _span = tracing::info_span!("engine.tick.phase3a.route").entered();
    if let Err(err) = crate::engine::dependencies::apply_claim_gates(store).await {
        tracing::warn!(err = %err, "dependency claim gate failed");
    }
    if routing_quota.is_exhausted() {
        tracing::debug!("routing quota exhausted for this tick — skipping repo routing phase");
        return Ok(());
    }

    // Global GitHub 5xx circuit breaker — skip routing during sustained GitHub outages
    // to avoid routing-heavy retry storms. Tasks will remain in 'new' status and be
    // retried when the circuit closes.
    if is_github_circuit_open() {
        let remaining = github_circuit_remaining_secs();
        tracing::info!(
            remaining_secs = remaining,
            "GitHub 5xx circuit breaker open — skipping routing phase"
        );
        return Ok(());
    }
    let new_tasks = task_manager.list_routable().await?;
    let routable: Vec<&ExternalTask> = new_tasks
        .iter()
        .filter(|t| !skips_agent(&t.labels))
        .collect();

    // Pre-emptive health check: refresh degraded-agent flags once per tick,
    // not per-task (previously this ran inside route() causing N redundant
    // DB queries when routing N tasks in the same tick).
    if !routable.is_empty() {
        let start = std::time::Instant::now();
        router.refresh_health(store).await;
        tracing::debug!(
            duration_ms = start.elapsed().as_millis(),
            "router.refresh_health completed"
        );
    }

    // Limit routing to the remaining global quota for this outer engine tick.
    for task in routable.into_iter().take(routing_quota.remaining()) {
        if !routing_quota.consume_one() {
            break;
        }
        let _task_span = tracing::info_span!("engine.route", task_id = %task.id.0).entered();

        let task_start = Instant::now();
        match router.route(task, store, repo).await {
            Ok(result) => {
                tracing::debug!(task_id = %task.id.0, duration_ms = task_start.elapsed().as_millis(), "route completed");
                // Store route result in store
                if let Err(e) = router
                    .store_route_result(&task.id.0, &result, store, repo)
                    .await
                {
                    tracing::warn!(
                        task_id = task.id.0,
                        ?e,
                        "failed to store route result; skipping Routed transition"
                    );
                    continue;
                }

                if is_internal_id(&task.id.0) {
                    // Internal tasks: update DB status, skip GitHub label ops.
                    if let Err(e) = task_manager
                        .update_task_status(&task.id, Status::Routed)
                        .await
                    {
                        tracing::warn!(
                            task_id = task.id.0,
                            ?e,
                            "failed to set internal status:routed"
                        );
                        continue;
                    }
                } else {
                    // Fire-and-forget: label operations are cosmetic (routing already
                    // persisted in DB). Spawning them prevents blocking the tick loop
                    // on 6-9 sequential HTTP calls (~3-9s overhead per routed task).
                    let backend_clone = Arc::clone(backend);
                    let task_id_clone = task.id.clone();
                    let task_labels: Vec<String> = task.labels.clone();
                    let new_labels = {
                        let mut labels = vec![
                            format!("agent:{}", result.agent),
                            format!("complexity:{}", result.complexity),
                        ];
                        if let Some(ref model) = result.model {
                            labels.push(format!("model:{model}"));
                        }
                        labels
                    };
                    tokio::spawn(async move {
                        // Remove old agent/complexity/model labels
                        for label in &task_labels {
                            if label.starts_with("agent:")
                                || label.starts_with("complexity:")
                                || label.starts_with("model:")
                            {
                                if let Err(e) =
                                    backend_clone.remove_label(&task_id_clone, label).await
                                {
                                    tracing::warn!(task_id = task_id_clone.0, label, error = %e, "failed to remove stale routing label during re-route");
                                }
                            }
                        }
                        // Add new labels
                        if let Err(e) = backend_clone.set_labels(&task_id_clone, &new_labels).await
                        {
                            tracing::warn!(
                                task_id = task_id_clone.0,
                                ?e,
                                "failed to set routing labels"
                            );
                        }
                    });

                    // Transition to routed
                    if let Err(e) = task_manager
                        .update_task_status(&task.id, Status::Routed)
                        .await
                    {
                        tracing::warn!(task_id = task.id.0, ?e, "failed to set status:routed");
                        continue;
                    }
                }

                // Dual-write: upsert task + store route result in SQLite
                match store.ensure_external_task(repo, task).await {
                    Ok(store_id) => {
                        let profile_json =
                            serde_json::to_string(&result.profile).unwrap_or_default();
                        let skills_json =
                            serde_json::to_string(&result.selected_skills).unwrap_or_default();
                        if let Err(e) = store
                            .store_route(&crate::store::StoreRoute {
                                id: store_id,
                                agent: &result.agent,
                                model: result.model.as_deref(),
                                complexity: &result.complexity,
                                estimate: result.estimate,
                                reason: &result.reason,
                                profile: &profile_json,
                                skills: &skills_json,
                            })
                            .await
                        {
                            tracing::debug!(
                                task_id = task.id.0,
                                ?e,
                                "dual-write: store_route failed"
                            );
                        }
                        if let Err(e) = store
                            .update_status(store_id, crate::store::TaskStatus::Routed)
                            .await
                        {
                            tracing::debug!(
                                task_id = task.id.0,
                                ?e,
                                "dual-write: update_status failed"
                            );
                        }
                        // Sync the estimate to GitHub Projects if the router assigned one.
                        // Fire-and-forget: do NOT await inline — GraphQL mutations can take
                        // up to 30 s and would block the entire tick loop on every routed task.
                        if result.estimate > 0 {
                            let backend_clone = Arc::clone(backend);
                            let task_id = task.id.clone();
                            let estimate = result.estimate;
                            tokio::spawn(async move {
                                if let Err(e) = backend_clone
                                    .sync_estimate_to_project(&task_id, estimate)
                                    .await
                                {
                                    tracing::debug!(
                                        task_id = task_id.0,
                                        estimate,
                                        err = %e,
                                        "dual-write: estimate project sync failed"
                                    );
                                }
                            });
                        }
                    }
                    Err(e) => {
                        tracing::debug!(
                            task_id = task.id.0,
                            ?e,
                            "dual-write: ensure_external_task failed"
                        );
                    }
                }

                if let Some(ref warning) = result.warning {
                    tracing::warn!(task_id = task.id.0, warning, "routing sanity warning");
                }

                tracing::info!(
                    task_id = task.id.0,
                    agent = %result.agent,
                    complexity = %result.complexity,
                    reason = %result.reason,
                    "task routed"
                );
            }
            Err(e) => {
                if let Some(cooled) = e.downcast_ref::<AllAgentsCooledError>() {
                    tracing::error!(
                        task_id = %task.id.0,
                        scope = %cooled.scope(),
                        remaining_secs = ?cooled.remaining_secs(),
                        "ALL AGENTS COOLED — no agent available to route this task. \
                         Task stays in 'new' and will be retried on every tick. \
                         Check `orch cooldown list` to see what is blocking dispatch."
                    );
                    continue;
                }
                if let Some(waiting) = e.downcast_ref::<crate::store::WaitingOnDependency>() {
                    tracing::info!(
                        task_id = %task.id.0,
                        blockers = %waiting.blockers.join(", "),
                        "task is waiting on a dependency"
                    );
                    continue;
                }
                tracing::error!(task_id = task.id.0, ?e, "routing failed, skipping task");
            }
        }
    }
    Ok(())
}

/// Global routing sweep: route status:new tasks from inactive or removed repos.
///
/// `tick_route_tasks` is scoped to the active repo per-tick and never processes
/// tasks whose `repo` field differs from the current project. When a project is
/// removed from the orch config, its tasks accumulate in `new` indefinitely
/// because no tick ever runs for that repo. This sweep covers all repos so
/// orphaned new tasks are eventually routed.
///
/// `active_repos` must be the full set of currently-configured project repos,
/// not just the repo of the tick that called this — mirroring
/// `dispatch_routed_tasks_global` (see its doc comment for the "racing the real
/// per-repo dispatch" failure mode this guards against). `tick()` runs once per
/// active project; filtering on `t.repo != current_repo` alone (the previous
/// behavior) made every *other* active repo's new tasks look "orphaned" too and
/// routed them a tick early, through the wrong repo's tick.
pub(crate) async fn route_new_tasks_global(
    router: &mut Router,
    store: &Arc<TaskStore>,
    active_repos: &std::collections::HashSet<String>,
    routing_quota: &mut RoutingTickQuota,
) -> anyhow::Result<()> {
    use crate::store::{StoreRoute, TaskStatus};

    if routing_quota.is_exhausted() {
        tracing::debug!("routing quota exhausted for this tick — skipping global routing sweep");
        return Ok(());
    }

    let all_new = store.list_all_by_status_global(TaskStatus::New).await?;
    let orphaned: Vec<&crate::store::Task> = all_new
        .iter()
        .filter(|t| !active_repos.contains(&t.repo))
        .filter(|t| !skips_agent(&t.labels))
        .collect();

    if orphaned.is_empty() {
        return Ok(());
    }

    tracing::info!(
        count = orphaned.len(),
        "global routing sweep: found new tasks from inactive repos"
    );

    router.refresh_health(store).await;

    for task in orphaned.into_iter().take(routing_quota.remaining()) {
        if !routing_quota.consume_one() {
            break;
        }
        let ext_task = crate::engine::tasks::store_task_to_external(task);
        let task_start = Instant::now();
        match router.route(&ext_task, store, &task.repo).await {
            Ok(result) => {
                tracing::debug!(
                    task_id = %ext_task.id.0,
                    repo = %task.repo,
                    duration_ms = task_start.elapsed().as_millis(),
                    "global sweep: route completed"
                );
                let profile_json = serde_json::to_string(&result.profile).unwrap_or_default();
                let skills_json =
                    serde_json::to_string(&result.selected_skills).unwrap_or_default();
                if let Err(e) = store
                    .store_route(&StoreRoute {
                        id: task.id,
                        agent: &result.agent,
                        model: result.model.as_deref(),
                        complexity: &result.complexity,
                        estimate: result.estimate,
                        reason: &result.reason,
                        profile: &profile_json,
                        skills: &skills_json,
                    })
                    .await
                {
                    tracing::warn!(
                        task_id = %ext_task.id.0,
                        repo = %task.repo,
                        err = %e,
                        "global sweep: failed to store route result; skipping status update"
                    );
                    continue;
                }
                if let Err(e) = store.update_status(task.id, TaskStatus::Routed).await {
                    tracing::warn!(
                        task_id = %ext_task.id.0,
                        repo = %task.repo,
                        err = %e,
                        "global sweep: failed to set status:routed"
                    );
                } else {
                    tracing::info!(
                        task_id = %ext_task.id.0,
                        repo = %task.repo,
                        agent = %result.agent,
                        complexity = %result.complexity,
                        "global sweep: task routed"
                    );
                }
                if let Some(ref warning) = result.warning {
                    tracing::warn!(task_id = %ext_task.id.0, warning, "global sweep: routing sanity warning");
                }
            }
            Err(e) => {
                if let Some(cooled) = e.downcast_ref::<AllAgentsCooledError>() {
                    tracing::error!(
                        task_id = %ext_task.id.0,
                        repo = %task.repo,
                        scope = %cooled.scope(),
                        remaining_secs = ?cooled.remaining_secs(),
                        "global sweep: ALL AGENTS COOLED — task stays in 'new'"
                    );
                    continue;
                }
                if let Some(waiting) = e.downcast_ref::<crate::store::WaitingOnDependency>() {
                    tracing::info!(
                        task_id = %ext_task.id.0,
                        repo = %task.repo,
                        blockers = %waiting.blockers.join(", "),
                        "global sweep: task is waiting on a dependency"
                    );
                    continue;
                }
                tracing::error!(
                    task_id = %ext_task.id.0,
                    repo = %task.repo,
                    err = ?e,
                    "global sweep: routing failed, skipping task"
                );
            }
        }
    }

    Ok(())
}

/// Phase 3b of tick: spawn agents for all status:routed tasks up to the parallel limit.
#[derive(Debug, Clone, Copy)]
pub(crate) struct DispatchMode {
    pub(crate) is_degraded: bool,
    pub(crate) healthy_agents: usize,
    pub(crate) threshold: usize,
}

pub(crate) fn dispatch_mode_from_router(router: &Router) -> DispatchMode {
    let threshold = crate::engine::router::config::min_healthy_agents_threshold();
    let healthy_agents = router.healthy_agent_count("simple");
    let is_degraded = router.is_degraded(threshold);
    DispatchMode {
        is_degraded,
        healthy_agents,
        threshold,
    }
}

/// Phase 3b of tick: spawn agents for all status:routed tasks up to the parallel limit.
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip_all, name = "engine.tick.phase3b.dispatch")]
pub(crate) async fn tick_dispatch_tasks(
    backend: &Arc<dyn ExternalBackend>,
    tmux: &Arc<TmuxManager>,
    repo: &str,
    runner: &Arc<TaskRunner>,
    capture: &Arc<CaptureService>,
    semaphore: &Arc<Semaphore>,
    task_manager: &Arc<TaskManager>,
    weight_tx: &mpsc::Sender<WeightSignal>,
    dispatch_mode: DispatchMode,
    dispatching: &Arc<DashMap<String, String>>,
    store: &Arc<TaskStore>,
    session_map: &std::collections::HashMap<String, bool>,
) -> anyhow::Result<()> {
    // Phase 3a already drops no-agent and owner:human, this filter stays as defense in depth
    let mut routed_tasks = task_manager.list_external_by_status(Status::Routed).await?;

    // Also include internal tasks in Routed status.
    use crate::store::TaskStatus as DbStatus;
    let internal_routed = task_manager
        .list_internal_by_status(DbStatus::Routed)
        .await?;
    routed_tasks.extend(internal_routed);

    // Filter and collect owned tasks to avoid lifetime issues
    let dispatchable: Vec<ExternalTask> = routed_tasks
        .into_iter()
        .filter(|t| !skips_agent(&t.labels))
        .collect();

    dispatch_tasks_for_repo(
        backend,
        tmux,
        repo,
        runner,
        capture,
        semaphore,
        task_manager,
        weight_tx,
        dispatch_mode,
        dispatching,
        store,
        session_map,
        dispatchable,
    )
    .await
}

/// Dispatch a pre-fetched list of routed tasks for a single repo.
///
/// Shared by `tick_dispatch_tasks` (active-repo, per-tick dispatch) and
/// `dispatch_routed_tasks_global` (inactive-repo sweep) so both paths spawn
/// agents through the exact same worktree/tmux/runner logic.
#[allow(clippy::too_many_arguments)]
async fn dispatch_tasks_for_repo(
    backend: &Arc<dyn ExternalBackend>,
    tmux: &Arc<TmuxManager>,
    repo: &str,
    runner: &Arc<TaskRunner>,
    capture: &Arc<CaptureService>,
    semaphore: &Arc<Semaphore>,
    task_manager: &Arc<TaskManager>,
    weight_tx: &mpsc::Sender<WeightSignal>,
    dispatch_mode: DispatchMode,
    dispatching: &Arc<DashMap<String, String>>,
    store: &Arc<TaskStore>,
    session_map: &std::collections::HashMap<String, bool>,
    dispatchable: Vec<ExternalTask>,
) -> anyhow::Result<()> {
    if dispatchable.is_empty() {
        tracing::debug!(count = 0, "dispatchable tasks found");
        return Ok(());
    }

    tracing::info!(count = dispatchable.len(), "dispatchable tasks found");
    if dispatch_mode.is_degraded {
        tracing::warn!(
            healthy_agents = dispatch_mode.healthy_agents,
            threshold = dispatch_mode.threshold,
            "degraded mode: using sequential dispatch"
        );
    }

    let sequential_delay = if dispatch_mode.is_degraded {
        crate::engine::router::config::sequential_dispatch_delay_ms()
    } else {
        0
    };

    for (idx, task) in dispatchable.into_iter().enumerate() {
        if crate::engine::dependencies::dispatch_is_waiting(store, repo, &task.id.0).await {
            continue;
        }
        // In degraded mode, add delay between dispatches to pace the system
        if idx > 0 && dispatch_mode.is_degraded {
            let delay_ms = sequential_delay;
            tracing::debug!(
                task_id = task.id.0,
                delay_ms = delay_ms,
                "sequential dispatch: waiting before dispatch"
            );
            tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
        }
        // In-memory guard: prevents double-dispatch due to GitHub API eventual consistency.
        // After update_status(InProgress), the label removal fires a webhook that can
        // trigger an immediate tick. GitHub's search index may not yet reflect the label
        // change, so list_by_status(Routed) can still return this task. The tmux session
        // does not exist until the runner completes worktree setup (~10s later), so the
        // session_exists check alone is insufficient.
        let dispatch_key = format!("{}/{}", repo, task.id.0);
        // Atomically claim the dispatch slot.  DashMap lets us distinguish:
        //   - same task already in-flight (expected): log debug and skip.
        //   - different task holds the same key (should never happen): log warning and skip.
        // A plain DashSet::insert would return false for both cases without distinction.
        {
            use dashmap::mapref::entry::Entry;
            match dispatching.entry(dispatch_key.clone()) {
                Entry::Occupied(existing) => {
                    let existing_id = existing.get().clone();
                    drop(existing); // release shard lock before logging
                    if existing_id == task.id.0 {
                        tracing::debug!(
                            task_id = task.id.0,
                            "task already dispatching, skipping duplicate"
                        );
                    } else {
                        tracing::warn!(
                            task_id = task.id.0,
                            existing_task_id = existing_id,
                            dispatch_key,
                            "dispatch key collision: unexpected task already holds this key"
                        );
                    }
                    continue;
                }
                Entry::Vacant(slot) => {
                    slot.insert(task.id.0.clone());
                    // Promoted from debug! to info! (issue #3526): paired with the
                    // "dispatch guard released" line in dispatch_guard.rs, this is the
                    // only direct evidence of how long a dispatch guard was actually held
                    // for a given key. Both were debug!, silently dropped under the
                    // default "orch=info" filter (main.rs) — see the reclaim-skip log
                    // promotions above for the full rationale.
                    tracing::info!(task_id = task.id.0, dispatch_key, "dispatch guard claimed");
                }
            }
        }
        // RAII guard — removes dispatch_key on drop even if the spawned task panics.
        let dispatch_guard = DispatchGuard::new(dispatching.clone(), dispatch_key.clone());
        let task_id = task.id.0.clone();

        // Load routing result from store (stored during Phase 3a). Loaded before the
        // tmux/semaphore/in_progress steps so a stale cooldown can bail out cheaply.
        let route_result = match get_route_result(store, repo, &task_id).await {
            Ok(r) => Some(r),
            Err(RouteResultError::NoAgent { .. }) => {
                tracing::warn!(
                    task_id,
                    "routed task missing agent — resetting to new for re-routing (#1604)"
                );
                if let Err(e2) = task_manager.update_task_status(&task.id, Status::New).await {
                    tracing::error!(task_id, error = %e2, "failed to reset task to new");
                }
                continue; // dispatch_guard drops here, removing the key
            }
            Err(e) => {
                tracing::warn!(task_id, error = %e, "get_route_result failed — dispatching without route info");
                None
            }
        };

        // Re-check the assigned agent/model against the cooldown store: routing and
        // dispatch are decoupled by ticks, and a failure recorded after this task was
        // routed but before it dispatched would otherwise burn a full run on an
        // already-cooled agent/model. Leave the task in Routed so the next tick's
        // dispatch pass re-evaluates it — no new per-task defer state (see #3243).
        if let Some(route) = route_result.as_ref() {
            let agent_cooled = is_agent_in_cooldown(&route.agent);
            let model_cooled = route
                .model
                .as_deref()
                .is_some_and(|model| is_model_in_cooldown(&route.agent, model));
            if agent_cooled || model_cooled {
                tracing::warn!(
                    task_id,
                    agent = route.agent,
                    model = route.model.as_deref().unwrap_or(""),
                    "routed agent/model entered cooldown after routing — deferring dispatch to next tick"
                );
                continue; // dispatch_guard drops here, removing the key
            }
        }

        // Check if already running (has active session)
        let session_name = tmux.session_name(repo, &task_id);
        if tmux
            .session_blocks_dispatch_from_map(&session_name, session_map)
            .await
        {
            tracing::warn!(
                task_id,
                session_name,
                "task has existing tmux session, skipping dispatch"
            );
            continue; // dispatch_guard drops here, removing the key
        }

        // Try to acquire a slot
        let permit = match semaphore.clone().try_acquire_owned() {
            Ok(p) => p,
            Err(_) => {
                tracing::debug!("all parallel slots busy, skipping remaining tasks");
                break; // dispatch_guard drops here, removing the key
            }
        };

        // Mark in_progress BEFORE spawning to prevent double dispatch.
        let set_in_progress_result = task_manager
            .update_task_status(&task.id, Status::InProgress)
            .await;
        if let Err(e) = set_in_progress_result {
            tracing::error!(task_id, ?e, "failed to set in_progress, skipping dispatch");
            drop(permit);
            continue; // dispatch_guard drops here, removing the key
        }
        tracing::info!(task_id, "dispatching task");

        // Register session for capture
        capture
            .register_session(repo, &task_id, &session_name)
            .await;

        // Dispatch task
        let runner = runner.clone();
        let backend = backend.clone();
        let tmux = tmux.clone();
        let capture = capture.clone();
        let task_id_for_cleanup = task_id.clone();
        let task_owned = task;
        let weight_tx = weight_tx.clone();
        let repo_owned = repo.to_string();
        let task_manager_for_spawn = task_manager.clone();
        let store_for_spawn = store.clone();

        let repo_ctx = repo_owned.clone();
        tokio::spawn(REPO_CONTEXT.scope(repo_ctx, async move {
            let _dispatch_guard = dispatch_guard; // released on drop (normal or panic)
            let dispatch_start = std::time::Instant::now();
            match runner
                .run_with_context(&task_owned, &backend, &tmux, route_result.as_ref())
                .await
            {
                Ok(signal) => {
                    tracing::info!(task_id, "task runner completed");

                    let duration = dispatch_start.elapsed().as_secs_f64();

                    // Derive a display status from the weight signal.
                    // When review agent is enabled, successful tasks go through
                    // review before being marked done — UNLESS the response
                    // handler already marked the task done (no-op tasks with
                    // no PR and no commits should not enter the review cycle).
                    let enable_review = config::get("workflow.enable_review_agent")
                        .map(|v| v != "false")
                        .unwrap_or(true);
                    let display_status = match &signal {
                        WeightSignal::Success { .. } if enable_review => {
                            // Check if response handler already set done (no-op task).
                            // The task_manager.update_task_status() was already called
                            // by response_handler, so read the actual status from store.
                            let has_pr = match store_for_spawn
                                .resolve_task_id(&repo_owned, &task_id)
                                .await
                            {
                                Ok(Some(store_id)) => match store_for_spawn
                                    .get(store_id)
                                    .await
                                {
                                    Ok(t) => t.pr_number.is_some(),
                                    Err(e) => {
                                        tracing::warn!(task_id, err = %e, "store.get() failed — defaulting to needs_review");
                                        true
                                    }
                                },
                                Ok(None) => false,
                                Err(e) => {
                                    tracing::warn!(task_id, err = %e, "failed to check PR status — defaulting to needs_review");
                                    true
                                }
                            };
                            if has_pr {
                                "needs_review"
                            } else {
                                "done"
                            }
                        }
                        WeightSignal::Success { .. } => "done",
                        WeightSignal::RateLimited { .. } => "new",
                        WeightSignal::Blocked => "blocked",
                        // Rerouted: silence detection or other non-rate-limit reset already
                        // moved the task to "new". Stay in "new" — never convert to
                        // needs_review, which would trigger the no-code shortcut and falsely
                        // close the task as done without a successful agent run.
                        WeightSignal::Rerouted => "new",
                        // None means the runner guard skipped the task (e.g. tmux session
                        // already exists) or the task completed with an unrecognised status.
                        // Route to needs_review only when the review agent is enabled;
                        // otherwise mark done so the task is not permanently stuck.
                        WeightSignal::None if enable_review => "needs_review",
                        WeightSignal::None => "done",
                    };

                    // Send weight signal back to the router
                    let _ = weight_tx.send(signal).await;

                    // All tasks: if needs_review, trigger the review agent.
                    // Status updates go through task_manager so internal tasks
                    // hit SQLite while external tasks hit GitHub labels.
                    if display_status == "needs_review" {
                        // Transition to NeedsReview — emits event so the review subscriber
                        // fires with the correct duration before the review agent starts.
                        if let Err(e) = task_manager_for_spawn
                            .update_task_status_with_duration(
                                &ExternalId(task_id.clone()),
                                Status::NeedsReview,
                                Some(duration),
                            )
                            .await
                        {
                            tracing::error!(task_id, err = %e, "update_task_status(NeedsReview) failed — task may be stuck");
                        }
                        // Review agent dispatch is handled by the event-driven subscriber.
                    } else {
                        // done, blocked, or new (rate-limited): update status directly.
                        let final_status = match display_status {
                            "done" => Status::Done,
                            "blocked" => Status::Blocked,
                            _ => Status::New,
                        };
                        if let Err(e) = task_manager_for_spawn
                            .update_task_status_with_duration(
                                &ExternalId(task_id.clone()),
                                final_status,
                                Some(duration),
                            )
                            .await
                        {
                            tracing::warn!(task_id, ?e, "failed to update task status after completion");
                        }
                    }
                }
                Err(e) => {
                    tracing::error!(task_id, ?e, "task runner failed");
                    let duration = dispatch_start.elapsed().as_secs_f64();
                    if is_internal_id(&task_id) {
                        // Internal tasks have no GitHub issue to comment on.
                        if let Err(ue) = task_manager_for_spawn
                            .update_task_status_with_duration(
                                &ExternalId(task_id.clone()),
                                Status::NeedsReview,
                                Some(duration),
                            )
                            .await
                        {
                            tracing::error!(task_id, err = %ue, "update_task_status(NeedsReview) failed — task may be stuck");
                        }
                    } else {
                        // Post comment (best-effort)
                        if let Err(comment_err) = backend
                            .post_comment(
                                &ExternalId(task_id.clone()),
                                &format!(
                                    "[{}] error: task runner failed: {e}{}",
                                    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
                                    crate::engine::orch_footer()
                                ),
                            )
                            .await
                        {
                            tracing::warn!(
                                task_id,
                                ?comment_err,
                                "failed to post error comment to GitHub"
                            );
                        }
                        // Update status immediately to NeedsReview so external tasks
                        // don't remain stuck in InProgress until the no-session timeout.
                        // The notify subscriber will send the channel notification with duration.
                        if let Err(ue) = task_manager_for_spawn
                            .update_task_status_with_duration(
                                &ExternalId(task_id.clone()),
                                Status::NeedsReview,
                                Some(duration),
                            )
                            .await
                        {
                            tracing::error!(task_id, err = %ue, "update_task_status(NeedsReview) failed — task may be stuck");
                        }
                    }
                }
            }

            // Unregister session from capture
            capture.unregister_session(&repo_owned, &task_id_for_cleanup).await;

            // Release the semaphore permit
            drop(permit);
            // _dispatch_guard drops here, removing the key from the dispatching set.
        }));
    }
    Ok(())
}

fn skips_agent(labels: &[String]) -> bool {
    labels
        .iter()
        .any(|label| label == "no-agent" || label == "owner:human")
}

/// Filter routed tasks down to those belonging to a repo outside `active_repos`,
/// drop `no-agent` and `owner:human` tasks, and group the rest by repo.
///
/// Pure/side-effect-free so it can be unit tested without touching real tmux
/// sessions or spawning a runner — see `dispatch_routed_tasks_global`, which is
/// the only caller and does the actual (side-effectful) dispatch.
fn group_orphaned_routed_tasks(
    all_routed: Vec<crate::store::Task>,
    active_repos: &std::collections::HashSet<String>,
) -> std::collections::HashMap<String, Vec<crate::store::Task>> {
    let mut by_repo: std::collections::HashMap<String, Vec<crate::store::Task>> =
        std::collections::HashMap::new();
    for task in all_routed
        .into_iter()
        .filter(|t| !active_repos.contains(&t.repo))
        .filter(|t| !skips_agent(&t.labels))
    {
        by_repo.entry(task.repo.clone()).or_default().push(task);
    }
    by_repo
}

/// Global dispatch sweep: dispatch status:routed tasks from inactive or removed repos.
///
/// `tick_dispatch_tasks` is scoped to the active repo per-tick (its `task_manager`
/// only queries that repo's tasks) and never processes tasks whose `repo` field
/// differs from the current project. When a project is removed from the orch
/// config, tasks that reach `routed` for it — including ones routed by the
/// `route_new_tasks_global` sweep — have no code path left to dispatch them, so
/// they stay `routed` forever. This sweep covers all repos so orphaned routed
/// tasks are eventually dispatched.
///
/// `active_repos` must be the full set of currently-configured project repos,
/// not just the repo of the tick that called this. `tick()` runs once per
/// active project; passing only that project's own repo would make every
/// other active repo's routed tasks look "orphaned" too and dispatch them a
/// second time through this fallback path, racing the real per-repo dispatch.
///
/// `TaskRunner::resolve_project_dir` already falls back to the deterministic
/// `~/.orch/projects/<owner>/<repo>.git` bare-clone convention when a repo is
/// not listed in the active config, so dispatch works without a `ProjectEngine`.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn dispatch_routed_tasks_global(
    tmux: &Arc<TmuxManager>,
    capture: &Arc<CaptureService>,
    semaphore: &Arc<Semaphore>,
    weight_tx: &mpsc::Sender<WeightSignal>,
    dispatch_mode: DispatchMode,
    dispatching: &Arc<DashMap<String, String>>,
    store: &Arc<TaskStore>,
    session_map: &std::collections::HashMap<String, bool>,
    active_repos: &std::collections::HashSet<String>,
) -> anyhow::Result<()> {
    use crate::store::TaskStatus;

    let all_routed = store.list_all_by_status_global(TaskStatus::Routed).await?;
    let by_repo = group_orphaned_routed_tasks(all_routed, active_repos);

    if by_repo.is_empty() {
        return Ok(());
    }

    tracing::info!(
        repos = by_repo.len(),
        "global dispatch sweep: found routed tasks from inactive repos"
    );

    for (repo, tasks) in by_repo {
        let backend: Arc<dyn ExternalBackend> = match crate::backends::github::GitHubBackend::new(
            repo.clone(),
        ) {
            Ok(b) => Arc::new(b),
            Err(e) => {
                tracing::warn!(repo = %repo, err = %e, "global sweep: failed to construct backend, skipping repo");
                continue;
            }
        };
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            repo.clone(),
        ));
        let runner = Arc::new(TaskRunner::new(repo.clone()).with_store(store.clone()));
        let dispatchable: Vec<ExternalTask> = tasks
            .iter()
            .map(crate::engine::tasks::store_task_to_external)
            .collect();

        if let Err(e) = dispatch_tasks_for_repo(
            &backend,
            tmux,
            &repo,
            &runner,
            capture,
            semaphore,
            &task_manager,
            weight_tx,
            dispatch_mode,
            dispatching,
            store,
            session_map,
            dispatchable,
        )
        .await
        {
            tracing::warn!(repo = %repo, err = %e, "global sweep: dispatch failed for repo");
        }
    }

    Ok(())
}

/// Phase 4 of tick: unblock parent tasks whose sub-issues are all done.
pub(crate) async fn tick_unblock_parents(
    backend: &Arc<dyn ExternalBackend>,
    task_manager: &Arc<TaskManager>,
    store: &Arc<TaskStore>,
    repo: &str,
) -> anyhow::Result<()> {
    let blocked = task_manager.list_all_by_status(Status::Blocked).await?;

    // Pre-filter: skip tasks that are blocked for a known reason (e.g. CI failure,
    // escalation). These are not waiting on children, so there is no point making
    // a GraphQL call for them.
    let store_blocked = store
        .list_by_status(repo, crate::store::TaskStatus::Blocked)
        .await?;
    let has_block_reason: std::collections::HashSet<String> = store_blocked
        .iter()
        .filter(|t| t.block_reason.is_some())
        .filter_map(|t| t.external_id.clone())
        .collect();

    // Spawn a concurrent task for each candidate blocked task.
    // Previously these ran sequentially; get_sub_issues is a GraphQL call taking 1-3 s each,
    // and with 4 blocked tasks that was 4-12 s of sequential latency every tick.
    let handles: Vec<_> = blocked
        .into_iter()
        .filter(|task| {
            if has_block_reason.contains(&task.id.0) {
                tracing::debug!(
                    task_id = task.id.0,
                    "skipping blocked task with known block_reason"
                );
                false
            } else {
                true
            }
        })
        .map(|task| {
            let backend_clone = Arc::clone(backend);
            let task_manager_clone = Arc::clone(task_manager);
            let store_clone = Arc::clone(store);
            let repo_owned = repo.to_string();
            tokio::spawn(async move {
                let task_id = &task.id;

                let mut children: Vec<ExternalId> = Vec::new();
                let mut child_statuses: std::collections::HashMap<
                    String,
                    crate::store::TaskStatus,
                > = std::collections::HashMap::new();

                match store_clone.resolve_task_id(&repo_owned, &task_id.0).await {
                    Ok(Some(parent_store_id)) => {
                        match store_clone.list_children(&repo_owned, parent_store_id).await {
                            Ok(store_children) => {
                                for child in store_children {
                                    let Some(child_external_id) = child.external_id else {
                                        continue;
                                    };
                                    child_statuses.insert(child_external_id.clone(), child.status);
                                    children.push(ExternalId(child_external_id));
                                }
                            }
                            Err(e) => {
                                tracing::debug!(
                                    task_id = task_id.0,
                                    ?e,
                                    "failed to list store-linked children"
                                );
                            }
                        }
                    }
                    Ok(None) => {}
                    Err(e) => {
                        tracing::debug!(
                            task_id = task_id.0,
                            ?e,
                            "failed to resolve blocked task in store for child lookup"
                        );
                    }
                }

                if !is_internal_id(&task_id.0) {
                    match backend_clone.get_sub_issues(task_id).await {
                        Ok(ids) => {
                            let mut seen: std::collections::HashSet<String> =
                                children.iter().map(|child| child.0.clone()).collect();
                            for id in ids {
                                if seen.insert(id.0.clone()) {
                                    children.push(id);
                                }
                            }
                        }
                        Err(e) => {
                            tracing::debug!(task_id = task_id.0, ?e, "failed to get sub-issues");
                        }
                    }
                }

                // No children means nothing to wait on — skip (may be blocked for other reasons)
                if children.is_empty() {
                    return;
                }

                // Check if every child is done using the local store (batched) and
                // fall back to the backend only for children not present in the store.
                let mut all_done = true;
                // Build owned strings for the batch lookup (needed for &str slices below)
                let child_ext_strs: Vec<String> =
                    children.iter().map(|c| c.0.clone()).collect();
                let child_exts: Vec<&str> =
                    child_ext_strs.iter().map(|s| s.as_str()).collect();
                // Query store for statuses of any children present locally
                if let Ok(map) = store_clone
                    .get_statuses_by_external_ids(&repo_owned, &child_exts)
                    .await
                {
                    for (k, v) in map.into_iter() {
                        child_statuses.insert(k, v);
                    }
                } else {
                    tracing::debug!(
                        task_id = task_id.0,
                        "failed to batch-query store for child statuses; falling back to per-child lookups"
                    );
                }

                for child_id in &children {
                    // Check store first
                    if let Some(status) = child_statuses.get(&child_id.0) {
                        if *status != crate::store::TaskStatus::Done {
                            all_done = false;
                            break;
                        }
                        continue;
                    }

                    // Not found in store — fall back to backend check
                    match backend_clone.get_task(child_id).await {
                        Ok(child) => {
                            if !child.labels.iter().any(|l| l == Status::Done.as_label()) {
                                all_done = false;
                                break;
                            }
                        }
                        Err(e) => {
                            tracing::debug!(task_id = task_id.0, child = %child_id.0, ?e, "failed to fetch child task from backend — treating as not done");
                            all_done = false;
                            break;
                        }
                    }
                }

                if all_done {
                    tracing::info!(
                        task_id = task_id.0,
                        children = children.len(),
                        "all children done, unblocking parent"
                    );
                    if let Err(e) =
                        task_manager_clone.update_task_status(task_id, Status::New).await
                    {
                        tracing::warn!(task_id = task_id.0, ?e, "failed to unblock parent");
                    }
                }
            })
        })
        .collect();

    for handle in handles {
        if let Err(e) = handle.await {
            tracing::warn!(?e, "phase 4 sub-issue check panicked");
        }
    }
    Ok(())
}

/// Phase 5 of tick: run cron job matching and fire any due jobs.
pub(crate) async fn tick_job_scheduler(
    jobs_path: &std::path::Path,
    backend: &Arc<dyn ExternalBackend>,
    store: Option<&Arc<TaskStore>>,
    repo: &str,
    transport: Option<&Arc<crate::channels::transport::Transport>>,
) -> anyhow::Result<()> {
    jobs::tick(jobs_path, backend, store, repo, transport).await
}

/// Core tick — runs every 10s.
///
/// Delegates to named phase functions in order:
/// 1. `tick_check_session_completions` — poll tmux for finished sessions
/// 2. `tick_recover_stuck_tasks`       — reset in_progress/in_review tasks with no active session
/// 3. `tick_route_tasks`               — route status:new tasks to an agent
/// 4. `tick_dispatch_tasks`            — spawn agents for status:routed tasks
/// 5. `tick_unblock_parents`           — unblock parents whose sub-issues are all done
/// 6. `tick_job_scheduler`             — fire due cron jobs
#[allow(clippy::too_many_arguments)]
pub(crate) async fn tick(
    backend: &Arc<dyn ExternalBackend>,
    tmux: &Arc<TmuxManager>,
    repo: &str,
    runner: &Arc<TaskRunner>,
    capture: &Arc<CaptureService>,
    semaphore: &Arc<Semaphore>,
    config: &EngineConfig,
    jobs_path: &std::path::Path,
    router: &mut Router,
    task_manager: &Arc<TaskManager>,
    weight_tx: &mpsc::Sender<WeightSignal>,
    dispatching: &Arc<DashMap<String, String>>,
    store: &Arc<TaskStore>,
    transport: Option<&Arc<crate::channels::transport::Transport>>,
    active_repos: &std::collections::HashSet<String>,
    auto_merge_in_flight: &Arc<DashSet<String>>,
    routing_quota: &mut RoutingTickQuota,
) -> anyhow::Result<()> {
    let _tick_span = tracing::info_span!("engine.tick").entered();

    // Run startup cleanup once to kill stale sessions from previous runs.
    startup_cleanup(tmux).await;

    tick_check_session_completions(tmux, repo, capture, store).await?;
    tick_detect_silent_agents(tmux, repo, capture, backend, task_manager, config, store).await?;
    // Fetch session map once and share between stuck-task recovery and dispatch to avoid
    // spawning two `tmux list-panes -a` subprocesses per tick.
    let session_map = tmux.batch_session_active().await;
    tick_recover_stuck_tasks(
        backend,
        tmux,
        repo,
        task_manager,
        config,
        store,
        &session_map,
        router,
        dispatching,
        auto_merge_in_flight,
    )
    .await?;
    if let Err(err) = crate::engine::dependencies::reconcile_dependencies(
        backend.as_ref(),
        store,
        transport.map(|arc| arc.as_ref()),
    )
    .await
    {
        tracing::warn!(err = %err, "dependency reconcile failed");
    }
    tick_route_tasks(backend, task_manager, router, store, repo, routing_quota).await?;
    // Global routing sweep for tasks from inactive or removed repos.
    // tick_route_tasks is scoped to the active repo; tasks from projects no longer
    // in config are never returned by list_routable and would stay in 'new' indefinitely.
    if let Err(e) = route_new_tasks_global(router, store, active_repos, routing_quota).await {
        tracing::warn!(err = %e, "global new-task routing sweep failed");
    }
    let dispatch_mode = dispatch_mode_from_router(router);
    tick_dispatch_tasks(
        backend,
        tmux,
        repo,
        runner,
        capture,
        semaphore,
        task_manager,
        weight_tx,
        dispatch_mode,
        dispatching,
        store,
        &session_map,
    )
    .await?;
    // Global dispatch sweep for routed tasks from inactive or removed repos.
    // tick_dispatch_tasks is scoped to the active repo; tasks from projects no longer
    // in config are never returned by list_external_by_status and would stay in
    // 'routed' indefinitely (see #3413). Excludes the full active-repo set, not just
    // `repo`, so this per-project tick doesn't treat other active repos as orphaned.
    if let Err(e) = dispatch_routed_tasks_global(
        tmux,
        capture,
        semaphore,
        weight_tx,
        dispatch_mode,
        dispatching,
        store,
        &session_map,
        active_repos,
    )
    .await
    {
        tracing::warn!(err = %e, "global routed-task dispatch sweep failed");
    }
    tick_unblock_parents(backend, task_manager, store, repo).await?;
    if let Err(e) = tick_job_scheduler(jobs_path, backend, Some(store), repo, transport).await {
        tracing::error!(?e, "job scheduler tick failed");
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::{ExternalId, ExternalTask, Mention, Status};
    use crate::channels::transport::Transport;
    use crate::engine::tasks::TaskManager;
    use crate::store::TaskStore;
    use crate::tmux::{SessionGuard, TmuxManager};
    use async_trait::async_trait;
    use std::sync::{Arc, Mutex};

    #[test]
    fn skips_agent_for_human_and_no_agent_labels() {
        assert!(skips_agent(&["owner:human".to_string()]));
        assert!(skips_agent(&["no-agent".to_string()]));
        assert!(!skips_agent(&["status:new".to_string()]));
    }

    /// A router reporting one available agent with no healthy "review" model, so the
    /// global NeedsReview refire sweep inside `tick_recover_stuck_tasks` treats every
    /// review agent as cooled and skips — keeping it a no-op for tests unrelated to it.
    fn cooled_review_router_for_test() -> Router {
        Router::new_for_test(
            crate::engine::router::RouterConfig::default(),
            vec!["claude".to_string()],
        )
    }

    // ── minimal mock backend ─────────────────────────────────────────────────

    /// Configurable mock backend for tick tests.
    struct MockBackend {
        /// Tasks returned by `list_by_status(Blocked)`.
        blocked_tasks: Vec<ExternalTask>,
        /// Sub-issues map: task_id → list of child ExternalIds.
        sub_issues: std::collections::HashMap<String, Vec<ExternalId>>,
        /// Tasks returned by `get_task`. Keyed by id.0.
        tasks_by_id: std::collections::HashMap<String, ExternalTask>,
        /// Recorded `get_sub_issues` calls.
        get_sub_issues_calls: Arc<Mutex<Vec<String>>>,
        /// Recorded `update_status` calls.
        status_updates: Arc<Mutex<Vec<(String, Status)>>>,
        /// Recorded `remove_label` calls.
        removed_labels: Arc<Mutex<Vec<(String, String)>>>,
        /// Recorded `post_comment` calls.
        posted_comments: Arc<Mutex<Vec<(String, String)>>>,
    }

    impl MockBackend {
        fn new() -> Self {
            Self {
                blocked_tasks: vec![],
                sub_issues: Default::default(),
                tasks_by_id: Default::default(),
                get_sub_issues_calls: Arc::new(Mutex::new(vec![])),
                status_updates: Arc::new(Mutex::new(vec![])),
                removed_labels: Arc::new(Mutex::new(vec![])),
                posted_comments: Arc::new(Mutex::new(vec![])),
            }
        }
    }

    fn make_task(id: &str, labels: &[&str]) -> ExternalTask {
        ExternalTask {
            id: ExternalId(id.to_string()),
            title: format!("Task {id}"),
            body: "".to_string(),
            state: "open".to_string(),
            labels: labels.iter().map(|s| s.to_string()).collect(),
            author: "bot".to_string(),
            created_at: "2026-01-01T00:00:00Z".to_string(),
            updated_at: "2026-01-01T00:00:00Z".to_string(),
            url: format!("https://github.com/test/test/issues/{id}"),
        }
    }

    #[async_trait]
    impl ExternalBackend for MockBackend {
        fn name(&self) -> &str {
            "mock"
        }
        async fn create_task(
            &self,
            _title: &str,
            _body: &str,
            _labels: &[String],
        ) -> anyhow::Result<ExternalId> {
            Ok(ExternalId("new".to_string()))
        }
        async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
            self.tasks_by_id
                .get(&id.0)
                .cloned()
                .ok_or_else(|| anyhow::anyhow!("task not found: {}", id.0))
        }
        async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
            if status == Status::Blocked {
                Ok(self.blocked_tasks.clone())
            } else {
                Ok(vec![])
            }
        }
        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
            Ok(vec![])
        }
        async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
            self.posted_comments
                .lock()
                .unwrap()
                .push((_id.0.clone(), _body.to_string()));
            Ok(())
        }
        async fn set_labels(&self, _id: &ExternalId, _labels: &[String]) -> anyhow::Result<()> {
            Ok(())
        }
        async fn remove_label(&self, _id: &ExternalId, _label: &str) -> anyhow::Result<()> {
            self.removed_labels
                .lock()
                .unwrap()
                .push((_id.0.clone(), _label.to_string()));
            Ok(())
        }
        async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
            self.get_sub_issues_calls.lock().unwrap().push(id.0.clone());
            Ok(self.sub_issues.get(&id.0).cloned().unwrap_or_default())
        }
        async fn create_sub_task(
            &self,
            _parent: &ExternalId,
            _title: &str,
            _body: &str,
            _labels: &[String],
        ) -> anyhow::Result<ExternalId> {
            Ok(ExternalId("child".to_string()))
        }
        async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
            Ok(())
        }
        async fn has_open_issue_with_title(
            &self,
            _title: &str,
            _label: &str,
        ) -> anyhow::Result<bool> {
            Ok(false)
        }
        async fn health_check(&self) -> anyhow::Result<()> {
            Ok(())
        }
        async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
            Ok(false)
        }
        async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
            Ok(Some("testbot".to_string()))
        }
        async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
            Ok(vec![])
        }
        async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
            self.status_updates
                .lock()
                .unwrap()
                .push((id.0.clone(), status));
            Ok(())
        }
    }

    fn make_task_manager(backend: Arc<dyn ExternalBackend>) -> Arc<TaskManager> {
        Arc::new(TaskManager::new(backend))
    }

    // ── tick_unblock_parents ─────────────────────────────────────────────────

    #[tokio::test]
    async fn unblock_parents_unblocks_when_all_children_done() {
        let mut mock = MockBackend::new();

        // Blocked parent with two done children
        let parent = make_task("10", &["status:blocked"]);
        mock.blocked_tasks.push(parent.clone());
        mock.sub_issues.insert(
            "10".to_string(),
            vec![ExternalId("11".to_string()), ExternalId("12".to_string())],
        );
        mock.tasks_by_id
            .insert("11".to_string(), make_task("11", &["status:done"]));
        mock.tasks_by_id
            .insert("12".to_string(), make_task("12", &["status:done"]));

        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = make_task_manager(backend.clone());
        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        let updates = status_updates.lock().unwrap();
        assert_eq!(updates.len(), 1, "parent should be unblocked");
        assert_eq!(updates[0], ("10".to_string(), Status::New));
    }

    #[tokio::test]
    async fn unblock_parents_skips_when_child_not_done() {
        let mut mock = MockBackend::new();

        let parent = make_task("20", &["status:blocked"]);
        mock.blocked_tasks.push(parent.clone());
        mock.sub_issues.insert(
            "20".to_string(),
            vec![ExternalId("21".to_string()), ExternalId("22".to_string())],
        );
        // Child 21 is done, child 22 is still in_progress
        mock.tasks_by_id
            .insert("21".to_string(), make_task("21", &["status:done"]));
        mock.tasks_by_id
            .insert("22".to_string(), make_task("22", &["status:in_progress"]));

        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = make_task_manager(backend.clone());
        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        let updates = status_updates.lock().unwrap();
        assert!(
            updates.is_empty(),
            "should not unblock when a child is still running"
        );
    }

    #[tokio::test]
    async fn unblock_parents_skips_task_with_no_children() {
        let mut mock = MockBackend::new();

        // Blocked task with no sub-issues (blocked for a different reason)
        let parent = make_task("30", &["status:blocked"]);
        mock.blocked_tasks.push(parent.clone());
        // No entry in sub_issues → get_sub_issues returns []

        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = make_task_manager(backend.clone());
        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        let updates = status_updates.lock().unwrap();
        assert!(
            updates.is_empty(),
            "should not unblock tasks with no sub-issues"
        );
    }

    #[tokio::test]
    async fn unblock_parents_skips_task_with_block_reason_in_store() {
        // A blocked task that has a known block_reason in the store should never
        // trigger a get_sub_issues GraphQL call — it is not waiting on children.
        let mut mock = MockBackend::new();

        // Blocked parent in the backend list
        let parent = make_task("60", &["status:blocked"]);
        mock.blocked_tasks.push(parent.clone());
        // Give it children in the backend so that, if the skip logic is wrong,
        // the parent would get unblocked.
        mock.sub_issues
            .insert("60".to_string(), vec![ExternalId("61".to_string())]);
        mock.tasks_by_id
            .insert("61".to_string(), make_task("61", &["status:done"]));

        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = make_task_manager(backend.clone());

        // Insert the blocked task into the store with a block_reason set.
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo: "test/repo",
                ext_id: "60",
                title: "Task 60",
                body: "",
                author: "bot",
                url: "https://github.com/test/test/issues/60",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(task_id, crate::store::TaskStatus::Blocked)
            .await
            .unwrap();
        store
            .set_block_reason(task_id, Some("CI failure limit reached"))
            .await
            .unwrap();

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        let updates = status_updates.lock().unwrap();
        assert!(
            updates.is_empty(),
            "task with block_reason should be skipped — no API call, no unblock"
        );
    }

    #[tokio::test]
    async fn unblock_parents_unblocks_internal_parent_from_store_children() {
        let mock = MockBackend::new();
        let get_sub_issues_calls = mock.get_sub_issues_calls.clone();
        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "test/repo".to_string(),
        ));

        let parent_id = store
            .create_internal("test/repo", "Parent", "", "job", "daily", None)
            .await
            .unwrap();
        store
            .update_status(parent_id, crate::store::TaskStatus::Blocked)
            .await
            .unwrap();
        let child_id = store
            .create(&crate::store::NewTask {
                external_id: Some("91".to_string()),
                repo: "test/repo".to_string(),
                origin: "github".to_string(),
                title: "Child".to_string(),
                body: String::new(),
                source: String::new(),
                source_id: String::new(),
                author: String::new(),
                url: String::new(),
                labels: vec![],
                parent_id: Some(parent_id),
            })
            .await
            .unwrap();
        store
            .update_status(child_id, crate::store::TaskStatus::Done)
            .await
            .unwrap();

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        let parent = store.get(parent_id).await.unwrap();
        assert_eq!(parent.status, crate::store::TaskStatus::New);
        assert!(
            status_updates.lock().unwrap().is_empty(),
            "internal parent should be updated in store without backend mirroring"
        );
        assert!(
            get_sub_issues_calls.lock().unwrap().is_empty(),
            "internal parent should not query backend sub-issues"
        );
    }

    // ── tick_recover_stuck_tasks (InReview) ──────────────────────────────────

    /// Set `updated_at` to a far-past date for a task in an in-memory store.
    #[cfg(test)]
    async fn set_task_updated_at_past(store: &TaskStore, task_id: i64) {
        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
            .bind(task_id)
            .execute(store.pool())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn recover_stuck_tasks_resets_external_in_review_to_needs_review() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        // Insert an external task and transition it to InReview with an old updated_at
        let id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo: "owner/repo",
                ext_id: "99",
                title: "Stuck InReview",
                body: "",
                author: "",
                url: "",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InReview)
            .await
            .unwrap();
        set_review_session_expected(&store, "owner/repo", "99", true).await;
        set_task_updated_at_past(&store, id).await;

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let updates = status_updates.lock().unwrap();
        assert_eq!(updates.len(), 1, "stuck InReview task should be recovered");
        assert_eq!(updates[0].0, "99");
        assert_eq!(updates[0].1, Status::NeedsReview);
    }

    #[tokio::test]
    async fn recover_stuck_tasks_skips_recent_in_review() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600, // 10 minutes — recent task won't trigger
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        // Insert a recently-updated InReview task (updated_at = now)
        let id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo: "owner/repo",
                ext_id: "100",
                title: "Recent InReview",
                body: "",
                author: "",
                url: "",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InReview)
            .await
            .unwrap();
        // updated_at stays at now — age < 600s → should NOT be recovered

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let updates = status_updates.lock().unwrap();
        assert!(
            updates.is_empty(),
            "recent InReview task should not be recovered"
        );
    }

    #[tokio::test]
    async fn recover_stuck_tasks_resets_internal_in_review_to_needs_review() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        // Create an internal task in InReview with old updated_at
        let id = store
            .create_internal("owner/repo", "Internal InReview", "", "cron", "1", None)
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InReview)
            .await
            .unwrap();
        set_review_session_expected(&store, "owner/repo", "internal:1", true).await;
        set_task_updated_at_past(&store, id).await;

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::NeedsReview,
            "stuck internal InReview task should be reset to NeedsReview"
        );
    }

    #[tokio::test]
    async fn recover_stuck_tasks_resets_cross_repo_external_in_progress_to_new() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        // Cross-repo task should still be recovered even when current tick repo is owner/repo.
        let id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo: "owner/other",
                ext_id: "777",
                title: "Cross-repo stuck task",
                body: "",
                author: "",
                url: "",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();
        set_task_updated_at_past(&store, id).await;

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::New,
            "cross-repo stale in_progress task should be reset to New"
        );
        assert_eq!(task.route_attempts, 0, "route attempts should be cleared");
        assert!(task.agent.is_none(), "agent should be cleared");
        assert!(task.model.is_none(), "model should be cleared");

        // Cross-repo global sweep is store-only and must not call backend status updates.
        assert!(
            status_updates.lock().unwrap().is_empty(),
            "cross-repo recovery should not call backend update_status"
        );
    }

    #[tokio::test]
    async fn recover_stuck_tasks_finalizes_open_task_runs_rows() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        let id = store
            .create_internal("owner/repo", "Stuck with open run", "", "cron", "1", None)
            .await
            .unwrap();
        store
            .set_fields(
                id,
                &[
                    ("agent", serde_json::json!("claude")),
                    ("model", serde_json::json!("sonnet")),
                    ("route_attempts", serde_json::json!(1)),
                ],
            )
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();
        set_task_updated_at_past(&store, id).await;

        // Start an agent run that will be orphaned by recovery
        store
            .start_run(&crate::store::StartRun {
                task_id: id,
                attempt: 1,
                run_type: "agent",
                agent: "claude",
                model: "sonnet",
                command: "claude --model sonnet",
                prompt: "fix it",
            })
            .await
            .unwrap();

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(task.status, crate::store::TaskStatus::New);

        let runs = store.get_runs(id).await.unwrap();
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].outcome, "aborted");
        assert!(runs[0].completed_at.is_some());
        assert_eq!(
            runs[0].error,
            "stuck-task recovery: internal no session found"
        );
    }

    /// Regression test for #3518: a completed agent run must not be discarded by the
    /// stuck-task reclaim just because its tmux session has already exited.
    ///
    /// In production, sessions are created without `remain-on-exit`, so once the agent
    /// process exits tmux removes the session immediately — there is no observable
    /// "dead pane" state for `tick_check_session_completions` to catch, and the runner's
    /// own `store_touch_updated_at` only fires after its own poll notices the exit (up to
    /// its 5s poll interval) plus post-processing. For a task whose total runtime already
    /// exceeds `no_session_stuck_timeout`, the very next tick that observes the (now
    /// absent) session would otherwise reclaim it instantly — discarding a successful run.
    ///
    /// The fix: `tick_recover_stuck_tasks` skips the no-session reclaim while the task's
    /// dispatch guard (the in-memory `dispatching` map keyed by "{repo}/{task_id}",
    /// populated for the entire duration of `runner.run_with_context`) is still held —
    /// i.e. while this process is still actively running the task, regardless of tmux
    /// session state.
    #[tokio::test]
    async fn recover_stuck_tasks_skips_reclaim_while_dispatch_guard_held() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        let id = store
            .create_internal(
                "owner/repo",
                "Long-running daily job",
                "",
                "cron",
                "1",
                None,
            )
            .await
            .unwrap();
        store
            .set_fields(
                id,
                &[
                    ("agent", serde_json::json!("claude")),
                    ("model", serde_json::json!("sonnet")),
                    ("route_attempts", serde_json::json!(1)),
                ],
            )
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();
        // Simulate a task that has already run well past no_session_stuck_timeout,
        // as a legitimately long agent run would.
        set_task_updated_at_past(&store, id).await;

        // Simulate the runner still actively processing this task: its dispatch guard
        // is held even though the tmux session (empty session_map below) is already gone.
        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
        dispatching.insert(
            format!("owner/repo/internal:{id}"),
            format!("internal:{id}"),
        );

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &dispatching,
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::InProgress,
            "task should not be reclaimed while its dispatch guard is still held"
        );

        // No run should have been finalized/aborted either.
        let runs = store.get_runs(id).await.unwrap();
        assert!(runs.is_empty());

        // Once the guard is released (runner finished), the very same conditions should
        // reclaim the task as before — the fix must not disable the safety net entirely.
        dispatching.clear();
        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &dispatching,
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();
        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::New,
            "task should still be reclaimed once the dispatch guard is released"
        );
    }

    /// Concurrency regression test for issue #3526: the reclaim race recurred twice
    /// (internal:156563 in #3523, internal:156673 in #3526) *after* the #3519/#3525
    /// fix landed, in production under the real multi-threaded tokio runtime. The
    /// existing `recover_stuck_tasks_skips_reclaim_while_dispatch_guard_held` test
    /// above only exercises sequential `.await` calls on a single-threaded test
    /// runtime (`#[tokio::test]` defaults to `flavor = "current_thread"`), which can
    /// never observe genuine cross-thread races in the shared `dispatching` DashMap.
    ///
    /// This test claims the guard exactly the way `dispatch_tasks_for_repo` does
    /// (atomic `DashMap::entry` claim, `DispatchGuard` RAII release), hands it to a
    /// spawned task running on a *different* worker thread that holds it until
    /// explicitly told to release, and hammers the real `tick_recover_stuck_tasks`
    /// from the main test task hundreds of times while the guard is deterministically
    /// still held. If there were a visibility gap between `DashMap::entry().insert()`
    /// on one thread and `DashMap::contains_key()` on another, this test would catch it.
    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
    async fn recover_stuck_tasks_never_reclaims_while_guard_held_under_real_concurrency() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        let id = store
            .create_internal(
                "owner/repo",
                "Long-running daily job",
                "",
                "cron",
                "1",
                None,
            )
            .await
            .unwrap();
        store
            .set_fields(
                id,
                &[
                    ("agent", serde_json::json!("claude")),
                    ("model", serde_json::json!("sonnet")),
                    ("route_attempts", serde_json::json!(1)),
                ],
            )
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();
        set_task_updated_at_past(&store, id).await;

        let dispatch_key = format!("owner/repo/internal:{id}");
        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());

        // Claim the guard synchronously, on this task, exactly like
        // dispatch_tasks_for_repo does: the atomic entry-claim always happens before
        // tokio::spawn hands the guard to the background task. (Claiming inside the
        // spawned task itself would race the hammer loop below against tokio's own
        // scheduling of that task onto a worker thread — a test artifact, not the
        // real production ordering, which guarantees claim-before-spawn.)
        let claim_task_id = format!("internal:{id}");
        {
            use dashmap::mapref::entry::Entry;
            match dispatching.entry(dispatch_key.clone()) {
                Entry::Vacant(slot) => {
                    slot.insert(claim_task_id);
                }
                Entry::Occupied(_) => panic!("dispatch key already claimed"),
            }
        }
        let guard = DispatchGuard::new(Arc::clone(&dispatching), dispatch_key.clone());

        // Hold the guard on a spawned task — a different worker thread under the
        // multi-thread runtime — mirroring the real runner holding it across genuine
        // async work (worktree setup, agent session, response handling) inside
        // `tokio::spawn(... run_with_context ...)`. It only drops the guard once
        // explicitly told to via `release_rx`, so its lifetime is fully controlled
        // by this test rather than raced against a timer — the release-signal
        // ordering was itself a source of false positives in an earlier version of
        // this test (a `sleep`-then-drop holder can legitimately release the guard
        // in the gap between the hammer loop's last check and its next iteration,
        // which is a correct outcome, not a bug, but made the assertion flaky).
        let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
        let holder = tokio::spawn(async move {
            let _ = release_rx.await;
            drop(guard);
        });

        // Hammer the real reclaim path concurrently from the main task while the
        // guard is deterministically still held (the holder task is parked on
        // `release_rx` and cannot drop the guard until we signal it below). Each
        // iteration's `tick_recover_stuck_tasks` call may itself run on any worker
        // thread the tokio scheduler picks, independent of the thread that claimed
        // the guard — this is what actually exercises cross-thread DashMap
        // visibility, not wall-clock racing against a timer.
        const HAMMER_ITERATIONS: u32 = 300;
        for i in 0..HAMMER_ITERATIONS {
            tick_recover_stuck_tasks(
                &backend,
                &tmux,
                "owner/repo",
                &task_manager,
                &config,
                &store,
                &std::collections::HashMap::new(),
                &cooled_review_router_for_test(),
                &dispatching,
                &Arc::new(DashSet::new()),
            )
            .await
            .unwrap();

            let task = store.get(id).await.unwrap();
            assert_eq!(
                task.status,
                crate::store::TaskStatus::InProgress,
                "task must never be reclaimed while the dispatch guard is deterministically \
                 still held, even under real cross-thread concurrency (dispatch_key={dispatch_key}, \
                 iteration={i}, contains_key_now={}, map_len_now={})",
                dispatching.contains_key(&dispatch_key),
                dispatching.len(),
            );
            tokio::task::yield_now().await;
        }

        // Now release the guard and confirm the holder task actually completed.
        let _ = release_tx.send(());
        holder.await.unwrap();

        // Guard released — the safety net must still reclaim as before.
        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &dispatching,
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();
        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::New,
            "task should be reclaimed once the dispatch guard is released"
        );
    }

    #[tokio::test]
    async fn recover_stuck_tasks_skips_external_in_review_waiting_for_human_review() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        let id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo: "owner/repo",
                ext_id: "101",
                title: "Waiting For Human Review",
                body: "",
                author: "",
                url: "",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InReview)
            .await
            .unwrap();
        set_task_updated_at_past(&store, id).await;

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let updates = status_updates.lock().unwrap();
        assert!(
            updates.is_empty(),
            "InReview task waiting for human review should not be reset"
        );
    }

    #[tokio::test]
    async fn unblock_parents_no_blocked_tasks() {
        let mock = MockBackend::new(); // no blocked tasks
        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = make_task_manager(backend.clone());
        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        assert!(status_updates.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn unblock_parents_handles_multiple_blocked_tasks() {
        let mut mock = MockBackend::new();

        // Task 40: all children done → should unblock
        let t40 = make_task("40", &["status:blocked"]);
        mock.blocked_tasks.push(t40);
        mock.sub_issues
            .insert("40".to_string(), vec![ExternalId("41".to_string())]);
        mock.tasks_by_id
            .insert("41".to_string(), make_task("41", &["status:done"]));

        // Task 50: child not done → should stay blocked
        let t50 = make_task("50", &["status:blocked"]);
        mock.blocked_tasks.push(t50);
        mock.sub_issues
            .insert("50".to_string(), vec![ExternalId("51".to_string())]);
        mock.tasks_by_id
            .insert("51".to_string(), make_task("51", &["status:in_progress"]));

        let status_updates = mock.status_updates.clone();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = make_task_manager(backend.clone());
        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        tick_unblock_parents(&backend, &task_manager, &store, "test/repo")
            .await
            .unwrap();

        let updates = status_updates.lock().unwrap();
        assert_eq!(updates.len(), 1, "only one parent should be unblocked");
        assert_eq!(updates[0].0, "40", "task 40 should be unblocked");
        assert_eq!(updates[0].1, Status::New);
    }

    #[tokio::test]
    async fn detect_silent_agents_skips_backend_for_internal_tasks() {
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));
        let mock = Arc::new(MockBackend::new());
        let backend: Arc<dyn ExternalBackend> = mock.clone();
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            silence_grace_period: 0,
            ..EngineConfig::default()
        };

        let internal_id = store
            .create_internal("owner/repo", "Silent internal", "", "cron", "1", None)
            .await
            .unwrap();
        store
            .update_status(internal_id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();

        let task_id = format!("internal:{internal_id}");
        capture
            .register_session("owner/repo", &task_id, "orch-test-internal")
            .await;
        tokio::time::sleep(std::time::Duration::from_millis(1100)).await;

        tick_detect_silent_agents(
            &tmux,
            "owner/repo",
            &capture,
            &backend,
            &task_manager,
            &config,
            &store,
        )
        .await
        .unwrap();

        assert!(
            mock.removed_labels.lock().unwrap().is_empty(),
            "internal tasks should skip backend label removal"
        );
        assert!(
            mock.posted_comments.lock().unwrap().is_empty(),
            "internal tasks should skip backend comments"
        );

        let task = store.get(internal_id).await.unwrap();
        // Silence detection now uses failover: if a fallback agent is found → Routed,
        // otherwise → New (reset for re-routing when cooldowns expire). Either is
        // acceptable; the key invariant is that the task is no longer InProgress.
        assert!(
            matches!(
                task.status,
                crate::store::TaskStatus::Routed | crate::store::TaskStatus::New
            ),
            "internal task should be routed to fallback or reset to new, got {:?}",
            task.status
        );
    }

    #[tokio::test]
    async fn detect_silent_agents_finalizes_open_task_runs_rows() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            silence_grace_period: 60,
            silence_cooldown: 300,
            ..EngineConfig::default()
        };

        let internal_id = store
            .create_internal("owner/repo", "Silent with open run", "", "cron", "1", None)
            .await
            .unwrap();
        store
            .set_fields(
                internal_id,
                &[
                    ("agent", serde_json::json!("claude")),
                    ("model", serde_json::json!("sonnet")),
                ],
            )
            .await
            .unwrap();
        store
            .update_status(internal_id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();

        let task_id = format!("internal:{internal_id}");
        capture
            .register_session("owner/repo", &task_id, "orch-test-silent-run")
            .await;
        capture
            .set_buffer_state_for_test(
                "owner/repo",
                &task_id,
                false,
                false,
                chrono::Utc::now() - chrono::Duration::seconds(120),
            )
            .await;

        // Start an agent run that will be orphaned by silence detection
        store
            .start_run(&crate::store::StartRun {
                task_id: internal_id,
                attempt: 1,
                run_type: "agent",
                agent: "claude",
                model: "sonnet",
                command: "claude --model sonnet",
                prompt: "fix it",
            })
            .await
            .unwrap();

        tick_detect_silent_agents(
            &tmux,
            "owner/repo",
            &capture,
            &backend,
            &task_manager,
            &config,
            &store,
        )
        .await
        .unwrap();

        let runs = store.get_runs(internal_id).await.unwrap();
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].outcome, "aborted");
        assert!(runs[0].completed_at.is_some());
        assert_eq!(runs[0].error, "silence detection: session killed");
    }

    /// Regression test for the race between Phase 1 (tick_check_session_completions)
    /// and Phase 2 (tick_recover_stuck_tasks).
    ///
    /// Before the fix, Phase 1 killed the tmux session without touching updated_at.
    /// Phase 2 could then see status=in_progress, has_session=false, and an old
    /// updated_at, and would reset the task to New — even though the runner's
    /// wait_for_completion() poll had not yet returned.
    ///
    /// The fix: Phase 1 touches updated_at as soon as it detects the session is done.
    /// This test verifies that after the touch, Phase 2 does NOT reclaim the task.
    #[tokio::test]
    async fn phase1_session_completion_touch_prevents_phase2_reclaim() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        // Create an in-progress internal task with old updated_at.
        // Without the fix this task would be reclaimed by Phase 2 (age >> threshold,
        // no session running in the test environment).
        let id = store
            .create_internal("owner/repo", "Completed task", "", "cron", "1", None)
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();
        set_task_updated_at_past(&store, id).await;

        // Simulate Phase 1: touch updated_at when the session is detected as done.
        // In production this happens inside tick_check_session_completions.
        let task_id = format!("internal:{id}");
        store_touch_updated_at(&Some(Arc::clone(&store)), "owner/repo", &task_id).await;

        // Phase 2 runs — updated_at is fresh so the task must NOT be reclaimed.
        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::InProgress,
            "Phase 2 must not reclaim a task whose updated_at was just touched by Phase 1"
        );
    }

    #[tokio::test]
    async fn stuck_task_timing_treats_dead_session_as_missing() {
        let tmux = Arc::new(TmuxManager::new());
        let repo = "owner/repo";
        let task_id = "internal:33498";
        let session_name = tmux.session_name(repo, task_id);

        let create_result = tokio::process::Command::new("tmux")
            .args(["new-session", "-d", "-s", &session_name, "-c", "/tmp"])
            .output()
            .await;

        match create_result {
            Ok(o) if o.status.success() => {}
            _ => {
                eprintln!("Skipping test: tmux not available or failed to create test session");
                return;
            }
        }

        let _guard = SessionGuard(session_name.clone());

        let set_option_result = tokio::process::Command::new("tmux")
            .args(["set-option", "-t", &session_name, "remain-on-exit", "on"])
            .output()
            .await;
        if !matches!(set_option_result, Ok(ref o) if o.status.success()) {
            eprintln!("Skipping test: unable to set tmux remain-on-exit option");
            return;
        }

        let send_exit_result = tokio::process::Command::new("tmux")
            .args(["send-keys", "-t", &session_name, "exit", "Enter"])
            .output()
            .await;
        if !matches!(send_exit_result, Ok(ref o) if o.status.success()) {
            eprintln!("Skipping test: unable to exit tmux pane");
            return;
        }

        // Poll until pane is dead (up to 2s) — fixed sleep is unreliable under load.
        for _ in 0..20 {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            if !tmux.session_is_running(&session_name).await {
                break;
            }
        }

        // Also wait for batch_session_active to reflect the dead state.
        // session_is_running uses `list-panes -t <session>` which may settle
        // before the global `list-panes -a` snapshot used by the production code.
        // On CI under load these two tmux commands can transiently disagree.
        let mut session_map = tmux.batch_session_active().await;
        for _ in 0..20 {
            if !session_map.get(&session_name).copied().unwrap_or(false) {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            session_map = tmux.batch_session_active().await;
        }
        if session_map.get(&session_name).copied().unwrap_or(false) {
            eprintln!("Skipping test: session still alive in batch_session_active after retries (CI tmux lag)");
            return;
        }

        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };
        let updated_at = (chrono::Utc::now()
            - chrono::Duration::seconds(config.no_session_stuck_timeout as i64 + 5))
        .to_rfc3339();

        let timing = stuck_task_timing_from_map(
            &tmux,
            repo,
            task_id,
            &updated_at,
            &config,
            "parse failure",
            &session_map,
        )
        .expect("dead session should be treated as missing");

        assert!(!timing.has_session);
        assert_eq!(timing.threshold, config.no_session_stuck_timeout);
    }

    #[tokio::test]
    #[serial_test::serial(suspend_state)]
    async fn stuck_task_timing_discounts_host_suspend_gap() {
        super::super::suspend::clear_for_test();

        let tmux = Arc::new(TmuxManager::new());
        let repo = "owner/repo";
        let task_id = "internal:99001";
        let session_map = std::collections::HashMap::new();

        let config = EngineConfig {
            no_session_stuck_timeout: 1800,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        // Task was last touched 33 minutes ago (age_mins=33 matches the reported
        // false-positive), but the host was suspended for 30 of those minutes —
        // real elapsed runtime is only 3 minutes, well under the 30-minute threshold.
        let updated_at = (chrono::Utc::now() - chrono::Duration::minutes(33)).to_rfc3339();
        let suspend_gap_detected_at = chrono::Utc::now() - chrono::Duration::minutes(1);
        super::super::suspend::inject_gap_for_test(
            suspend_gap_detected_at,
            chrono::Duration::minutes(30),
        );

        let timing = stuck_task_timing_from_map(
            &tmux,
            repo,
            task_id,
            &updated_at,
            &config,
            "parse failure",
            &session_map,
        );

        assert!(
            timing.is_none(),
            "task age should be discounted below the stuck threshold once suspend time is subtracted, got {timing:?}"
        );

        super::super::suspend::clear_for_test();
    }

    #[tokio::test]
    async fn recover_stuck_tasks_reclaims_routed_task_blocked_by_stale_session() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1,
            ..EngineConfig::default()
        };

        let id = store
            .create_internal("owner/repo", "Blocked routed task", "", "cron", "1", None)
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::Routed)
            .await
            .unwrap();
        set_task_updated_at_past(&store, id).await;

        let task_id = format!("internal:{id}");
        let session_name = tmux.session_name("owner/repo", &task_id);
        let create_result = tokio::process::Command::new("tmux")
            .args([
                "new-session",
                "-d",
                "-s",
                &session_name,
                "-c",
                "/tmp",
                "sleep 60",
            ])
            .output()
            .await;

        match create_result {
            Ok(o) if o.status.success() => {}
            _ => {
                eprintln!("Skipping test: tmux not available or failed to create test session");
                return;
            }
        }

        let session_map = tmux.batch_session_active().await;
        assert_eq!(session_map.get(&session_name).copied(), Some(true));

        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &session_map,
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::New,
            "routed task blocked by a stale session should be reset for re-routing"
        );
        assert!(
            !tmux.session_exists(&session_name).await,
            "recovery should kill the stale tmux session so dispatch can proceed"
        );
    }

    // ── tick_dispatch_tasks: deadlock regression test (#1361) ──────────────

    /// Regression test for #1361: tick_dispatch_tasks previously accepted
    /// `&Arc<RwLock<Router>>` and called `router_arc.read().await` internally.
    /// The main loop already held a write lock on the same RwLock, so the read
    /// could never be acquired — guaranteed deadlock on every tick with routed
    /// tasks.
    ///
    /// The fix changed the signature to accept `&Router` directly (the caller
    /// already has the dereferenced guard), eliminating the lock re-acquisition.
    ///
    /// This test verifies the function completes within 2 seconds when the
    /// caller holds the write lock — the old code would deadlock here.
    #[tokio::test]
    async fn dispatch_does_not_deadlock_under_write_lock() {
        use crate::engine::router::Router;
        use tokio::sync::RwLock;

        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let semaphore = Arc::new(Semaphore::new(4));
        let (weight_tx, _weight_rx) = mpsc::channel(16);
        let dispatching = Arc::new(DashMap::new());
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));

        let router_config = crate::engine::router::RouterConfig::default();
        let router = Router::new(router_config);
        let router_arc = Arc::new(RwLock::new(router));

        // Simulate what the main loop does: hold a write lock, snapshot
        // dispatch mode, then call tick_dispatch_tasks without passing any
        // lock guard into async dispatch work.
        let write_guard = router_arc.write().await;
        let dispatch_mode = dispatch_mode_from_router(&write_guard);

        let result = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            tick_dispatch_tasks(
                &backend,
                &tmux,
                "owner/repo",
                &Arc::new(crate::engine::runner::TaskRunner::new(
                    "owner/repo".to_string(),
                )),
                &capture,
                &semaphore,
                &task_manager,
                &weight_tx,
                dispatch_mode,
                &dispatching,
                &store,
                &std::collections::HashMap::new(),
            ),
        )
        .await;

        assert!(
            result.is_ok(),
            "tick_dispatch_tasks deadlocked! It tried to acquire a read lock \
             on router_arc while a write lock was already held (issue #1361)"
        );
    }

    /// Regression test for #3599: a task routed to an agent/model that entered
    /// cooldown *after* routing but *before* dispatch must not be dispatched —
    /// the stale route was decided before the failure that triggered the
    /// cooldown was known. Dispatch must re-check the assigned agent/model
    /// against the same cooldown store used at routing time and, if stale,
    /// leave the task in `Routed` for the next tick to re-evaluate (no PR is
    /// spawned, no per-task defer timer is written).
    #[tokio::test]
    async fn dispatch_skips_task_whose_routed_model_entered_cooldown() {
        use crate::store::{StoreRoute, TaskStatus as DbStatus, UpsertExternal};

        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let runner = Arc::new(TaskRunner::new("owner/repo".to_string()));
        let semaphore = Arc::new(Semaphore::new(4));
        let (weight_tx, _weight_rx) = mpsc::channel(16);
        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));

        let id = store
            .upsert_external(&UpsertExternal {
                repo: "owner/repo",
                ext_id: "999",
                title: "Stale routed task",
                body: "",
                author: "user",
                url: "https://github.com/owner/repo/issues/999",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .store_route(&StoreRoute {
                id,
                agent: "minimax",
                model: Some("opus"),
                complexity: "medium",
                estimate: 0,
                reason: "test",
                profile: "{}",
                skills: "[]",
            })
            .await
            .unwrap();
        store.update_status(id, DbStatus::Routed).await.unwrap();

        // Simulate a billing/rate-limit cooldown recorded for minimax:opus after
        // this task was routed but before it dispatched.
        crate::engine::cooldown::set_model_cooldown(
            "minimax",
            "opus",
            300,
            "rate_limit_usage_window",
        )
        .await;

        let dispatch_mode = DispatchMode {
            is_degraded: false,
            healthy_agents: 1,
            threshold: 1,
        };

        tick_dispatch_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &runner,
            &capture,
            &semaphore,
            &task_manager,
            &weight_tx,
            dispatch_mode,
            &dispatching,
            &store,
            &std::collections::HashMap::new(),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            DbStatus::Routed,
            "task whose routed model is now cooled down must stay Routed, not be dispatched"
        );
        assert!(
            dispatching.is_empty(),
            "dispatch guard must be released when skipping a stale-cooldown task"
        );
    }

    #[tokio::test]
    async fn dispatch_skips_a_task_with_an_open_dependency() {
        use crate::store::{
            DepSource, NewDependency, StoreRoute, TaskStatus as DbStatus, UpsertExternal,
        };

        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let runner = Arc::new(TaskRunner::new("owner/repo".to_string()));
        let semaphore = Arc::new(Semaphore::new(4));
        let (weight_tx, _weight_rx) = mpsc::channel(16);
        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));

        let id = store
            .upsert_external(&UpsertExternal {
                repo: "owner/repo",
                ext_id: "42",
                title: "Waiting routed task",
                body: "",
                author: "user",
                url: "https://github.com/owner/repo/issues/42",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .replace_dependencies(
                id,
                &[NewDependency {
                    repo: "owner/repo".into(),
                    number: 7,
                    source: DepSource::Github,
                }],
            )
            .await
            .unwrap();
        store
            .store_route(&StoreRoute {
                id,
                agent: "claude",
                model: Some("haiku"),
                complexity: "simple",
                estimate: 0,
                reason: "test",
                profile: "{}",
                skills: "[]",
            })
            .await
            .unwrap();
        store.update_status(id, DbStatus::Routed).await.unwrap();

        let dispatch_mode = DispatchMode {
            is_degraded: false,
            healthy_agents: 1,
            threshold: 1,
        };
        tick_dispatch_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &runner,
            &capture,
            &semaphore,
            &task_manager,
            &weight_tx,
            dispatch_mode,
            &dispatching,
            &store,
            &std::collections::HashMap::new(),
        )
        .await
        .unwrap();

        let task = store.get(id).await.unwrap();
        assert_eq!(task.status, DbStatus::Waiting);
        assert!(dispatching.is_empty());
    }

    /// Regression test for the completed-session -> stuck-task reclaim race.
    ///
    /// Scenario:
    /// - Runner finishes a tmux session and will call store_touch_updated_at shortly after
    /// - Engine's tick may observe the dead session in Phase 1 and Phase 2 may run
    ///   stuck-task recovery before the runner touches the store, causing incorrect reclaim
    /// Fix: tick_check_session_completions now touches the store.updated_at when it
    /// observes a completed session, preventing reclaim. This test simulates the
    /// timing by creating a session, marking the corresponding task InProgress with
    /// an old updated_at, calling tick_check_session_completions (which should touch
    /// the store), then calling tick_recover_stuck_tasks and asserting the task
    /// remains InProgress.
    #[tokio::test]
    async fn completed_session_does_not_cause_stuck_reclaim_race() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mock = MockBackend::new();
        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
        let task_manager = Arc::new(TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let tmux = Arc::new(TmuxManager::new());
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));

        // Insert external task and set to InProgress with old updated_at
        let id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo: "owner/repo",
                ext_id: "200",
                title: "Race Task",
                body: "",
                author: "",
                url: "",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();

        // set updated_at to far past so it would normally be eligible for reclaim
        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
            .bind(id)
            .execute(store.pool())
            .await
            .unwrap();

        // Register a real tmux session for this task and then exit it so it's observed dead
        let task_id = "200";
        let session_name = tmux.session_name("owner/repo", task_id);
        let create_result = tokio::process::Command::new("tmux")
            .args(["new-session", "-d", "-s", &session_name, "-c", "/tmp"])
            .output()
            .await;
        match create_result {
            Ok(o) if o.status.success() => {}
            _ => {
                eprintln!("Skipping test: tmux not available or failed to create test session");
                return;
            }
        }
        let _guard = SessionGuard(session_name.clone());

        // Ensure remain-on-exit so the session lingers as dead long enough to be snapshot
        let _ = tokio::process::Command::new("tmux")
            .args(["set-option", "-t", &session_name, "remain-on-exit", "on"])
            .output()
            .await;
        let _ = tokio::process::Command::new("tmux")
            .args(["send-keys", "-t", &session_name, "exit", "Enter"])
            .output()
            .await;

        // Poll until pane is dead
        for _ in 0..20 {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            if !tmux.session_is_running(&session_name).await {
                break;
            }
        }

        // Register the session in capture (engine does this during dispatch)
        let task_key = task_id.to_string();
        capture
            .register_session("owner/repo", &task_key, &session_name)
            .await;

        // Call phase1 (now touches store.updated_at for completed session)
        let config = EngineConfig {
            no_session_stuck_timeout: 600,
            stuck_timeout: 1800,
            ..EngineConfig::default()
        };

        tick_check_session_completions(&tmux, "owner/repo", &capture, &store)
            .await
            .unwrap();

        // Verify phase1 actually touched updated_at. It only processes sessions
        // that appear in snapshot() (list_sessions + batch_session_active). On CI,
        // if the session was already fully removed before the snapshot runs (e.g.
        // remain-on-exit semantics differ across tmux versions), phase1 won't see
        // it and the store won't be touched. Skip in that case.
        {
            let task_state = store.get(id).await.unwrap();
            if task_state.updated_at.starts_with("2020") {
                eprintln!(
                    "Skipping test: tick_check_session_completions did not update stored \
                     updated_at — session was not in snapshot (CI tmux environment issue)"
                );
                return;
            }
        }

        // Now run phase2 — the updated_at should have been touched so no reclaim occurs
        tick_recover_stuck_tasks(
            &backend,
            &tmux,
            "owner/repo",
            &task_manager,
            &config,
            &store,
            &std::collections::HashMap::new(),
            &cooled_review_router_for_test(),
            &Arc::new(DashMap::new()),
            &Arc::new(DashSet::new()),
        )
        .await
        .unwrap();

        // Verify the task is still InProgress in the store
        let task = store.get(id).await.unwrap();
        assert_eq!(
            task.status,
            crate::store::TaskStatus::InProgress,
            "task should not be reclaimed to New"
        );
    }

    /// Regression test: a repo configured with a ".git" suffix (e.g. "owner/repo.git")
    /// must still match its own live tmux sessions in `tick_check_session_completions`.
    ///
    /// `TmuxManager::session_name` strips ".git" when creating the session, so a live
    /// session's parsed `project` field never carries it. Before the fix, this
    /// function's `repo_name` derivation skipped the `.trim_end_matches(".git")` step,
    /// so `session.project` ("repo") never equaled `repo_name` ("repo.git") and the
    /// completed-session touch/kill was silently skipped for the entire repo — leaving
    /// the coarser-grained stuck-task reclaim as the only (racy) safety net.
    #[tokio::test]
    async fn session_completion_matches_repo_configured_with_git_suffix() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let tmux = Arc::new(TmuxManager::new());
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));

        let repo = "owner/repo.git";
        let id = store
            .upsert_external(&crate::store::UpsertExternal {
                repo,
                ext_id: "201",
                title: "Git-suffix repo task",
                body: "",
                author: "",
                url: "",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .update_status(id, crate::store::TaskStatus::InProgress)
            .await
            .unwrap();
        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
            .bind(id)
            .execute(store.pool())
            .await
            .unwrap();

        // session_name strips ".git" internally — this is the real session a dispatch
        // for this repo would have created.
        let task_id = "201";
        let session_name = tmux.session_name(repo, task_id);
        let create_result = tokio::process::Command::new("tmux")
            .args(["new-session", "-d", "-s", &session_name, "-c", "/tmp"])
            .output()
            .await;
        match create_result {
            Ok(o) if o.status.success() => {}
            _ => {
                eprintln!("Skipping test: tmux not available or failed to create test session");
                return;
            }
        }
        let _guard = SessionGuard(session_name.clone());

        let _ = tokio::process::Command::new("tmux")
            .args(["set-option", "-t", &session_name, "remain-on-exit", "on"])
            .output()
            .await;
        let _ = tokio::process::Command::new("tmux")
            .args(["send-keys", "-t", &session_name, "exit", "Enter"])
            .output()
            .await;

        for _ in 0..20 {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            if !tmux.session_is_running(&session_name).await {
                break;
            }
        }

        capture.register_session(repo, task_id, &session_name).await;

        tick_check_session_completions(&tmux, repo, &capture, &store)
            .await
            .unwrap();

        let task_state = store.get(id).await.unwrap();
        if task_state.updated_at.starts_with("2020") {
            eprintln!(
                "Skipping test: tick_check_session_completions did not update stored \
                 updated_at — session was not in snapshot (CI tmux environment issue)"
            );
            return;
        }
        assert!(
            !task_state.updated_at.starts_with("2020"),
            "tick_check_session_completions must match its own repo's live sessions \
             even when the repo is configured with a \".git\" suffix"
        );
    }

    // ── tick_job_scheduler: resilience to bad project configs ────────────────

    /// A project with a duplicate job id (same id in .orch.yml AND prompts/jobs/)
    /// must not cause tick_job_scheduler to return Err — it should log an error
    /// and return Ok(()) so other projects are unaffected.
    #[tokio::test]
    async fn job_scheduler_returns_ok_on_duplicate_job_config() {
        let tmp = tempfile::tempdir().unwrap();
        let cfg = tmp.path().join(".orch.yml");
        std::fs::write(
            &cfg,
            "jobs:\n  - id: trading-scan\n    schedule: \"0 9 * * *\"\n    task:\n      title: Scan\n      body: do it\n",
        )
        .unwrap();
        let jobs_dir = tmp.path().join("prompts").join("jobs");
        std::fs::create_dir_all(&jobs_dir).unwrap();
        std::fs::write(
            jobs_dir.join("trading-scan.md"),
            "---\nid: trading-scan\nschedule: '0 9 * * *'\ntitle: Trading Scan\n---\n\nDo trading scan.\n",
        )
        .unwrap();

        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
        let result = tick_job_scheduler(&cfg, &backend, None, "test/repo", None).await;
        assert!(
            result.is_ok(),
            "duplicate job id must not propagate as Err: {result:?}"
        );
    }

    /// When one project has a duplicate job id (bad config) and a second project
    /// has a valid config, the scheduler tick for the second project must still
    /// succeed — simulating the per-project loop in the engine.
    #[tokio::test]
    async fn job_scheduler_processes_valid_project_when_other_has_duplicate() {
        // Bad project: duplicate id across .orch.yml and prompts/jobs/
        let bad_tmp = tempfile::tempdir().unwrap();
        let bad_cfg = bad_tmp.path().join(".orch.yml");
        std::fs::write(
            &bad_cfg,
            "jobs:\n  - id: dup\n    schedule: \"0 9 * * *\"\n    task:\n      title: Dup\n      body: x\n",
        )
        .unwrap();
        let bad_jobs_dir = bad_tmp.path().join("prompts").join("jobs");
        std::fs::create_dir_all(&bad_jobs_dir).unwrap();
        std::fs::write(
            bad_jobs_dir.join("dup.md"),
            "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
        )
        .unwrap();

        // Good project: valid config, no duplicate
        let good_tmp = tempfile::tempdir().unwrap();
        let good_cfg = good_tmp.path().join(".orch.yml");
        std::fs::write(
            &good_cfg,
            "jobs:\n  - id: valid-job\n    schedule: \"0 9 * * *\"\n    task:\n      title: Valid\n      body: ok\n",
        )
        .unwrap();

        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());

        let bad_result = tick_job_scheduler(&bad_cfg, &backend, None, "test/bad-repo", None).await;
        assert!(
            bad_result.is_ok(),
            "bad project must not abort scheduler: {bad_result:?}"
        );

        let good_result =
            tick_job_scheduler(&good_cfg, &backend, None, "test/good-repo", None).await;
        assert!(
            good_result.is_ok(),
            "valid project must still run after bad project: {good_result:?}"
        );
    }

    // ── route_new_tasks_global ───────────────────────────────────────────────

    /// Regression test for #3407: tasks from inactive/removed repos were stuck
    /// in `new` indefinitely because `tick_route_tasks` is repo-scoped.
    ///
    /// `route_new_tasks_global` must route tasks whose repo != current_repo
    /// and leave current-repo tasks untouched.
    #[serial_test::serial(cooldown_state)]
    #[tokio::test]
    async fn global_sweep_routes_inactive_repo_tasks() {
        use crate::engine::router::{Router, RouterConfig};
        use crate::store::{TaskStatus, UpsertExternal};

        crate::engine::cooldown::reset_global_state().await;

        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        // Active repo task — must NOT be touched by the global sweep.
        let active_id = store
            .upsert_external(&UpsertExternal {
                repo: "active/repo",
                ext_id: "1",
                title: "Active task",
                body: "",
                author: "user",
                url: "https://github.com/active/repo/issues/1",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();

        // Inactive repo task — must be routed by the global sweep.
        let inactive_id = store
            .upsert_external(&UpsertExternal {
                repo: "inactive/repo",
                ext_id: "42",
                title: "Orphaned task",
                body: "",
                author: "user",
                url: "https://github.com/inactive/repo/issues/42",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();

        assert_eq!(store.get(active_id).await.unwrap().status, TaskStatus::New);
        assert_eq!(
            store.get(inactive_id).await.unwrap().status,
            TaskStatus::New
        );

        let mut model_map: std::collections::HashMap<
            String,
            std::collections::HashMap<String, Vec<String>>,
        > = std::collections::HashMap::new();
        let mut tier = std::collections::HashMap::new();
        tier.insert("claude".to_string(), vec!["haiku".to_string()]);
        model_map.insert("medium".to_string(), tier);
        let config = RouterConfig {
            mode: "round_robin".to_string(),
            agents: vec!["claude".to_string()],
            model_map,
            ..Default::default()
        };
        let mut router = Router::new_for_test(config, vec!["claude".to_string()]);

        let active_repos: std::collections::HashSet<String> =
            ["active/repo".to_string()].into_iter().collect();
        let mut routing_quota = RoutingTickQuota::new(1);
        route_new_tasks_global(&mut router, &store, &active_repos, &mut routing_quota)
            .await
            .unwrap();

        // Active-repo task must remain new (global sweep skips it).
        assert_eq!(
            store.get(active_id).await.unwrap().status,
            TaskStatus::New,
            "global sweep must not touch tasks for the active repo"
        );

        // Inactive-repo task must now be routed.
        let after = store.get(inactive_id).await.unwrap();
        assert_eq!(
            after.status,
            TaskStatus::Routed,
            "global sweep must route tasks from inactive repos"
        );
        assert!(
            matches!(&after.agent, Some(a) if !a.is_empty()),
            "agent must be set after routing"
        );
    }

    /// Regression test for #3523: `route_new_tasks_global` previously filtered only
    /// `t.repo != current_repo`, so during repo A's tick it would route repo B's `new`
    /// tasks too — even though B is an active, non-orphaned project with its own tick
    /// scheduled later in the same pass. This is the exact "racing the real per-repo
    /// dispatch" failure mode `dispatch_routed_tasks_global` was fixed for in #3415;
    /// the route-side sweep needs the same `active_repos` scoping, not just the
    /// current tick's own repo.
    #[serial_test::serial(cooldown_state)]
    #[tokio::test]
    async fn global_sweep_does_not_touch_other_active_repo_tasks() {
        use crate::engine::router::{Router, RouterConfig};
        use crate::store::{TaskStatus, UpsertExternal};

        crate::engine::cooldown::reset_global_state().await;

        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        // Belongs to a second active repo — NOT the repo whose tick is running,
        // but still a currently-configured project, not an orphan.
        let other_active_id = store
            .upsert_external(&UpsertExternal {
                repo: "other-active/repo",
                ext_id: "7",
                title: "Other active project's task",
                body: "",
                author: "user",
                url: "https://github.com/other-active/repo/issues/7",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();

        // Genuinely orphaned repo — not in the active set at all.
        let inactive_id = store
            .upsert_external(&UpsertExternal {
                repo: "inactive/repo",
                ext_id: "42",
                title: "Orphaned task",
                body: "",
                author: "user",
                url: "https://github.com/inactive/repo/issues/42",
                labels: &[],
                origin: "github",
            })
            .await
            .unwrap();

        let mut model_map: std::collections::HashMap<
            String,
            std::collections::HashMap<String, Vec<String>>,
        > = std::collections::HashMap::new();
        let mut tier = std::collections::HashMap::new();
        tier.insert("claude".to_string(), vec!["haiku".to_string()]);
        model_map.insert("medium".to_string(), tier);
        let config = RouterConfig {
            mode: "round_robin".to_string(),
            agents: vec!["claude".to_string()],
            model_map,
            ..Default::default()
        };
        let mut router = Router::new_for_test(config, vec!["claude".to_string()]);

        // Simulate "active/repo"'s tick running the global sweep. Both
        // "active/repo" and "other-active/repo" are currently-configured
        // projects; only "inactive/repo" is orphaned.
        let active_repos: std::collections::HashSet<String> =
            ["active/repo".to_string(), "other-active/repo".to_string()]
                .into_iter()
                .collect();
        let mut routing_quota = RoutingTickQuota::new(1);
        route_new_tasks_global(&mut router, &store, &active_repos, &mut routing_quota)
            .await
            .unwrap();

        assert_eq!(
            store.get(other_active_id).await.unwrap().status,
            TaskStatus::New,
            "global sweep run from a different active repo's tick must not route \
             another active repo's new tasks — that repo's own tick will route them"
        );
        assert_eq!(
            store.get(inactive_id).await.unwrap().status,
            TaskStatus::Routed,
            "global sweep must still route tasks from genuinely orphaned repos"
        );
    }

    /// Tasks with the `no-agent` label must be skipped by the global sweep.
    #[serial_test::serial(cooldown_state)]
    #[tokio::test]
    async fn global_sweep_skips_no_agent_tasks() {
        use crate::engine::router::{Router, RouterConfig};
        use crate::store::{TaskStatus, UpsertExternal};

        crate::engine::cooldown::reset_global_state().await;

        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        let id = store
            .upsert_external(&UpsertExternal {
                repo: "inactive/repo",
                ext_id: "99",
                title: "No-agent task",
                body: "",
                author: "user",
                url: "https://github.com/inactive/repo/issues/99",
                labels: &["no-agent".to_string()],
                origin: "github",
            })
            .await
            .unwrap();

        let mut model_map: std::collections::HashMap<
            String,
            std::collections::HashMap<String, Vec<String>>,
        > = std::collections::HashMap::new();
        let mut tier = std::collections::HashMap::new();
        tier.insert("claude".to_string(), vec!["haiku".to_string()]);
        model_map.insert("medium".to_string(), tier);
        let config = RouterConfig {
            mode: "round_robin".to_string(),
            agents: vec!["claude".to_string()],
            model_map,
            ..Default::default()
        };
        let mut router = Router::new_for_test(config, vec!["claude".to_string()]);

        let active_repos: std::collections::HashSet<String> =
            ["active/repo".to_string()].into_iter().collect();
        let mut routing_quota = RoutingTickQuota::new(1);
        route_new_tasks_global(&mut router, &store, &active_repos, &mut routing_quota)
            .await
            .unwrap();

        assert_eq!(
            store.get(id).await.unwrap().status,
            TaskStatus::New,
            "no-agent tasks must not be routed"
        );
    }

    /// Regression test for #3615: the routing limit must be consumed by a
    /// shared per-engine-tick quota, not independently by every repo/global
    /// routing pass. Otherwise one slow router timeout per pass can stack into
    /// a multi-minute watchdog stall.
    #[serial_test::serial(cooldown_state)]
    #[tokio::test]
    async fn global_sweep_honors_shared_routing_quota() {
        use crate::engine::router::{Router, RouterConfig};
        use crate::store::{TaskStatus, UpsertExternal};

        crate::engine::cooldown::reset_global_state().await;

        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        for ext_id in ["1", "2"] {
            store
                .upsert_external(&UpsertExternal {
                    repo: "inactive/repo",
                    ext_id,
                    title: "Orphaned task",
                    body: "",
                    author: "user",
                    url: &format!("https://github.com/inactive/repo/issues/{ext_id}"),
                    labels: &[],
                    origin: "github",
                })
                .await
                .unwrap();
        }

        let mut model_map: std::collections::HashMap<
            String,
            std::collections::HashMap<String, Vec<String>>,
        > = std::collections::HashMap::new();
        let mut tier = std::collections::HashMap::new();
        tier.insert("claude".to_string(), vec!["haiku".to_string()]);
        model_map.insert("medium".to_string(), tier);
        let config = RouterConfig {
            mode: "round_robin".to_string(),
            agents: vec!["claude".to_string()],
            model_map,
            ..Default::default()
        };
        let mut router = Router::new_for_test(config, vec!["claude".to_string()]);

        let active_repos: std::collections::HashSet<String> =
            ["active/repo".to_string()].into_iter().collect();
        let mut routing_quota = RoutingTickQuota::new(1);
        route_new_tasks_global(&mut router, &store, &active_repos, &mut routing_quota)
            .await
            .unwrap();

        let all_tasks = store.list_all_global().await.unwrap();
        let routed = all_tasks
            .iter()
            .filter(|task| task.status == TaskStatus::Routed)
            .count();
        let still_new = all_tasks
            .iter()
            .filter(|task| task.status == TaskStatus::New)
            .count();

        assert_eq!(routed, 1, "only one task may consume the shared quota");
        assert_eq!(still_new, 1, "remaining tasks wait for the next tick");

        route_new_tasks_global(&mut router, &store, &active_repos, &mut routing_quota)
            .await
            .unwrap();
        let after_exhausted = store.list_all_global().await.unwrap();
        assert_eq!(
            after_exhausted
                .iter()
                .filter(|task| task.status == TaskStatus::Routed)
                .count(),
            1,
            "an exhausted shared quota must not reset within the same tick"
        );
    }

    // ── dispatch_routed_tasks_global ─────────────────────────────────────────
    //
    // `dispatch_routed_tasks_global` itself is deliberately not exercised
    // end-to-end here: once it finds an orphaned repo, it spawns the real
    // runner, which creates a real tmux session and touches the network.
    // The existing `dispatch_does_not_deadlock_under_write_lock` test avoids
    // this same hazard by keeping the dispatchable set empty. The selection
    // logic (which tasks belong to which repo) is pulled into the pure
    // `group_orphaned_routed_tasks` helper below so it can be tested without
    // those side effects.

    /// Regression test for #3413: tasks routed for an inactive/removed repo were
    /// stuck in `routed` indefinitely because `tick_dispatch_tasks` is repo-scoped.
    ///
    /// `group_orphaned_routed_tasks` must select tasks whose repo != the active
    /// repo, group them by repo, and leave active-repo tasks out entirely.
    #[tokio::test]
    async fn group_orphaned_routed_tasks_selects_inactive_repo_tasks() {
        use crate::store::{StoreRoute, TaskStatus, UpsertExternal};

        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        async fn make_routed(store: &TaskStore, repo: &str, ext_id: &str) -> i64 {
            let id = store
                .upsert_external(&UpsertExternal {
                    repo,
                    ext_id,
                    title: "Routed task",
                    body: "",
                    author: "user",
                    url: &format!("https://github.com/{repo}/issues/{ext_id}"),
                    labels: &[],
                    origin: "github",
                })
                .await
                .unwrap();
            store
                .store_route(&StoreRoute {
                    id,
                    agent: "claude",
                    model: Some("sonnet"),
                    complexity: "medium",
                    estimate: 0,
                    reason: "test",
                    profile: "{}",
                    skills: "[]",
                })
                .await
                .unwrap();
            store.update_status(id, TaskStatus::Routed).await.unwrap();
            id
        }

        let active_id = make_routed(&store, "active/repo", "1").await;
        let inactive_id_a = make_routed(&store, "inactive/repo", "2").await;
        let other_inactive_id = make_routed(&store, "other-inactive/repo", "3").await;
        let inactive_id_b = make_routed(&store, "inactive/repo", "4").await;

        let all_routed = store
            .list_all_by_status_global(TaskStatus::Routed)
            .await
            .unwrap();
        let active_repos: std::collections::HashSet<String> =
            ["active/repo".to_string()].into_iter().collect();
        let by_repo = group_orphaned_routed_tasks(all_routed, &active_repos);

        assert!(
            !by_repo.contains_key("active/repo"),
            "global sweep must not select tasks for the active repo"
        );
        let inactive_ids: std::collections::HashSet<i64> = by_repo
            .get("inactive/repo")
            .expect("inactive/repo must be selected")
            .iter()
            .map(|t| t.id)
            .collect();
        assert_eq!(
            inactive_ids,
            [inactive_id_a, inactive_id_b].into_iter().collect(),
            "global sweep must group all orphaned tasks for a repo together"
        );
        assert_eq!(
            by_repo
                .get("other-inactive/repo")
                .map(|tasks| tasks.iter().map(|t| t.id).collect::<Vec<_>>()),
            Some(vec![other_inactive_id])
        );

        // Sanity: the active-repo task really was created and routed, it's just
        // excluded from the selection above.
        assert_eq!(
            store.get(active_id).await.unwrap().status,
            TaskStatus::Routed
        );
    }

    /// Regression test for the PR #3413 review finding: `tick()` runs once per active
    /// project, so a single `current_repo` string is the wrong exclusion — repo B's
    /// routed tasks must not look "orphaned" during repo A's tick just because A != B.
    /// `group_orphaned_routed_tasks` must exclude every repo in the full active set.
    #[tokio::test]
    async fn group_orphaned_routed_tasks_excludes_all_active_repos_not_just_current() {
        use crate::store::{StoreRoute, TaskStatus, UpsertExternal};

        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        async fn make_routed(store: &TaskStore, repo: &str, ext_id: &str) -> i64 {
            let id = store
                .upsert_external(&UpsertExternal {
                    repo,
                    ext_id,
                    title: "Routed task",
                    body: "",
                    author: "user",
                    url: &format!("https://github.com/{repo}/issues/{ext_id}"),
                    labels: &[],
                    origin: "github",
                })
                .await
                .unwrap();
            store
                .store_route(&StoreRoute {
                    id,
                    agent: "claude",
                    model: Some("sonnet"),
                    complexity: "medium",
                    estimate: 0,
                    reason: "test",
                    profile: "{}",
                    skills: "[]",
                })
                .await
                .unwrap();
            store.update_status(id, TaskStatus::Routed).await.unwrap();
            id
        }

        let repo_a_id = make_routed(&store, "active/repo-a", "1").await;
        let repo_b_id = make_routed(&store, "active/repo-b", "2").await;
        let orphaned_id = make_routed(&store, "inactive/repo", "3").await;

        let all_routed = store
            .list_all_by_status_global(TaskStatus::Routed)
            .await
            .unwrap();
        // Simulate repo A's tick: current repo is "active/repo-a", but the full
        // active project set also includes "active/repo-b".
        let active_repos: std::collections::HashSet<String> =
            ["active/repo-a".to_string(), "active/repo-b".to_string()]
                .into_iter()
                .collect();
        let by_repo = group_orphaned_routed_tasks(all_routed, &active_repos);

        assert!(
            !by_repo.contains_key("active/repo-a"),
            "the current repo's own tasks must not be swept"
        );
        assert!(
            !by_repo.contains_key("active/repo-b"),
            "another active repo's tasks must not be swept during repo A's tick"
        );
        assert_eq!(
            by_repo
                .get("inactive/repo")
                .map(|tasks| tasks.iter().map(|t| t.id).collect::<Vec<_>>()),
            Some(vec![orphaned_id]),
            "a genuinely inactive repo's tasks must still be swept"
        );

        // Sanity: repo A and repo B tasks were really created and routed, just excluded.
        assert_eq!(
            store.get(repo_a_id).await.unwrap().status,
            TaskStatus::Routed
        );
        assert_eq!(
            store.get(repo_b_id).await.unwrap().status,
            TaskStatus::Routed
        );
    }

    /// Tasks with the `no-agent` label must be skipped by the global dispatch sweep.
    #[tokio::test]
    async fn global_dispatch_sweep_skips_no_agent_tasks() {
        use crate::store::{StoreRoute, TaskStatus, UpsertExternal};

        let store = Arc::new(TaskStore::open_memory().await.unwrap());

        let id = store
            .upsert_external(&UpsertExternal {
                repo: "inactive/repo",
                ext_id: "99",
                title: "No-agent routed task",
                body: "",
                author: "user",
                url: "https://github.com/inactive/repo/issues/99",
                labels: &["no-agent".to_string()],
                origin: "github",
            })
            .await
            .unwrap();
        store
            .store_route(&StoreRoute {
                id,
                agent: "claude",
                model: Some("sonnet"),
                complexity: "medium",
                estimate: 0,
                reason: "test",
                profile: "{}",
                skills: "[]",
            })
            .await
            .unwrap();
        store.update_status(id, TaskStatus::Routed).await.unwrap();

        // Safe to call the full sweep here: with the only orphaned task filtered
        // out by the no-agent label, `group_orphaned_routed_tasks` returns an
        // empty map and `dispatch_routed_tasks_global` returns before ever
        // constructing a backend or spawning a runner.
        let tmux = Arc::new(TmuxManager::new());
        let transport = Arc::new(Transport::new());
        let capture = Arc::new(CaptureService::new(transport));
        let semaphore = Arc::new(Semaphore::new(4));
        let (weight_tx, _weight_rx) = mpsc::channel(16);
        let dispatching = Arc::new(DashMap::new());
        let dispatch_mode = DispatchMode {
            is_degraded: false,
            healthy_agents: 1,
            threshold: 1,
        };

        let active_repos: std::collections::HashSet<String> =
            ["active/repo".to_string()].into_iter().collect();
        dispatch_routed_tasks_global(
            &tmux,
            &capture,
            &semaphore,
            &weight_tx,
            dispatch_mode,
            &dispatching,
            &store,
            &std::collections::HashMap::new(),
            &active_repos,
        )
        .await
        .unwrap();

        assert_eq!(
            store.get(id).await.unwrap().status,
            TaskStatus::Routed,
            "no-agent tasks must not be dispatched"
        );
    }
}