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
//! Engine — the core orchestration loop.
//!
//! The engine is the central coordinator. It owns the tick loop, backend
//! connections, channel registry, transport layer, and tmux session manager.
//!
//! Submodules handle the heavy lifting:
//! - [`tick`] — core tick phases (session polling, stuck recovery, routing, dispatch)
//! - [`sync`] — periodic sync operations (cleanup, PR review, mentions, skills)
//! - [`review`] — PR review pipeline (review agent, auto-merge, change handling)
//! - [`cleanup`] — worktree cleanup and merged-PR detection
//!
//! This file contains struct definitions, project initialization, and the
//! main event loop (`serve()`).
pub mod auto_merge;
pub mod channel_handler;
pub mod cleanup;
pub mod commands;
pub mod cooldown;
pub mod dispatch_guard;
pub mod events;
pub mod jobs;
pub mod review;
pub mod review_poll;
pub mod router;
pub mod runner;
pub mod subscribers;
pub mod suspend;
pub mod sync;
pub mod tasks;
pub mod tick;
/// Standard Orch attribution footer for issue bodies, PR bodies, and comments.
///
/// Append to every user-visible string posted to GitHub so activity is
/// clearly attributed to orch rather than appearing as a human post.
pub fn orch_footer() -> &'static str {
"\n\n---\n*Posted by [Orch](https://github.com/gabrielkoerich/orch)*"
}
/// Build a standard attribution footer for GitHub comments posted by orch bots.
///
/// `verb` is "Created", "Reviewed", or "Commented" depending on context.
pub fn attribution_footer(verb: &str, agent: &str, model: Option<&str>) -> String {
match model {
Some(m) => format!(
"\n\n---\n*{} by {}[bot] via [Orch](https://github.com/gabrielkoerich/orch) using `{}`*",
verb, agent, m
),
None => format!(
"\n\n---\n*{} by {}[bot] via [Orch](https://github.com/gabrielkoerich/orch)*",
verb, agent
),
}
}
use crate::backends::{ExternalBackend, ExternalId};
use crate::channels::capture::CaptureService;
use crate::channels::discord_ws::DiscordGateway;
use crate::channels::github::start_webhook_server;
use crate::channels::notification::NotificationLevel;
use crate::channels::routing::{ChannelRouter, GlobalChannelConfig, ProjectChannelConfig};
use crate::channels::slack::SlackChannel;
use crate::channels::telegram::TelegramChannel;
use crate::channels::tmux::TmuxChannel;
use crate::channels::transport::Transport;
use crate::channels::{Channel, ChannelRegistry, IncomingMessage, OutgoingMessage};
use crate::cmd::CommandErrorContext;
use crate::config;
use crate::engine::cleanup::remove_worktree_and_branch;
use crate::engine::router::{Router, RouterConfig};
use crate::engine::runner::worktree::{
abort_worktree_rebase, list_project_worktrees, rebase_worktree_on_origin_main,
task_id_from_worktree_name, validate_worktree_gitdir,
};
use crate::engine::tasks::TaskManager;
use crate::github::http::{rate_limit_metrics, GhHttp};
use crate::repo_context::REPO_CONTEXT;
use crate::store::{review_session_expected, set_review_session_expected};
use crate::store::{TaskStatus, TaskStore};
use crate::tmux::TmuxManager;
use runner::WeightSignal;
// AtomicBool/Ordering removed — shutdown is now immediate (reset tasks + break)
use std::sync::Arc;
use tokio::process::Command;
use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
use crate::backends::Status;
/// Lightweight reference tuple for channel message handling.
type EngineRef = (
String,
Arc<dyn ExternalBackend>,
Arc<TaskManager>,
Option<Arc<TaskStore>>,
);
/// Per-project engine state.
///
/// Each project has its own backend, task runner, and task manager,
/// but they share the global tmux manager, transport, and semaphore.
#[derive(Clone)]
pub struct ProjectEngine {
pub repo: String,
pub project_dir: std::path::PathBuf,
pub backend: Arc<dyn ExternalBackend>,
pub task_manager: Arc<TaskManager>,
pub runner: Arc<runner::TaskRunner>,
pub store: Arc<TaskStore>,
}
/// Return the configured agent list from top-level `agents` in config.yml,
/// falling back to [`router::config::DEFAULT_AGENTS`] when not set.
///
/// This is the canonical source of truth for "which agents does orch know
/// about" — use it instead of `DEFAULT_AGENTS` directly so that
/// Claude-compatible agents added via config (e.g. `olm`) are recognized
/// without code changes.
///
/// The key is top-level (`agents:`) rather than nested (`engine.agents:`)
/// because `config::get` serializes nested YAML arrays via `serde_norway::to_string`
/// which produces YAML block format, not JSON — breaking downstream parsing.
pub fn configured_agents() -> Vec<String> {
if let Ok(agents_str) = crate::config::get("agents") {
if !agents_str.is_empty() && agents_str != "[]" {
// config::get returns serde_norway::to_string for arrays, which is
// YAML block format ("- claude\n- codex\n..."). Parse as YAML first.
if let Ok(agents_arr) = serde_norway::from_str::<Vec<String>>(&agents_str) {
if !agents_arr.is_empty() {
return agents_arr;
}
}
// Fallback: try JSON (inline arrays) or comma-separated
if let Ok(agents_arr) = serde_json::from_str::<Vec<String>>(&agents_str) {
if !agents_arr.is_empty() {
return agents_arr;
}
}
}
}
router::config::DEFAULT_AGENTS
.iter()
.map(|s| s.to_string())
.collect()
}
/// Engine configuration.
#[derive(Clone)]
pub struct EngineConfig {
/// Main tick interval
pub tick_interval: std::time::Duration,
/// GitHub sync interval (cleanup, PR review, mentions)
pub sync_interval: std::time::Duration,
/// Webhook health check interval (seconds)
pub webhook_health_check_interval: Option<std::time::Duration>,
/// Maximum parallel task executions
pub max_parallel: usize,
/// Stuck task timeout for tasks with an active tmux session (seconds)
pub stuck_timeout: u64,
/// Stuck task timeout for tasks with no active tmux session (seconds).
/// Shorter than `stuck_timeout` because no session means the agent has already exited.
pub no_session_stuck_timeout: u64,
/// Stuck task timeout for in_review tasks with no active tmux session (seconds).
/// Longer than `no_session_stuck_timeout` because review agents exit their tmux session
/// on normal completion before the result is delivered to the engine. Using a short
/// no-session timeout for in_review tasks causes a race where a completed review result
/// arrives after the stuck recovery has already reset the task to needs_review, discarding
/// the review work.
pub in_review_no_session_stuck_timeout: u64,
/// Auto-create follow-up tasks when PR reviews request changes
pub auto_create_followup_on_changes: bool,
/// Graceful shutdown timeout — how long to wait for running agents before exiting.
pub graceful_shutdown_timeout: std::time::Duration,
/// Grace period before silence detection kicks in (seconds).
/// Allows time for agent startup, model download, API handshake.
pub silence_grace_period: u64,
/// Cooldown duration for a model detected as silent (seconds).
pub silence_cooldown: u64,
/// How often to check for a newer orch release and notify channels (seconds).
/// Set to 0 to disable. Default: 3600 (1 hour).
pub upgrade_check_interval: u64,
/// Seconds of continuous startup failure (GitHub unreachable / auth errors)
/// before the engine escalates from WARN to ERROR-level logging and sends a
/// one-time push notification to configured channels. Set to 0 to disable.
/// Default: 3600 (1 hour).
pub startup_failure_escalation_secs: u64,
}
impl Default for EngineConfig {
fn default() -> Self {
Self {
tick_interval: std::time::Duration::from_secs(10),
sync_interval: std::time::Duration::from_secs(45),
webhook_health_check_interval: Some(std::time::Duration::from_secs(60)),
max_parallel: 4,
stuck_timeout: 1800,
no_session_stuck_timeout: 600,
in_review_no_session_stuck_timeout: 1800,
auto_create_followup_on_changes: true,
graceful_shutdown_timeout: std::time::Duration::from_secs(600),
silence_grace_period: 300,
silence_cooldown: 3600,
upgrade_check_interval: 3600,
startup_failure_escalation_secs: 3600,
}
}
}
impl EngineConfig {
/// Load engine configuration from config files, falling back to defaults.
pub fn from_config() -> Self {
let mut config = Self::default();
if let Ok(val) = crate::config::get("engine.tick_interval") {
if let Ok(secs) = val.parse::<u64>() {
config.tick_interval = std::time::Duration::from_secs(secs);
} else {
tracing::warn!(key = "engine.tick_interval", value = %val, default_secs = config.tick_interval.as_secs(), "invalid value for engine.tick_interval, using default");
}
}
if let Ok(val) = crate::config::get("engine.sync_interval") {
if let Ok(secs) = val.parse::<u64>() {
config.sync_interval = std::time::Duration::from_secs(secs);
} else {
tracing::warn!(key = "engine.sync_interval", value = %val, default_secs = config.sync_interval.as_secs(), "invalid value for engine.sync_interval, using default");
}
}
if let Ok(val) = crate::config::get("engine.max_parallel") {
if let Ok(n) = val.parse::<usize>() {
config.max_parallel = n;
} else {
tracing::warn!(key = "engine.max_parallel", value = %val, default = config.max_parallel, "invalid value for engine.max_parallel, using default");
}
}
if let Ok(val) = crate::config::get("engine.stuck_timeout") {
if let Ok(secs) = val.parse::<u64>() {
config.stuck_timeout = secs;
} else {
tracing::warn!(key = "engine.stuck_timeout", value = %val, default_secs = config.stuck_timeout, "invalid value for engine.stuck_timeout, using default");
}
}
if let Ok(val) = crate::config::get("engine.no_session_stuck_timeout") {
if let Ok(secs) = val.parse::<u64>() {
config.no_session_stuck_timeout = secs;
} else {
tracing::warn!(key = "engine.no_session_stuck_timeout", value = %val, default_secs = config.no_session_stuck_timeout, "invalid value for engine.no_session_stuck_timeout, using default");
}
}
if let Ok(val) = crate::config::get("engine.in_review_no_session_stuck_timeout") {
if let Ok(secs) = val.parse::<u64>() {
config.in_review_no_session_stuck_timeout = secs;
} else {
tracing::warn!(key = "engine.in_review_no_session_stuck_timeout", value = %val, default_secs = config.in_review_no_session_stuck_timeout, "invalid value for engine.in_review_no_session_stuck_timeout, using default");
}
}
if let Ok(val) = crate::config::get("engine.webhook_health_check_interval") {
if let Ok(secs) = val.parse::<u64>() {
if secs > 0 {
config.webhook_health_check_interval =
Some(std::time::Duration::from_secs(secs));
} else {
config.webhook_health_check_interval = None;
}
} else {
tracing::warn!(key = "engine.webhook_health_check_interval", value = %val, default = ?config.webhook_health_check_interval, "invalid value for engine.webhook_health_check_interval, using default");
}
}
if let Ok(val) = crate::config::get("workflow.auto_create_followup_on_changes") {
config.auto_create_followup_on_changes = !val.eq_ignore_ascii_case("false");
}
if let Ok(val) = crate::config::get("engine.graceful_shutdown_timeout") {
if let Ok(secs) = val.parse::<u64>() {
config.graceful_shutdown_timeout = std::time::Duration::from_secs(secs);
} else {
tracing::warn!(key = "engine.graceful_shutdown_timeout", value = %val, default_secs = config.graceful_shutdown_timeout.as_secs(), "invalid value for engine.graceful_shutdown_timeout, using default");
}
}
if let Ok(val) = crate::config::get("engine.silence_grace_period") {
if let Ok(secs) = val.parse::<u64>() {
config.silence_grace_period = secs;
} else {
tracing::warn!(key = "engine.silence_grace_period", value = %val, default = config.silence_grace_period, "invalid value for engine.silence_grace_period, using default");
}
}
if let Ok(val) = crate::config::get("engine.silence_cooldown") {
if let Ok(secs) = val.parse::<u64>() {
config.silence_cooldown = secs;
} else {
tracing::warn!(key = "engine.silence_cooldown", value = %val, default = config.silence_cooldown, "invalid value for engine.silence_cooldown, using default");
}
}
if let Ok(val) = crate::config::get("engine.upgrade_check_interval") {
if let Ok(secs) = val.parse::<u64>() {
config.upgrade_check_interval = secs;
} else {
tracing::warn!(key = "engine.upgrade_check_interval", value = %val, default = config.upgrade_check_interval, "invalid value for engine.upgrade_check_interval, using default");
}
}
if let Ok(val) = crate::config::get("engine.startup_failure_escalation_secs") {
if let Ok(secs) = val.parse::<u64>() {
config.startup_failure_escalation_secs = secs;
} else {
tracing::warn!(
key = "engine.startup_failure_escalation_secs",
value = %val,
default_secs = config.startup_failure_escalation_secs,
"invalid value for engine.startup_failure_escalation_secs, using default"
);
}
}
config
}
}
fn should_run_upgrade_check(
last_upgrade_check: Option<std::time::Instant>,
upgrade_check_interval: u64,
) -> bool {
if upgrade_check_interval == 0 {
return false;
}
last_upgrade_check
.map(|last| last.elapsed() >= std::time::Duration::from_secs(upgrade_check_interval))
.unwrap_or(true)
}
/// Initialize all project engines from config.
///
/// Returns a vector of ProjectEngine, one for each configured project.
async fn init_project_engines() -> anyhow::Result<Vec<ProjectEngine>> {
let projects = config::get_projects_with_paths()?;
let repos: Vec<&str> = projects.iter().map(|(r, _)| r.as_str()).collect();
tracing::info!(repos = ?repos, "loading projects from config");
if projects.is_empty() {
let config_path = crate::home::config_path()
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "~/.orch/config.yml".to_string());
anyhow::bail!(
"no projects configured — add repos under `projects:` in {}",
config_path
);
}
let mut engines = Vec::new();
let mut auth_failures = 0usize;
let mut network_failures = 0usize;
// Initialize unified task store once — all project engines share the same SQLite file.
// Creating one pool here avoids N separate connection pools for the same database.
let store = Arc::new(TaskStore::open(&crate::store::default_db_path().await?).await?);
// Load persisted model cooldowns and register store for future writes.
// Runs once here so the global cooldown store is not overwritten per project.
crate::engine::cooldown::init_cooldown_store(store.clone()).await;
for (repo, project_dir) in projects {
tracing::info!(repo = %repo, "initializing project engine");
// Initialize backend
let backend: Arc<dyn ExternalBackend> =
Arc::new(crate::backends::github::GitHubBackend::new(repo.clone())?);
// Health check — verifies network and GitHub authentication
if let Err(e) = backend.health_check().await {
let err_str = e.to_string();
if err_str.contains("401")
|| err_str.contains("Bad credentials")
|| err_str.contains("authentication")
|| err_str.contains("No GitHub token")
{
auth_failures += 1;
tracing::debug!(
repo = %repo,
error = %e,
"GitHub auth failed for {repo} — run `gh auth login`"
);
} else {
network_failures += 1;
tracing::debug!(
repo = %repo,
error = %e,
"GitHub unreachable for {repo} (network unavailable?)"
);
}
continue;
}
tracing::info!(repo = %repo, backend = backend.name(), "backend connected");
// Initialize task manager (with unified store)
let task_manager = Arc::new(TaskManager::with_store(
backend.clone(),
store.clone(),
repo.clone(),
));
// Task runner (with store for metrics)
let runner = Arc::new(runner::TaskRunner::new(repo.clone()).with_store(store.clone()));
engines.push(ProjectEngine {
repo,
project_dir,
backend,
task_manager,
runner,
store: store.clone(),
});
}
if engines.is_empty() {
// Projects are configured but all health checks failed — this is a connectivity
// or auth issue, not a configuration problem. The serve() retry loop will catch
// this error and retry with backoff; it must NOT propagate to main() or it would
// write "Error: ..." to brew's stderr (orch.error.log) on every restart attempt.
if auth_failures > 0 && network_failures == 0 {
anyhow::bail!(
"GitHub auth failed for all configured projects ({auth_failures} project(s)) — run `gh auth login`"
);
} else if network_failures > 0 && auth_failures == 0 {
anyhow::bail!(
"GitHub unreachable for all configured projects ({network_failures} project(s)) — check network connectivity"
);
} else {
anyhow::bail!(
"all configured project backends failed health checks ({auth_failures} auth failures, {network_failures} network failures)"
);
}
}
Ok(engines)
}
async fn reconcile_startup_worktrees(project_engines: &[ProjectEngine]) -> anyhow::Result<()> {
for engine in project_engines {
let repo_root =
crate::engine::runner::worktree::resolve_main_repo(&engine.project_dir).await;
let repo_root_path = std::path::PathBuf::from(&repo_root);
let default_branch =
crate::engine::runner::worktree::detect_default_branch(&repo_root_path).await;
let worktrees = list_project_worktrees(&repo_root_path).await?;
// Fetch refs once for all worktrees in this project, so rebase below
// operates on up-to-date origin/* refs without N sequential fetches.
if let Err(e) = Command::new("git")
.args(["-C", &repo_root.to_string_lossy(), "fetch", "origin"])
.output_with_context()
.await
{
tracing::warn!(repo = %engine.repo, err = %e, "startup git fetch origin failed, rebases may use stale refs");
}
let mut orphans_removed: u32 = 0;
let mut invalid_removed: u32 = 0;
let mut cleaned: u32 = 0;
let mut valid_kept: u32 = 0;
for worktree_dir in worktrees {
let Some(name) = worktree_dir.file_name().and_then(|n| n.to_str()) else {
continue;
};
// Validate gitdir link before doing anything else — a broken .git file
// means git commands on this worktree will fail with "not a git repository".
if !validate_worktree_gitdir(&worktree_dir).await {
tracing::warn!(repo = %engine.repo, worktree = %worktree_dir.display(), "worktree has invalid or missing gitdir, removing");
remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
.await;
invalid_removed += 1;
continue;
}
let Some(task_id) = task_id_from_worktree_name(name) else {
tracing::info!(repo = %engine.repo, worktree = %worktree_dir.display(), "orphan worktree without task id, removing");
remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
.await;
orphans_removed += 1;
continue;
};
let Some(store_id) = engine.store.resolve_task_id(&engine.repo, &task_id).await? else {
tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "worktree has no matching task, removing");
remove_worktree_and_branch(
&task_id,
&worktree_dir,
Some(name),
&repo_root_path,
false,
)
.await;
orphans_removed += 1;
continue;
};
let task = engine.store.get(store_id).await?;
let branch_name = if task.branch.is_empty() {
name
} else {
task.branch.as_str()
};
match task.status {
TaskStatus::New
| TaskStatus::Routed
| TaskStatus::InProgress
| TaskStatus::NeedsReview
| TaskStatus::InReview => {
tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "rebasing startup worktree");
if let Err(e) =
rebase_worktree_on_origin_main(&worktree_dir, &default_branch).await
{
// If rebase failed we already made efforts to stash and
// restore changes safely. Log the error and reset the
// task as before. The worktree removal path is used
// to avoid leaving corrupted worktrees around.
tracing::warn!(repo = %engine.repo, task_id = %task_id, err = %e, "startup rebase failed, resetting task");
abort_worktree_rebase(&worktree_dir).await;
let keep_remote = task.pr_number.is_some();
remove_worktree_and_branch(
&task_id,
&worktree_dir,
Some(branch_name),
&repo_root_path,
keep_remote,
)
.await;
match engine.store.resolve_task_id(&engine.repo, &task_id).await {
Ok(Some(reset_id)) => {
if let Err(e) = engine.store.reset_to_new(reset_id).await {
tracing::warn!(task_id, err = %e, "failed to reset task to new after rebase failure");
}
}
Ok(None) => {
tracing::warn!(
task_id,
"task not found in store during reconciliation"
);
}
Err(e) => {
tracing::warn!(task_id, err = %e, "failed to resolve task ID during reconciliation");
}
}
if let Err(e) = engine
.task_manager
.update_task_status(
&ExternalId(task_id.clone()),
crate::backends::Status::New,
)
.await
{
tracing::warn!(task_id, err = %e, "failed to update backend status during reconciliation");
}
cleaned += 1;
} else {
valid_kept += 1;
}
}
_ => {
let keep_remote =
task.status == TaskStatus::Blocked && task.pr_number.is_some();
tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), status = ?task.status, "terminal task worktree, removing");
remove_worktree_and_branch(
&task_id,
&worktree_dir,
Some(branch_name),
&repo_root_path,
keep_remote,
)
.await;
cleaned += 1;
}
}
}
tracing::info!(
repo = %engine.repo,
orphans_removed,
invalid_removed,
cleaned,
valid_kept,
"worktree reconciliation: {orphans_removed} orphans removed, {invalid_removed} invalid removed, {cleaned} cleaned, {valid_kept} valid kept"
);
// Prune stale .git/worktrees/ entries whose directories no longer exist.
// This handles entries left behind by crashes or manual directory removal.
let prune = Command::new("git")
.args(["-C", &repo_root.to_string_lossy(), "worktree", "prune"])
.output_with_context()
.await;
match prune {
Ok(output) if output.status.success() => {
tracing::debug!(repo = %engine.repo, "startup worktree prune completed");
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::warn!(repo = %engine.repo, err = %stderr, "startup worktree prune failed");
}
Err(e) => {
tracing::warn!(repo = %engine.repo, err = %e, "startup worktree prune failed");
}
}
}
Ok(())
}
/// Sync Fibonacci estimates stored in SQLite to the GitHub Projects board for
/// all tasks that have a positive estimate.
///
/// Runs once on startup to catch tasks that were routed before the estimate
/// sync feature was available or before `project_estimate_field_id` was
/// configured. The underlying mutations are idempotent, so re-syncing an
/// already-correct estimate is harmless.
async fn reconcile_startup_estimates(project_engines: &[ProjectEngine]) {
use crate::backends::ExternalId;
for engine in project_engines {
let tasks = match engine.store.list_external_tasks_with_estimates().await {
Ok(t) => t,
Err(e) => {
tracing::warn!(repo = %engine.repo, err = %e, "startup estimate reconciliation: store query failed");
continue;
}
};
if tasks.is_empty() {
continue;
}
let mut synced: u32 = 0;
let mut failed: u32 = 0;
for (external_id, estimate) in &tasks {
match engine
.backend
.sync_estimate_to_project(&ExternalId(external_id.clone()), *estimate)
.await
{
Ok(()) => synced += 1,
Err(e) => {
tracing::debug!(
repo = %engine.repo,
task_id = %external_id,
estimate,
err = %e,
"startup estimate reconciliation: sync failed"
);
failed += 1;
}
}
}
if synced > 0 || failed > 0 {
tracing::info!(
repo = %engine.repo,
synced,
failed,
"startup estimate reconciliation complete"
);
}
}
}
/// Read per-project channel configuration from `.orch.yml`.
fn read_project_channel_config(project_dir: &std::path::Path) -> ProjectChannelConfig {
let config_path = project_dir.join(".orch.yml");
if !config_path.exists() {
return ProjectChannelConfig::default();
}
let content = match std::fs::read_to_string(&config_path) {
Ok(c) => c,
Err(e) => {
tracing::warn!(
path = %config_path.display(),
error = %e,
"failed to read .orch.yml; channel config will use defaults"
);
return ProjectChannelConfig::default();
}
};
let val: serde_norway::Value = match serde_norway::from_str(&content) {
Ok(v) => v,
Err(e) => {
tracing::warn!(
path = %config_path.display(),
error = %e,
"failed to parse .orch.yml; channel config will use defaults"
);
return ProjectChannelConfig::default();
}
};
let channels = match val.get("channels") {
Some(c) => c,
None => return ProjectChannelConfig::default(),
};
let get_str = |section: &str, key: &str| -> Option<String> {
channels
.get(section)
.and_then(|s| s.get(key))
.and_then(|v| v.as_str())
.map(String::from)
};
ProjectChannelConfig {
telegram_topic_id: get_str("telegram", "topic_id"),
telegram_bot_token: get_str("telegram", "bot_token"),
telegram_chat_id: get_str("telegram", "chat_id"),
discord_channel_id: get_str("discord", "channel_id"),
discord_bot_token: get_str("discord", "bot_token"),
discord_guild_id: get_str("discord", "guild_id"),
}
}
/// Fetch the latest orch release tag from GitHub via the `gh` CLI (async).
///
/// Returns the version string (without the leading "v"), or `None` when the
/// check fails (no network, unauthenticated, `gh` not installed, etc.).
async fn fetch_latest_release_version() -> Option<String> {
let output = Command::new("gh")
.args([
"api",
"repos/gabrielkoerich/orch/releases/latest",
"--jq",
".tag_name",
])
.output()
.await
.ok()?;
if !output.status.success() {
return None;
}
let tag = String::from_utf8(output.stdout).ok()?;
let version = tag.trim().trim_start_matches('v').to_string();
if version.is_empty() {
None
} else {
Some(version)
}
}
/// Check if a newer orch release is available and send channel notifications
/// asking the operator to upgrade manually. Upgrading is operator-only — the
/// service never runs `brew` itself.
///
/// Uses the store's KV to throttle checks (`upgrade:last_check_at`) and
/// deduplicate notifications (`upgrade:last_notified_version`). Each distinct
/// latest version is notified about once; the notification repeats only when
/// an even newer version is released.
async fn check_and_notify_upgrade(
store: &Arc<TaskStore>,
channels: &Arc<ChannelRegistry>,
current_version: &str,
check_interval: std::time::Duration,
) {
let last_check_key = "upgrade:last_check_at";
let last_notified_key = "upgrade:last_notified_version";
// Throttle: only check once per interval.
let now = chrono::Utc::now().timestamp();
if let Ok(Some(last_check_str)) = store.kv_get(last_check_key).await {
if let Ok(last_check) = last_check_str.parse::<i64>() {
if now - last_check < check_interval.as_secs() as i64 {
return;
}
}
}
// Record check timestamp (best-effort).
let _ = store.kv_set(last_check_key, &now.to_string()).await;
let latest = match fetch_latest_release_version().await {
Some(v) => v,
None => {
tracing::debug!("upgrade check: failed to fetch latest release version");
return;
}
};
if latest == current_version {
tracing::debug!(current = %current_version, "orch is up to date");
return;
}
tracing::warn!(
current_version = %current_version,
latest_version = %latest,
"orch upgrade available"
);
// Operator-only upgrade: send channel notifications so the operator can
// upgrade on their own schedule. The service never runs brew itself.
// Deduplicate: don't re-notify for the same latest version.
if let Ok(Some(last_notified)) = store.kv_get(last_notified_key).await {
if last_notified == latest {
tracing::debug!(latest = %latest, "upgrade already notified");
return;
}
}
let msg_telegram = format!(
"⚠️ <b>Orch Upgrade Available</b>\n\n\
Service: <code>{current_version}</code>\n\
Latest: <code>{latest}</code>\n\n\
Run: <code>brew update && brew upgrade orch && brew services restart orch</code>"
);
let msg_discord = format!(
"⚠️ **Orch Upgrade Available**\n\n\
Service: `{current_version}`\n\
Latest: `{latest}`\n\n\
Run: `brew update && brew upgrade orch && brew services restart orch`"
);
let msg_slack = format!(
"⚠️ *Orch Upgrade Available*\n\n\
Service: `{current_version}`\n\
Latest: `{latest}`\n\n\
Run: `brew update && brew upgrade orch && brew services restart orch`"
);
for channel in channels.iter() {
let (body, metadata, topic_id) = match channel.name() {
"telegram" => (
msg_telegram.clone(),
serde_json::json!({"preformatted_html": true}),
None,
),
"discord" => (msg_discord.clone(), serde_json::json!({}), None),
"slack" => (msg_slack.clone(), serde_json::json!({}), None),
_ => continue,
};
let msg = OutgoingMessage {
thread_id: "upgrade".to_string(),
body,
reply_to: None,
metadata,
topic_id,
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(
channel = channel.name(),
?e,
"failed to send upgrade notification"
);
}
}
// Record that we notified for this latest version.
let _ = store.kv_set(last_notified_key, &latest).await;
}
/// Send a one-time escalation notification when the startup retry loop has been
/// spinning for longer than `startup_failure_escalation_secs`.
///
/// This is called *before* the channel registry is initialised (the retry loop
/// sits above it in `serve()`), so we construct channel objects directly from
/// config — mirroring the approach used during normal channel registration, but
/// without relying on `ChannelRegistry`.
async fn send_startup_escalation_notification(elapsed_secs: u64) {
let duration = crate::channels::notification::format_duration(elapsed_secs as f64);
let msg_telegram = format!(
"🚨 <b>Orch startup blocked — GitHub unreachable</b>\n\n\
The engine has been retrying backend connections for {}\n\
without success. All task processing, routing, and scheduled\n\
jobs are paused. Check service logs with `orch log -f`.",
duration
);
let msg_discord = format!(
"🚨 **Orch startup blocked — GitHub unreachable**\n\n\
The engine has been retrying backend connections for {}\n\
without success. All task processing, routing, and scheduled\n\
jobs are paused. Check service logs with `orch log -f`.",
duration
);
let msg_slack = format!(
"🚨 *Orch startup blocked — GitHub unreachable*\n\n\
The engine has been retrying backend connections for {}\n\
without success. All task processing, routing, and scheduled\n\
jobs are paused. Check service logs with `orch log -f`.",
duration
);
// Telegram
let tg_token = crate::config::get("channels.telegram.bot_token");
let tg_chat_id = crate::config::get("channels.telegram.chat_id");
if let (Ok(token), Ok(chat_id)) = (&tg_token, &tg_chat_id) {
if !token.is_empty() && !chat_id.is_empty() {
if let Ok(channel) = TelegramChannel::new(token.clone(), Some(chat_id.clone())) {
let msg = OutgoingMessage {
thread_id: "startup_escalation".to_string(),
body: msg_telegram.clone(),
reply_to: None,
metadata: serde_json::json!({ "preformatted_html": true }),
topic_id: crate::config::get("channels.telegram.general_topic_id").ok(),
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(?e, "failed to send startup escalation via telegram");
} else {
tracing::info!("startup escalation notification sent to telegram");
}
}
}
}
// Discord
if let Ok(token) = crate::config::get("channels.discord.bot_token") {
let channel_id = crate::config::get("channels.discord.channel_id")
.or_else(|_| crate::config::get("channels.discord.general_channel_id"));
if !token.is_empty() {
if let Some(cid) = channel_id.ok().filter(|s| !s.is_empty()) {
let shard_id = crate::config::get("channels.discord.shard_id")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(0);
let shard_count = crate::config::get("channels.discord.shard_count")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(1);
if let Ok(gateway) = DiscordGateway::new(token, Some(cid), shard_id, shard_count) {
let msg = OutgoingMessage {
thread_id: "startup_escalation".to_string(),
body: msg_discord.clone(),
reply_to: None,
metadata: serde_json::Value::Null,
topic_id: None,
};
if let Err(e) = gateway.send(&msg).await {
tracing::warn!(?e, "failed to send startup escalation via discord");
} else {
tracing::info!("startup escalation notification sent to discord");
}
}
}
}
}
// Slack
if let Ok(token) = crate::config::get("channels.slack.bot_token") {
let channel_id = crate::config::get("channels.slack.channel_id");
if !token.is_empty() {
if let Ok(cid) = channel_id {
if let Ok(channel) = SlackChannel::new(token, Some(cid)) {
let msg = OutgoingMessage {
thread_id: "startup_escalation".to_string(),
body: msg_slack.clone(),
reply_to: None,
metadata: serde_json::Value::Null,
topic_id: None,
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(?e, "failed to send startup escalation via slack");
} else {
tracing::info!("startup escalation notification sent to slack");
}
}
}
}
}
}
/// Start the orch service.
///
/// This is the main entry point — called by `orch serve`.
pub async fn serve() -> anyhow::Result<()> {
let killed = crate::home::kill_other_orch_serve_processes(std::time::Duration::from_secs(30));
if killed > 0 {
tracing::info!(count = killed, "terminated stale orch serve processes");
}
tracing::info!("orch engine starting");
// Pre-create standard directories with async I/O so subsequent synchronous
// callers (state_dir, orch_home, etc.) find them already present and their
// create_dir_all calls become fast no-ops.
if let Err(e) = crate::home::init_dirs().await {
tracing::warn!("failed to initialize orch directories: {e}");
}
// Pre-warm the config cache with async I/O so get() / get_list() calls in
// hot async paths never block a Tokio thread on std::fs::read_to_string.
if let Err(e) = crate::config::warm_cache().await {
tracing::warn!("failed to warm config cache: {e}");
}
let mut config = EngineConfig::from_config();
tracing::info!("internal database ready");
// Initialize project engines — retry with backoff so a network outage at
// startup doesn't cause a crash-loop (launchd KeepAlive would restart us
// immediately, filling the error log with 600+ identical messages).
//
// IMPORTANT: errors from init_project_engines() must NEVER propagate past
// this loop to main(). If they did, anyhow would write "Error: …" to stderr,
// which brew routes to orch.error.log — polluting it even when projects ARE
// configured correctly but GitHub is temporarily unreachable.
let startup_escalation_secs = config.startup_failure_escalation_secs;
let mut project_engines = {
let mut delay_secs = 5u64;
let mut attempt = 0u32;
let mut escalated = false;
let start = std::time::Instant::now();
loop {
attempt += 1;
match init_project_engines().await {
Ok(engines) => break engines,
Err(e) => {
let elapsed = start.elapsed().as_secs();
// Short blips (under the escalation threshold) stay at WARN
// so they don't flood the operator's attention. Once the
// outage crosses the threshold, escalate to ERROR-level
// logging and send a one-time push notification to configured
// channels — "transient" has clearly become "prolonged."
if startup_escalation_secs > 0
&& !escalated
&& elapsed >= startup_escalation_secs
{
escalated = true;
tracing::error!(
delay_secs,
attempt,
elapsed_secs = elapsed,
threshold_secs = startup_escalation_secs,
"project backends unavailable for {} — escalating startup failure: {e}",
crate::channels::notification::format_duration(elapsed as f64)
);
// Send one-time notification to configured channels.
// Channels aren't registered yet at this stage, so we
// construct them directly from config (mirrors orch notify).
send_startup_escalation_notification(elapsed).await;
} else {
tracing::warn!(
delay_secs,
attempt,
"project backends unavailable, retrying: {e}"
);
}
tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;
delay_secs = (delay_secs * 2).min(120);
}
}
}
};
tracing::info!(
project_count = project_engines.len(),
"initialized project engines"
);
// Full set of currently-configured project repos, used by the per-tick global
// sweeps (e.g. `dispatch_routed_tasks_global`) to distinguish "orphaned" tasks
// (repo no longer in config) from tasks belonging to some other active project.
let active_repos: std::collections::HashSet<String> =
project_engines.iter().map(|e| e.repo.clone()).collect();
// Create the event bus for task status transitions
let event_bus = events::EventBus::new(256);
if let Err(e) = event_bus.start_ws_server().await {
tracing::warn!(
?e,
"failed to start event websocket server, continuing without it"
);
}
// Check for a newer orch release in the background and log if the service is behind.
// The periodic checker sends channel notifications after channels are initialized;
// upgrading is operator-only and never runs automatically.
{
let current = env!("ORCH_VERSION").to_string();
tokio::spawn(async move {
if let Some(latest) = fetch_latest_release_version().await {
if latest != current {
tracing::warn!(
current_version = %current,
latest_version = %latest,
"orch service is behind the latest release — run: brew update && brew upgrade orch && brew services restart orch"
);
}
}
});
}
// Re-create task managers with shared store and event bus
for engine in &mut project_engines {
engine.task_manager = Arc::new(TaskManager::with_events(
engine.backend.clone(),
engine.store.clone(),
engine.repo.clone(),
event_bus.sender(),
));
}
if let Err(e) = reconcile_startup_worktrees(&project_engines).await {
tracing::warn!(err = %e, "startup worktree reconciliation failed");
}
// Clear incremental ingest cursors so the first sync after startup re-scans the last 24h.
// This catches issues created during engine downtime that would otherwise be permanently
// skipped (GitHub's `since` filter uses updated_at, not created_at).
for engine in &project_engines {
crate::engine::sync::clear_issues_last_ingested(&engine.store, &engine.repo).await;
}
{
// Run estimate reconciliation in the background so it never blocks startup.
// Each GraphQL mutation takes ~0.8 s; with hundreds of tasks this would
// otherwise delay the engine reaching its main loop by several minutes.
let engines_snapshot: Vec<ProjectEngine> = project_engines.clone();
tokio::spawn(async move {
reconcile_startup_estimates(&engines_snapshot).await;
});
}
// Build ChannelRouter from global config + per-project configs
let global_channel_config = GlobalChannelConfig {
telegram_general_topic_id: crate::config::get("channels.telegram.general_topic_id").ok(),
discord_general_channel_id: crate::config::get("channels.discord.general_channel_id").ok(),
control_telegram_topic_id: crate::config::get("control.channels.telegram.topic_id").ok(),
control_discord_channel_id: crate::config::get("control.channels.discord.channel_id").ok(),
};
let project_channel_configs: Vec<(String, ProjectChannelConfig)> = project_engines
.iter()
.map(|e| {
let cfg = read_project_channel_config(&e.project_dir);
(e.repo.clone(), cfg)
})
.collect();
let channel_router = Arc::new(ChannelRouter::new(
&global_channel_config,
&project_channel_configs,
));
tracing::info!(
projects = ?channel_router.projects(),
"channel router initialized"
);
// Initialize tmux manager (shared across all projects)
let tmux = Arc::new(TmuxManager::new());
// Initialize transport
let transport = Arc::new(Transport::new());
// Initialize capture service and start background loop
let capture = Arc::new(CaptureService::new(transport.clone()));
let capture_for_tick = capture.clone();
tokio::spawn(async move {
capture.start().await;
});
// Initialize channel registry
let mut channel_registry = ChannelRegistry::new();
// Try to initialize Telegram channel
if let Ok(token) = crate::config::get("channels.telegram.bot_token") {
if !token.is_empty() {
let chat_id = crate::config::get("channels.telegram.chat_id").ok();
match TelegramChannel::new(token, chat_id) {
Ok(telegram) => {
if let Err(e) = telegram.health_check().await {
tracing::warn!(?e, "telegram channel health check failed, skipping");
} else {
channel_registry.register(Box::new(telegram));
tracing::info!("telegram channel registered");
}
}
Err(e) => {
tracing::warn!(?e, "failed to create telegram channel, skipping");
}
}
}
}
// Try to initialize Discord Gateway channel (websocket)
if let Ok(token) = crate::config::get("channels.discord.bot_token") {
if !token.is_empty() {
let channel_id = crate::config::get("channels.discord.channel_id").ok();
let shard_id = crate::config::get("channels.discord.shard_id")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(0);
let shard_count = crate::config::get("channels.discord.shard_count")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(1);
match DiscordGateway::new(token, channel_id, shard_id, shard_count) {
Ok(discord) => {
if let Err(e) = discord.health_check().await {
tracing::warn!(?e, "discord gateway health check failed, skipping");
} else {
channel_registry.register(Box::new(discord));
tracing::info!(shard_id, shard_count, "discord gateway registered");
}
}
Err(e) => {
tracing::warn!(?e, "failed to create discord gateway, skipping");
}
}
}
}
// Try to initialize Slack channel
if let Ok(token) = crate::config::get("channels.slack.bot_token") {
if !token.is_empty() {
let channel_id = crate::config::get("channels.slack.channel_id").ok();
match SlackChannel::new(token, channel_id) {
Ok(slack) => {
if let Err(e) = slack.health_check().await {
tracing::warn!(?e, "slack channel health check failed, skipping");
} else {
channel_registry.register(Box::new(slack));
tracing::info!("slack channel registered");
}
}
Err(e) => {
tracing::warn!(?e, "failed to create slack channel, skipping");
}
}
}
}
// Initialize tmux channel with transport for output streaming
let tmux_channel = TmuxChannel::with_transport(transport.clone());
channel_registry.register(Box::new(tmux_channel));
tracing::info!("tmux channel registered");
// Start all channels and collect their message receivers
let mut channel_receivers: Vec<tokio::sync::mpsc::Receiver<IncomingMessage>> = Vec::new();
for channel in channel_registry.iter() {
match channel.start().await {
Ok(rx) => {
tracing::info!(channel = channel.name(), "channel started");
channel_receivers.push(rx);
}
Err(e) => {
tracing::warn!(channel = channel.name(), ?e, "failed to start channel");
}
}
}
// Wrap channel registry in Arc for shared access (notification dispatcher needs it)
let channel_registry = Arc::new(channel_registry);
// Spawn tasks to handle incoming channel messages (if any channels are active)
let transport_for_messages = transport.clone();
let tmux_for_messages = tmux.clone();
let capture_for_messages = capture_for_tick.clone();
let channels_for_messages = channel_registry.clone();
// Lightweight engine references for command execution and task creation
let engine_refs: Vec<EngineRef> = project_engines
.iter()
.map(|e| {
(
e.repo.clone(),
e.backend.clone(),
e.task_manager.clone(),
Some(e.store.clone()),
)
})
.collect();
// Shared in-memory map for pending project picks (General channel multi-project picker).
let pending_picks: channel_handler::PendingPicks =
std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
let router_for_messages = channel_router.clone();
for mut rx in channel_receivers {
let transport = transport_for_messages.clone();
let tmux = tmux_for_messages.clone();
let capture = capture_for_messages.clone();
let channels = channels_for_messages.clone();
let engine_refs = engine_refs.clone();
let ch_router = router_for_messages.clone();
let picks = pending_picks.clone();
tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
tracing::debug!(channel = %msg.channel, thread = %msg.thread_id, "received message from channel");
channel_handler::handle_channel_message(
msg,
&transport,
&tmux,
&capture,
&channels,
&engine_refs,
&ch_router,
&picks,
)
.await;
}
});
}
// Post-restart confirmation: if the service was restarted via the /restart control command,
// a KV marker was stored before shutdown. Send a confirmation to the originating channel now
// that we're back online. Use a short delay to let the channel connections re-establish.
{
let restart_channels = channel_registry.clone();
let restart_store = project_engines.first().map(|e| e.store.clone());
if let Some(store) = restart_store {
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
match store.kv_get("control:restart_pending").await {
Ok(Some(conv_key)) => {
if let Some((ch_name, thread_id, topic_id)) =
crate::channels::transport::parse_conversation_key(&conv_key)
{
for ch in restart_channels.iter() {
if ch.name() == ch_name {
let msg = OutgoingMessage {
thread_id: thread_id.to_string(),
body: "orch restarted successfully.".to_string(),
reply_to: None,
metadata: serde_json::json!({}),
topic_id: topic_id.map(|t| t.to_string()),
};
if let Err(e) = ch.send(&msg).await {
tracing::warn!(
channel = ch_name,
error = %e,
"failed to send restart confirmation"
);
}
break;
}
}
}
if let Err(e) = store.kv_delete("control:restart_pending").await {
tracing::warn!(error = %e, "failed to clear control:restart_pending");
}
}
Ok(None) => {} // no pending restart, nothing to do
Err(e) => {
tracing::warn!(error = %e, "failed to read control:restart_pending");
}
}
});
}
}
// Spawn notification dispatcher — reads task completion notifications
// from transport and broadcasts to configured channels.
//
// Routing priority:
// 1. Dedicated channel: if the notification has a `repo` and the
// ChannelRouter maps it to a topic/channel, send there with `topic_id`.
// 2. Subscribed channels: send to each (channel, thread_id) subscribed to
// the repo, using `format_with_project()` so recipients know the source.
// 3. Fallback: if no repo or no dedicated channel, broadcast to all
// channels without a topic_id (legacy behaviour).
{
let mut notification_rx = transport.subscribe_notifications();
let channels = channel_registry.clone();
let notif_router = channel_router.clone();
// Grab a store reference for subscription lookups.
let notif_store: Option<Arc<TaskStore>> = project_engines.first().map(|e| e.store.clone());
tokio::spawn(async move {
loop {
match notification_rx.recv().await {
Ok(notification) => {
let level = NotificationLevel::from_config();
if !level.should_notify(¬ification.status) {
tracing::debug!(
task_id = %notification.task_id,
status = %notification.status,
"notification suppressed by level={:?}",
level
);
continue;
}
tracing::info!(
task_id = %notification.task_id,
status = %notification.status,
repo = ?notification.repo,
"routing notification to channels"
);
// Track whether we sent to at least one dedicated/subscribed target.
let mut routed = false;
// 0. Direct target: if notify_target is set, send straight to
// that Telegram chat_id and skip all other routing.
if let Some(ref target) = notification.notify_target {
let telegram = channels.iter().find(|c| c.name() == "telegram");
if let Some(channel) = telegram {
let body = notification.format_telegram();
let metadata = serde_json::json!({
"preformatted_html": true,
"chat_id_override": target
});
let msg = OutgoingMessage {
thread_id: notification.task_id.clone(),
body,
reply_to: None,
metadata,
topic_id: None,
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(
task_id = %notification.task_id,
target,
?e,
"failed to send to notify_target"
);
} else {
routed = true;
}
}
}
if routed {
// notify_target handled — skip further routing
} else if let Some(repo) = notification.repo.as_deref() {
// Track destinations already sent to in this iteration so
// the dedicated (path 1) and subscribed (path 2) loops
// don't double-fire the same Telegram/Discord destination
// when a repo's configured topic and a `channel_subscriptions`
// row resolve to the same `(channel, topic_id)`.
let mut sent: std::collections::HashSet<(String, Option<String>)> =
std::collections::HashSet::new();
// 1. Dedicated channel targets for this repo.
for channel in channels.iter() {
let ch_name = channel.name();
if let Some(topic_id) =
notif_router.target_for_project(repo, ch_name)
{
let body = match ch_name {
"telegram" => notification.format_telegram(),
"discord" => notification.format_discord(),
"slack" => notification.format_slack(),
_ => continue,
};
let metadata = if ch_name == "telegram" {
serde_json::json!({"preformatted_html": true})
} else {
serde_json::json!({})
};
let resolved_topic = Some(topic_id.to_string());
let msg = OutgoingMessage {
thread_id: notification.task_id.clone(),
body,
reply_to: None,
metadata,
topic_id: resolved_topic.clone(),
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(
channel = ch_name,
task_id = %notification.task_id,
?e,
"failed to send to dedicated channel"
);
} else {
sent.insert((ch_name.to_string(), resolved_topic));
routed = true;
}
}
}
// 2. Subscribed channels for this repo.
if let Some(store) = ¬if_store {
match store.list_subscribers_for_repo(repo).await {
Ok(subscribers) => {
for (ch_name, thread_id, topic_id) in subscribers {
let channel =
channels.iter().find(|c| c.name() == ch_name);
let Some(channel) = channel else {
continue;
};
let resolved_topic = if topic_id.is_empty() {
None
} else {
Some(topic_id.clone())
};
// Skip if a dedicated send to the same
// (channel, topic_id) already happened.
if sent.contains(&(
ch_name.clone(),
resolved_topic.clone(),
)) {
tracing::debug!(
channel = %ch_name,
task_id = %notification.task_id,
topic_id = ?resolved_topic,
"skipping duplicate subscriber dispatch — destination already received from dedicated path"
);
continue;
}
let body = notification.format_with_project(&ch_name);
let metadata = if ch_name == "telegram" {
serde_json::json!({"preformatted_html": true})
} else {
serde_json::json!({})
};
let msg = OutgoingMessage {
thread_id: thread_id.clone(),
body,
reply_to: None,
metadata,
topic_id: resolved_topic.clone(),
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(
channel = %ch_name,
task_id = %notification.task_id,
?e,
"failed to send to subscribed channel"
);
} else {
sent.insert((ch_name.clone(), resolved_topic));
routed = true;
}
}
}
Err(e) => {
tracing::warn!(
repo,
?e,
"failed to list subscribers for repo"
);
}
}
}
}
// 3. Fallback: broadcast to all channels when no routing happened.
if !routed {
for channel in channels.iter() {
let (body, should_send, is_telegram) = match channel.name() {
"telegram" => (notification.format_telegram(), true, true),
"discord" => (notification.format_discord(), true, false),
"slack" => (notification.format_slack(), true, false),
// GitHub is already handled by backend.post_comment()
// tmux doesn't need task completion notifications
_ => (String::new(), false, false),
};
if !should_send {
continue;
}
let metadata = if is_telegram {
serde_json::json!({"preformatted_html": true})
} else {
serde_json::json!({})
};
let msg = OutgoingMessage {
thread_id: notification.task_id.clone(),
body,
reply_to: None,
metadata,
topic_id: None,
};
if let Err(e) = channel.send(&msg).await {
tracing::warn!(
channel = channel.name(),
task_id = %notification.task_id,
?e,
"failed to send notification"
);
}
}
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
tracing::warn!(missed = n, "notification receiver lagged");
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
tracing::debug!("notification channel closed");
break;
}
}
}
});
tracing::info!("notification dispatcher started");
}
// Notify used by webhook events to wake up the engine tick immediately
let webhook_notify = Arc::new(Notify::new());
// Track webhook state for health checks and fallback.
// When webhooks are disabled, `in_fallback_mode` stays true so sync
// uses the faster fallback interval for polling.
let webhook_port: Option<u16>;
let mut webhook_healthy: bool;
let mut last_webhook_health_check = std::time::Instant::now();
// Start webhook server if configured
let webhook_enabled = crate::config::get("webhook.enabled")
.map(|v| v == "true")
.unwrap_or(false);
// Shared status updated by the server-spawn task and the health-check loop.
let webhook_status = Arc::new(tokio::sync::Mutex::new(
crate::webhook_status::WebhookStatus::default(),
));
if webhook_enabled {
let port: u16 = crate::config::get("webhook.port")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(8080);
webhook_port = Some(port);
let secret = crate::config::get("webhook.secret").unwrap_or_default();
let webhook_repo = project_engines
.first()
.map(|e| e.repo.clone())
.unwrap_or_default();
let (tx, mut rx) = tokio::sync::mpsc::channel::<IncomingMessage>(64);
// Initialise status: configured, not yet healthy.
let to_save = {
let mut s = webhook_status.lock().await;
s.configured = true;
s.port = Some(port);
s.healthy = false;
s.fallback_mode = false;
s.clone()
};
to_save.save().await;
// Spawn the HTTP server with exponential-backoff retry on transient
// bind errors (e.g. EADDRINUSE). After MAX_ATTEMPTS the engine falls
// back to polling and updates the shared status accordingly.
const WEBHOOK_MAX_ATTEMPTS: u32 = 5;
let status_for_spawn = webhook_status.clone();
tokio::spawn(async move {
use crate::channels::github::{is_transient_bind_error, webhook_backoff_delay};
let mut attempt = 0u32;
loop {
attempt += 1;
tracing::info!(attempt, port, "attempting to start webhook server");
match start_webhook_server(port, secret.clone(), webhook_repo.clone(), tx.clone())
.await
{
Ok(_) => {
tracing::info!(attempt, "webhook server exited cleanly");
break;
}
Err(e) => {
let reason = e.to_string();
tracing::error!(attempt, %reason, "webhook server failed");
if attempt >= WEBHOOK_MAX_ATTEMPTS || !is_transient_bind_error(&e) {
let kind = if attempt >= WEBHOOK_MAX_ATTEMPTS {
"max attempts reached"
} else {
"non-transient error"
};
tracing::error!(
attempt,
%reason,
kind,
orch_webhook_in_fallback = true,
"webhook server giving up, switching to polling fallback"
);
let to_save = {
let mut s = status_for_spawn.lock().await;
s.fallback_mode = true;
s.healthy = false;
s.last_failure_reason = Some(reason);
s.startup_attempts = attempt;
s.clone()
};
to_save.save().await;
break;
}
let delay = webhook_backoff_delay(attempt);
tracing::warn!(
attempt,
delay_ms = delay.as_millis(),
%reason,
"webhook bind failed (transient), retrying with backoff"
);
{
let to_save = {
let mut s = status_for_spawn.lock().await;
s.startup_attempts = attempt;
s.last_failure_reason = Some(reason);
s.clone()
};
to_save.save().await;
}
tokio::time::sleep(delay).await;
}
}
}
});
// Spawn the message forwarding task (reads from webhook channel)
let notify = webhook_notify.clone();
let transport_for_webhook = transport.clone();
tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
tracing::info!(
channel = %msg.channel,
thread = %msg.thread_id,
event = %msg.metadata.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
action = %msg.metadata.get("action").and_then(|v| v.as_str()).unwrap_or("unknown"),
"webhook event received, triggering immediate tick"
);
let route = transport_for_webhook.route(&msg).await;
tracing::info!(
channel = %msg.channel,
route = ?route,
"webhook event routed"
);
// Wake up the engine tick immediately instead of waiting up to 10s
notify.notify_one();
}
});
webhook_healthy = true;
tracing::info!(port, orch_webhook_up = true, "webhook server started");
} else {
webhook_port = None;
webhook_healthy = false;
{
let to_save = {
let mut s = webhook_status.lock().await;
s.configured = false;
s.fallback_mode = true;
s.clone()
};
to_save.save().await;
}
tracing::info!(
orch_webhook_in_fallback = true,
"webhook server disabled, using polling fallback mode"
);
}
// Agent router (selects agent + model per task) - shared across projects.
// Router::from_config() may run `opencode models` (a blocking subprocess) to
// discover free models. Wrapping in spawn_blocking keeps the Tokio runtime
// thread free during that I/O.
// NOTE: Router::new() also calls prime_free_model_cache() (another blocking
// subprocess), so the fallback must also run inside spawn_blocking.
let router = Arc::new(RwLock::new(
match tokio::task::spawn_blocking(Router::from_config).await {
Ok(r) => r,
Err(e) => {
tracing::error!(?e, "router init panicked in spawn_blocking, using default");
tokio::task::spawn_blocking(|| Router::new(RouterConfig::default()))
.await
.unwrap_or_else(|e2| {
panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
})
}
},
));
{
let r = router.read().await;
tracing::info!(
mode = %r.config.mode,
agents = ?r.available_agents,
fallback = %r.config.fallback_executor,
"router initialized"
);
}
// Concurrency limiter (shared across all projects)
let semaphore = Arc::new(Semaphore::new(config.max_parallel));
// In-memory dispatch guard: tracks task IDs currently being dispatched.
// Guards against GitHub API eventual consistency — after update_status(InProgress),
// the label-removal webhook can trigger an immediate tick where list_by_status(Routed)
// still returns the task (search index propagation delay). The tmux session does not
// exist until the runner completes worktree setup (~10s later), so session_exists
// alone is insufficient. Keyed by "{repo}/{task_id}".
let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
// In-memory guard to prevent double-spawn of auto-merge background tasks.
// Since review_open_prs runs every sync_tick (~10s) but CI polling can take
// up to 10 minutes, we track which tasks already have an auto-merge in flight.
let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
// Subscribe to config file changes for hot reload
let mut config_rx = crate::config::subscribe();
// Track sync interval
let mut last_sync = std::time::Instant::now();
// Track upgrade check interval
let mut last_upgrade_check: Option<std::time::Instant> = None;
// Channel for weight signals from task runners back to the router
let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
// Reset InReview tasks on startup. A task is reset to NeedsReview if:
// 1. It was expecting a live review session (review_session_expected=true), OR
// 2. It has been in InReview for >10 minutes (catches cases where the flag
// was never set due to crash-loops or lost events).
// Tasks with a recent review comment on their PR are left alone.
for engine in &project_engines {
// Read from SQLite (source of truth) — GitHub labels may be out of sync.
let in_review_from_store = engine
.store
.list_by_status(&engine.repo, crate::store::TaskStatus::InReview)
.await
.unwrap_or_default()
.iter()
.map(crate::engine::tasks::store_task_to_external)
.collect::<Vec<_>>();
if !in_review_from_store.is_empty() {
let in_review = &in_review_from_store;
for task in in_review {
let session_expected =
review_session_expected(&engine.store, &engine.repo, &task.id.0).await;
let age_minutes = chrono::DateTime::parse_from_rfc3339(&task.updated_at)
.map(|dt| (chrono::Utc::now() - dt.with_timezone(&chrono::Utc)).num_minutes())
.unwrap_or(i64::MAX);
if !session_expected && age_minutes < 10 {
continue;
}
if let Err(e) = engine
.task_manager
.update_task_status(&task.id, Status::NeedsReview)
.await
{
tracing::warn!(
task_id = task.id.0,
err = %e,
"failed to reset stale InReview task on startup"
);
} else {
set_review_session_expected(&engine.store, &engine.repo, &task.id.0, false)
.await;
}
}
if !in_review.is_empty() {
tracing::info!(
repo = %engine.repo,
count = in_review.len(),
"reset stale InReview tasks to NeedsReview on startup"
);
}
}
// Also reset internal (SQLite) InReview tasks on startup.
// Note: the block above already covers internal tasks from the store,
// but this second pass catches any that were only in the old internal_tasks table.
use crate::store::TaskStatus as DbStatus;
if let Ok(internal_in_review) = engine
.task_manager
.list_internal_by_status(DbStatus::InReview)
.await
{
for task in &internal_in_review {
let task_id = task.id.0.clone();
let session_expected =
review_session_expected(&engine.store, &engine.repo, &task_id).await;
let age_minutes = chrono::DateTime::parse_from_rfc3339(&task.updated_at)
.map(|dt| (chrono::Utc::now() - dt.with_timezone(&chrono::Utc)).num_minutes())
.unwrap_or(i64::MAX);
if !session_expected && age_minutes < 10 {
continue;
}
if let Err(e) = engine
.task_manager
.update_task_status(&ExternalId(task_id.clone()), Status::NeedsReview)
.await
{
tracing::warn!(
task_id,
err = %e,
"failed to reset stale internal InReview task on startup"
);
} else {
set_review_session_expected(&engine.store, &engine.repo, &task_id, false).await;
}
}
if !internal_in_review.is_empty() {
tracing::info!(
repo = %engine.repo,
count = internal_in_review.len(),
"reset stale internal InReview tasks to NeedsReview on startup"
);
}
}
}
// Spawn dispatch subscribers — react to Routed events immediately
for engine in &project_engines {
subscribers::dispatch::spawn(
event_bus.subscribe(),
engine.backend.clone(),
tmux.clone(),
engine.runner.clone(),
capture_for_tick.clone(),
semaphore.clone(),
engine.task_manager.clone(),
weight_tx.clone(),
router.clone(),
dispatching.clone(),
engine.store.clone(),
engine.repo.clone(),
);
}
tracing::info!("dispatch subscriber started");
// Spawn review subscribers — react to NeedsReview events immediately
for engine in &project_engines {
subscribers::review::spawn(
event_bus.subscribe(),
engine.backend.clone(),
tmux.clone(),
semaphore.clone(),
engine.task_manager.clone(),
router.clone(),
dispatching.clone(),
engine.store.clone(),
engine.repo.clone(),
);
}
tracing::info!("review subscriber started");
// Spawn unblock subscribers — react to Done events, unblock parent tasks immediately
for engine in &project_engines {
subscribers::unblock::spawn(
event_bus.subscribe(),
engine.backend.clone(),
engine.task_manager.clone(),
engine.store.clone(),
engine.repo.clone(),
);
}
tracing::info!("unblock subscriber started");
// Spawn notify subscriber — reacts to ALL events, pushes to transport.
// Spawned once (not per-project) since the transport handles all repos.
subscribers::notify::spawn(event_bus.subscribe(), transport.clone());
tracing::info!("notify subscriber started");
// Main loop
tracing::info!(
tick = ?config.tick_interval,
sync = ?config.sync_interval,
parallel = config.max_parallel,
"entering main loop"
);
let mut interval = tokio::time::interval(config.tick_interval);
// Signal handlers (launchd/systemd send SIGTERM to stop services, SIGHUP for reload/restart)
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
let mut sighup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
// Guard to prevent concurrent sync_tick runs (sync is spawned as a background task).
let sync_in_progress = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Tick watchdog: detects when the main loop hasn't completed a tick in > 60s.
// Updates an atomic timestamp at the end of each tick iteration.
let last_tick_epoch = Arc::new(std::sync::atomic::AtomicU64::new(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
));
{
let last_tick_epoch = Arc::clone(&last_tick_epoch);
let tick_interval_secs = config.tick_interval.as_secs();
tokio::spawn(async move {
// Check every 30s whether the main loop is still ticking.
let mut watchdog_interval = tokio::time::interval(std::time::Duration::from_secs(30));
// Own suspend baseline, independent of the main loop's checkpoint(). The
// watchdog's interval timer also freezes during a host suspend, so this
// detects the gap from its own wake-up instead of racing the main loop's
// checkpoint() for the same GAP_LOG entry (see #3544).
let mut suspend_detector = crate::engine::suspend::SuspendDetector::new();
loop {
watchdog_interval.tick().await;
let own_gap = suspend_detector.check();
let last = last_tick_epoch.load(std::sync::atomic::Ordering::Relaxed);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let stale_secs = now.saturating_sub(last);
// Warn if the tick loop hasn't completed in > 6× the tick interval (at least 60s).
let threshold = (tick_interval_secs * 6).max(60);
if stale_secs > threshold {
// A host suspend/resume gap fully explains a stale window that
// isn't an actual stall — the process (and its timers) were
// simply not scheduled while the host was asleep. Prefer this
// watchdog's own detector (immune to the checkpoint race above);
// fall back to the shared log in case the main loop's checkpoint()
// already ran and recorded a larger gap.
let shared_gap = crate::engine::suspend::gap_detected_within(
std::time::Duration::from_secs(stale_secs),
);
let gap = match (own_gap, shared_gap) {
(Some(a), Some(b)) => Some(a.max(b)),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(None, None) => None,
};
if let Some(gap) = gap {
let gap_secs = gap.num_seconds() as u64;
if gap_secs >= stale_secs {
tracing::info!(
stale_secs,
threshold,
suspend_gap_secs = gap_secs,
"tick loop stale window explained by host suspend/resume, not a stall"
);
} else {
tracing::error!(
stale_secs,
threshold,
suspend_gap_secs = gap_secs,
"WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
stale_secs,
threshold,
gap_secs,
);
}
} else {
tracing::error!(
stale_secs,
threshold,
"WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
stale_secs,
threshold,
);
}
}
}
});
}
loop {
tokio::select! {
_ = interval.tick() => {
let tick_start = std::time::Instant::now();
// Detect a host suspend/resume gap once per iteration, in one place.
// The watchdog and stuck-task recovery both read from this instead of
// re-deriving suspend information from their own wall-clock deltas.
if let Some(gap) = crate::engine::suspend::checkpoint() {
tracing::info!(
gap_secs = gap.num_seconds(),
"host suspend/resume gap detected, discounting from stuck-task age checks"
);
}
// Tick weight recovery for rate-limited agents
{
let mut rw = router.write().await;
rw.tick_weight_recovery();
}
// Skip tick/sync entirely if GitHub API is rate-limited
if let Some(remaining) = GhHttp::is_rate_limited() {
let m = rate_limit_metrics();
tracing::warn!(
remaining_secs = remaining.as_secs(),
rate_limit_hits = m.hits,
five_xx_hits = m.five_xx_hits,
proactive_throttles = m.proactive_throttles,
wait_secs_total = m.wait_secs,
rest_remaining = ?m.rest_remaining,
graphql_remaining = ?m.graphql_remaining,
"GitHub API rate-limited, skipping tick"
);
} else {
// Core tick: poll tasks for all projects
let mut router_guard = router.write().await;
let mut routing_quota = tick::RoutingTickQuota::new(
crate::engine::router::config::max_tasks_per_routing_tick(),
);
for engine in &project_engines {
let repo = engine.repo.clone();
let project_jobs_path = engine.project_dir.join(".orch.yml");
REPO_CONTEXT.scope(repo, async {
if let Err(e) = tick::tick(
&engine.backend,
&tmux,
&engine.repo,
&engine.runner,
&capture_for_tick,
&semaphore,
&config,
&project_jobs_path,
&mut router_guard,
&engine.task_manager,
&weight_tx,
&dispatching,
&engine.store,
Some(&transport),
&active_repos,
&auto_merge_in_flight,
&mut routing_quota,
).await {
tracing::error!(repo = %engine.repo, ?e, "tick failed for project");
}
}).await;
}
drop(router_guard);
// Drain pending weight signals after tick processing so the router
// learns from outcomes produced by this iteration's task dispatches.
while let Ok(signal) = weight_rx.try_recv() {
let mut rw = router.write().await;
match signal {
WeightSignal::RateLimited { ref agent } => {
rw.record_rate_limit(agent);
}
WeightSignal::Success { ref agent } => {
rw.record_success(agent);
}
WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
}
}
// Periodic sync (less frequent) — spawned as a background task so it
// cannot block the main tick loop. A stalled sync (hung HTTP call, slow
// DB query, lock contention) previously parked all tokio workers for 12+
// minutes because it ran inline. See issue #2574.
if last_sync.elapsed() >= config.sync_interval {
if sync_in_progress.compare_exchange(
false,
true,
std::sync::atomic::Ordering::AcqRel,
std::sync::atomic::Ordering::Relaxed,
).is_ok() {
// Clone everything sync_tick needs — it runs in a spawned task.
let sync_engines: Vec<_> = project_engines.iter().map(|e| {
(e.backend.clone(), e.repo.clone(),
e.task_manager.clone(), e.store.clone())
}).collect();
let sync_tmux = Arc::clone(&tmux);
let sync_config = config.clone();
let sync_router = Arc::clone(&router);
let sync_dispatching = Arc::clone(&dispatching);
let sync_auto_merge = Arc::clone(&auto_merge_in_flight);
let sync_guard = Arc::clone(&sync_in_progress);
tokio::spawn(async move {
let sync_start = std::time::Instant::now();
for (backend, repo, task_manager, store) in &sync_engines {
let repo = repo.clone();
REPO_CONTEXT.scope(repo.clone(), async {
if let Err(e) = sync::sync_tick(
backend, &sync_tmux, &repo, &sync_config,
&sync_router, task_manager, store,
&sync_dispatching, &sync_auto_merge,
).await {
tracing::error!(repo = %repo, ?e, "sync tick failed for project");
}
}).await;
}
// Emit degraded-agents metric/log once per sync cycle.
// Clone the needed data before releasing the read guard so
// the lock is not held across the async store writes.
if let Some((_, _, _, store)) = sync_engines.first() {
let (available_agents, config) = {
let r = sync_router.read().await;
(r.available_agents.clone(), r.config.clone())
};
sync::emit_degraded_agents_if_needed(
&available_agents,
&config,
Some(store),
)
.await;
}
let elapsed = sync_start.elapsed();
tracing::info!(elapsed_ms = elapsed.as_millis() as u64, "sync tick complete");
sync_guard.store(false, std::sync::atomic::Ordering::Release);
});
} else {
tracing::debug!("sync tick still in progress, skipping");
}
// Records sync *schedule* time (not completion). This prevents
// re-entering the sync branch every tick while one is in flight.
// The sync_in_progress guard handles actual concurrency control.
last_sync = std::time::Instant::now();
}
}
// Periodic webhook health check
if webhook_enabled {
let health_check_interval = config.webhook_health_check_interval
.unwrap_or(std::time::Duration::from_secs(60));
if last_webhook_health_check.elapsed() >= health_check_interval {
if let Some(port) = webhook_port {
let (health, failure_reason) =
crate::channels::github::check_webhook_health(port).await;
if health != webhook_healthy {
webhook_healthy = health;
if webhook_healthy {
tracing::info!(port, orch_webhook_up = true, "webhook health restored");
} else {
tracing::warn!(
port,
orch_webhook_up = false,
reason = failure_reason.as_deref().unwrap_or("unknown"),
"webhook health check failed"
);
}
}
// Persist updated status.
{
let to_save = {
let mut s = webhook_status.lock().await;
s.healthy = health;
s.last_check_utc = Some(chrono::Utc::now());
if health {
s.last_failure_reason = None;
} else if failure_reason.is_some() {
s.last_failure_reason = failure_reason;
}
s.clone()
};
to_save.save().await;
}
}
last_webhook_health_check = std::time::Instant::now();
}
}
// Periodic upgrade check — notify channels when a newer release is available.
if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
if let Some(store) = project_engines.first().map(|e| e.store.clone()) {
let channels = channel_registry.clone();
let current = env!("ORCH_VERSION").to_string();
let check_interval =
std::time::Duration::from_secs(config.upgrade_check_interval);
tokio::spawn(async move {
check_and_notify_upgrade(&store, &channels, ¤t, check_interval)
.await;
});
}
last_upgrade_check = Some(std::time::Instant::now());
}
// Update watchdog timestamp + log tick duration.
let tick_elapsed = tick_start.elapsed();
if tick_elapsed.as_secs() > 30 {
tracing::warn!(elapsed_ms = tick_elapsed.as_millis() as u64, "slow tick");
} else {
tracing::debug!(elapsed_ms = tick_elapsed.as_millis() as u64, "tick complete");
}
last_tick_epoch.store(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
std::sync::atomic::Ordering::Relaxed,
);
}
// Webhook events trigger an immediate tick (bypass polling interval)
_ = webhook_notify.notified() => {
if let Some(remaining) = GhHttp::is_rate_limited() {
tracing::warn!(
remaining_secs = remaining.as_secs(),
"GitHub API rate-limited, skipping webhook-triggered tick"
);
} else {
tracing::info!("webhook event triggered immediate tick");
let mut router_guard = router.write().await;
let mut routing_quota = tick::RoutingTickQuota::new(
crate::engine::router::config::max_tasks_per_routing_tick(),
);
for engine in &project_engines {
let repo = engine.repo.clone();
let project_jobs_path = engine.project_dir.join(".orch.yml");
REPO_CONTEXT.scope(repo, async {
if let Err(e) = tick::tick(
&engine.backend,
&tmux,
&engine.repo,
&engine.runner,
&capture_for_tick,
&semaphore,
&config,
&project_jobs_path,
&mut router_guard,
&engine.task_manager,
&weight_tx,
&dispatching,
&engine.store,
Some(&transport),
&active_repos,
&auto_merge_in_flight,
&mut routing_quota,
).await {
tracing::error!(repo = %engine.repo, ?e, "webhook-triggered tick failed");
}
}).await;
}
drop(router_guard);
// Drain pending weight signals after webhook-triggered tick processing.
while let Ok(signal) = weight_rx.try_recv() {
let mut rw = router.write().await;
match signal {
WeightSignal::RateLimited { ref agent } => {
rw.record_rate_limit(agent);
}
WeightSignal::Success { ref agent } => {
rw.record_success(agent);
}
WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
}
}
// Also attempt to run an immediate sync (ingest/cleanup) in the
// background so webhook-driven events (e.g. new issues) are
// picked up without waiting for the periodic sync interval.
// Reuse the same sync_in_progress guard used by the periodic
// branch to avoid concurrent syncs.
if sync_in_progress.compare_exchange(
false,
true,
std::sync::atomic::Ordering::AcqRel,
std::sync::atomic::Ordering::Relaxed,
).is_ok() {
// Clone everything sync_tick needs — it runs in a spawned task.
let sync_engines: Vec<_> = project_engines.iter().map(|e| {
(e.backend.clone(), e.repo.clone(), e.task_manager.clone(), e.store.clone())
}).collect();
let sync_tmux = Arc::clone(&tmux);
let sync_config = config.clone();
let sync_router = Arc::clone(&router);
let sync_dispatching = Arc::clone(&dispatching);
let sync_auto_merge = Arc::clone(&auto_merge_in_flight);
let sync_guard = Arc::clone(&sync_in_progress);
tokio::spawn(async move {
let sync_start = std::time::Instant::now();
for (backend, repo, task_manager, store) in &sync_engines {
let repo = repo.clone();
REPO_CONTEXT.scope(repo.clone(), async {
if let Err(e) = sync::sync_tick(
backend, &sync_tmux, &repo, &sync_config,
&sync_router, task_manager, store,
&sync_dispatching, &sync_auto_merge,
).await {
tracing::error!(repo = %repo, ?e, "webhook immediate sync tick failed for project");
}
}).await;
}
// Emit degraded-agents metric/log once per sync cycle.
if let Some((_, _, _, store)) = sync_engines.first() {
let (available_agents, config) = {
let r = sync_router.read().await;
(r.available_agents.clone(), r.config.clone())
};
sync::emit_degraded_agents_if_needed(
&available_agents,
&config,
Some(store),
).await;
}
let elapsed = sync_start.elapsed();
tracing::info!(elapsed_ms = elapsed.as_millis() as u64, "webhook immediate sync tick complete");
sync_guard.store(false, std::sync::atomic::Ordering::Release);
});
// Record schedule time so periodic sync doesn't immediately re-run.
last_sync = std::time::Instant::now();
} else {
tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
}
}
// Also reset the interval so we don't get a redundant tick right after
interval.reset();
}
result = config_rx.recv() => {
match result {
Ok(path) => {
tracing::info!(path = %path.display(), "config file changed, reloading");
// Reload engine config
let new_config = EngineConfig::from_config();
let tick_changed = new_config.tick_interval != config.tick_interval;
config = new_config;
// Reset tick interval if it changed
if tick_changed {
interval = tokio::time::interval(config.tick_interval);
tracing::info!(tick = ?config.tick_interval, "tick interval updated");
}
// Reload router config (async-safe: use reload_async to avoid blocking the runtime)
{
let mut router_guard = router.write().await;
router_guard.reload_async().await;
}
tracing::info!(
tick = ?config.tick_interval,
sync = ?config.sync_interval,
parallel = config.max_parallel,
"config reloaded"
);
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
tracing::warn!(missed = n, "config change receiver lagged, reloading");
// Reload everything since we missed events
config = EngineConfig::from_config();
interval = tokio::time::interval(config.tick_interval);
{
let mut router_guard = router.write().await;
router_guard.reload_async().await;
}
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
tracing::warn!("config change channel closed");
}
}
}
signal_name = async {
tokio::select! {
_ = tokio::signal::ctrl_c() => "SIGINT",
_ = sigterm.recv() => "SIGTERM",
_ = sighup.recv() => "SIGHUP",
}
} => {
tracing::info!(signal = signal_name, "beginning graceful shutdown");
// Wrap the entire shutdown sequence in a timeout to enforce the configured limit.
// This prevents indefinite blocking if status updates or tmux operations hang.
let shutdown_result = tokio::time::timeout(
config.graceful_shutdown_timeout,
async {
// Reset in_progress tasks to routed so they re-dispatch after restart.
// Also reset in_review tasks to needs_review — their review agent
// tmux sessions will be killed when the process exits.
let mut reset_count = 0u32;
let mut review_reset_count = 0u32;
for engine in &project_engines {
if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InProgress).await {
for task in &tasks {
if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::Routed).await {
tracing::warn!(task_id = task.id.0, ?e, "failed to reset task on shutdown");
} else {
if let Ok(Some(store_id)) =
engine.store.resolve_task_id(&engine.repo, &task.id.0).await
{
if let Err(e) = engine
.store
.finalize_incomplete_runs(
store_id,
"aborted",
"graceful shutdown: reset in_progress task to routed",
)
.await
{
tracing::warn!(
task_id = task.id.0,
?e,
"failed to finalize incomplete runs on shutdown"
);
}
}
reset_count += 1;
}
}
}
// Also reset internal in_progress tasks
if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InProgress).await {
for task in &tasks {
let task_id = format!("internal:{}", task.id);
if let Err(e) = engine.task_manager.update_task_status(
&crate::backends::ExternalId(task_id.clone()),
Status::Routed,
).await {
tracing::warn!(task_id, ?e, "failed to reset internal task on shutdown");
} else {
if let Err(e) = engine
.store
.finalize_incomplete_runs(
task.id,
"aborted",
"graceful shutdown: reset in_progress task to routed",
)
.await
{
tracing::warn!(
task_id,
?e,
"failed to finalize incomplete internal runs on shutdown"
);
}
reset_count += 1;
}
}
}
// Reset in_review tasks — review agent sessions die on shutdown
if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InReview).await {
for task in &tasks {
if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::NeedsReview).await {
tracing::warn!(task_id = task.id.0, ?e, "failed to reset in_review task on shutdown");
} else {
set_review_session_expected(&engine.store, &engine.repo, &task.id.0, false).await;
if let Ok(Some(store_id)) =
engine.store.resolve_task_id(&engine.repo, &task.id.0).await
{
if let Err(e) = engine
.store
.finalize_incomplete_runs(
store_id,
"aborted",
"graceful shutdown: reset in_review task to needs_review",
)
.await
{
tracing::warn!(
task_id = task.id.0,
?e,
"failed to finalize incomplete review runs on shutdown"
);
}
}
review_reset_count += 1;
}
}
}
// Also reset internal in_review tasks
if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InReview).await {
for task in &tasks {
let task_id = format!("internal:{}", task.id);
if let Err(e) = engine.task_manager.update_task_status(
&crate::backends::ExternalId(task_id.clone()),
Status::NeedsReview,
).await {
tracing::warn!(task_id, ?e, "failed to reset internal in_review task on shutdown");
} else {
set_review_session_expected(&engine.store, &engine.repo, &task_id, false).await;
if let Err(e) = engine
.store
.finalize_incomplete_runs(
task.id,
"aborted",
"graceful shutdown: reset in_review task to needs_review",
)
.await
{
tracing::warn!(
task_id,
?e,
"failed to finalize incomplete internal review runs on shutdown"
);
}
review_reset_count += 1;
}
}
}
}
if reset_count > 0 {
tracing::info!(reset_count, "reset in_progress tasks to routed for re-dispatch");
}
if review_reset_count > 0 {
tracing::info!(review_reset_count, "reset in_review tasks to needs_review for re-dispatch");
}
// Kill all orch-managed tmux sessions so stale sessions don't
// block dispatch after restart (session_exists check).
let mut killed_sessions = Vec::new();
if let Ok(sessions) = tmux.list_sessions().await {
for session in &sessions {
if session.name.starts_with("orch-") {
if let Err(e) = tmux.kill_session(&session.name).await {
tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
} else {
killed_sessions.push(session.name.clone());
}
}
}
if !killed_sessions.is_empty() {
tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
}
}
// Wait for sessions to actually die before exiting.
// Prevents race where process exits before tmux finishes cleanup.
if !killed_sessions.is_empty() {
let still_alive = tmux
.wait_for_sessions_dead(
&killed_sessions,
std::time::Duration::from_millis(100),
std::time::Duration::from_secs(5),
)
.await;
if still_alive > 0 {
tracing::warn!(
still_alive,
"some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
);
}
tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
}
},
).await;
if shutdown_result.is_err() {
tracing::error!(
timeout_secs = config.graceful_shutdown_timeout.as_secs(),
"graceful shutdown timed out, forcing exit"
);
}
break;
}
}
}
// Clean up event bus port file and service version file
events::cleanup_port_file().await;
events::cleanup_version_file();
// transport and channels drop here at end of scope
let _ = transport;
tracing::info!("orch engine stopped");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn engine_config_defaults() {
let config = EngineConfig::default();
assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
assert_eq!(config.max_parallel, 4);
assert_eq!(config.stuck_timeout, 1800);
assert_eq!(config.no_session_stuck_timeout, 600);
assert!(
config.no_session_stuck_timeout < config.stuck_timeout,
"no_session_stuck_timeout must be shorter than stuck_timeout"
);
assert_eq!(
config.graceful_shutdown_timeout,
std::time::Duration::from_secs(600)
);
assert_eq!(config.upgrade_check_interval, 3600);
}
#[test]
fn engine_config_from_config_uses_defaults_when_no_config() {
let config = EngineConfig::from_config();
assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
// max_parallel may be overridden by user config; just check it's reasonable
assert!(config.max_parallel >= 1 && config.max_parallel <= 64);
assert_eq!(config.stuck_timeout, 1800);
assert_eq!(config.no_session_stuck_timeout, 600);
assert_eq!(
config.graceful_shutdown_timeout,
std::time::Duration::from_secs(600)
);
assert_eq!(config.upgrade_check_interval, 3600);
}
#[test]
fn engine_config_no_session_timeout_is_under_15_minutes() {
let config = EngineConfig::default();
assert!(
config.no_session_stuck_timeout <= 900,
"no_session_stuck_timeout ({}) exceeds 15 minutes",
config.no_session_stuck_timeout
);
}
#[test]
fn upgrade_check_runs_immediately_when_never_checked() {
assert!(should_run_upgrade_check(None, 3600));
}
#[test]
fn upgrade_check_waits_for_interval_after_first_run() {
assert!(!should_run_upgrade_check(
Some(std::time::Instant::now()),
3600
));
}
#[test]
fn upgrade_check_can_be_disabled() {
assert!(!should_run_upgrade_check(None, 0));
}
#[test]
fn configured_agents_parses_yaml_block_array() {
// config::get returns serde_norway::to_string for arrays, which is YAML block format
let yaml_str = "- claude\n- codex\n- opencode\n- olm\n";
let parsed: Vec<String> = serde_norway::from_str(yaml_str).unwrap();
assert_eq!(parsed, vec!["claude", "codex", "opencode", "olm"]);
}
#[test]
fn configured_agents_parses_json_inline_array() {
let json_str = r#"["claude","codex","olm"]"#;
let parsed: Vec<String> = serde_json::from_str(json_str).unwrap();
assert_eq!(parsed, vec!["claude", "codex", "olm"]);
}
#[test]
fn configured_agents_fallback_returns_default_agents() {
// When no config is present, configured_agents() returns DEFAULT_AGENTS
let defaults = configured_agents();
assert!(defaults.contains(&"claude".to_string()));
assert!(defaults.contains(&"codex".to_string()));
assert!(defaults.contains(&"opencode".to_string()));
}
/// Integration test that requires a fully working tmux environment with
/// reliable capture-pane timing. Runs locally but not in CI (GitHub Actions
/// has tmux installed but capture-pane timing is unreliable).
///
/// DO NOT REMOVE #[ignore] — this test was un-ignored in PR #608 which
/// broke CI. The `tmux -V` skip check is insufficient because tmux CAN
/// create sessions on CI runners, but capture-pane output is empty or
/// delayed, causing the assertion to fail after a 10s timeout.
#[tokio::test]
#[ignore]
async fn integration_channel_to_tmux_to_capture() {
use crate::channels::capture::CaptureService;
use crate::channels::transport::Transport;
use crate::tmux::SessionGuard;
use std::sync::Arc;
// Create transport and capture service
let transport = Arc::new(Transport::new());
let capture = Arc::new(CaptureService::new(transport.clone()));
let task_id = "testtask1".to_string();
let session_name = format!("orch-test-{}", task_id);
// Start a detached tmux session
let _ = tokio::process::Command::new("tmux")
.args(["new-session", "-d", "-s", &session_name])
.output()
.await
.expect("failed to start tmux session");
// Guard ensures session cleanup even on panic
let _guard = SessionGuard(session_name.clone());
// Register session with capture service and transport binding
capture
.register_session("owner/repo", &task_id, &session_name)
.await;
transport
.bind(
"owner/repo",
&task_id,
&session_name,
"telegram",
"12345",
None,
)
.await;
// Spawn capture.run() which exits when session is unregistered
let capture_clone = capture.clone();
let capture_handle = tokio::spawn(async move { capture_clone.run().await });
// Subscribe to transport output for this task
let mut rx = transport
.subscribe("owner/repo", &task_id)
.await
.expect("no subscription");
// Send a message into the tmux session via tmux send-keys (simulate channel input)
let send = tokio::process::Command::new("tmux")
.args([
"send-keys",
"-t",
&session_name,
"echo from-channel",
"Enter",
])
.output()
.await
.expect("failed to send keys");
assert!(send.status.success());
// Wait for an output chunk from capture -> transport
let mut got = false;
for _ in 0..20 {
if let Ok(Ok(c)) =
tokio::time::timeout(std::time::Duration::from_millis(500), rx.recv()).await
{
if c.content.contains("from-channel") {
got = true;
break;
}
}
}
// Clean up: unregister session (tmux kill handled by SessionGuard on drop)
capture.unregister_session("owner/repo", &task_id).await;
// Wait for capture.run to finish
let _ = capture_handle.await;
assert!(got, "did not observe tmux output via capture/transport");
}
// ── read_project_channel_config tests ─────────────────────────────────
#[test]
fn read_project_channel_config_returns_defaults_when_no_file() {
let dir = tempfile::tempdir().expect("tempdir");
let cfg = read_project_channel_config(dir.path());
assert!(cfg.telegram_topic_id.is_none());
assert!(cfg.discord_channel_id.is_none());
}
#[test]
fn read_project_channel_config_parses_telegram_and_discord() {
let dir = tempfile::tempdir().expect("tempdir");
let orch_yml = dir.path().join(".orch.yml");
std::fs::write(
&orch_yml,
"channels:\n telegram:\n topic_id: \"42\"\n discord:\n channel_id: \"9999\"\n",
)
.expect("write .orch.yml");
let cfg = read_project_channel_config(dir.path());
assert_eq!(cfg.telegram_topic_id.as_deref(), Some("42"));
assert_eq!(cfg.discord_channel_id.as_deref(), Some("9999"));
}
#[test]
fn read_project_channel_config_handles_partial_channels() {
let dir = tempfile::tempdir().expect("tempdir");
let orch_yml = dir.path().join(".orch.yml");
std::fs::write(&orch_yml, "channels:\n telegram:\n topic_id: \"7\"\n")
.expect("write .orch.yml");
let cfg = read_project_channel_config(dir.path());
assert_eq!(cfg.telegram_topic_id.as_deref(), Some("7"));
assert!(cfg.discord_channel_id.is_none());
}
#[test]
fn read_project_channel_config_handles_malformed_yaml() {
let dir = tempfile::tempdir().expect("tempdir");
let orch_yml = dir.path().join(".orch.yml");
std::fs::write(&orch_yml, "channels: [\nbad yaml").expect("write .orch.yml");
let cfg = read_project_channel_config(dir.path());
// Should return defaults (not panic) and emit a warn! log with the parse error.
assert!(cfg.telegram_topic_id.is_none());
assert!(cfg.discord_channel_id.is_none());
}
#[test]
#[cfg(unix)]
fn read_project_channel_config_handles_unreadable_file() {
let dir = tempfile::tempdir().expect("tempdir");
// A directory fails to read for every user, root included, where chmod 000 does not
std::fs::create_dir(dir.path().join(".orch.yml")).expect("create .orch.yml dir");
let cfg = read_project_channel_config(dir.path());
// Should return defaults (not panic) and emit a warn! log with the read error.
assert!(cfg.telegram_topic_id.is_none());
assert!(cfg.discord_channel_id.is_none());
}
}