1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
//! Multi-agent orchestration with scheduling, budgeting, and compound review.
//!
//! This crate provides the core orchestration engine for managing fleets of AI agents
//! with features for resource scheduling, cost tracking, and coordinated review workflows.
//!
//! # Core Components
//!
//! - **AgentOrchestrator**: Main orchestrator running the "dark factory" pattern
//! - **DualModeOrchestrator**: Real-time and batch processing modes with fairness scheduling
//! - **CompoundReviewWorkflow**: Multi-agent review swarm with persona-based specialization
//! - **Scheduler**: Time-based and event-driven task scheduling
//! - **HandoffBuffer**: Inter-agent state transfer with TTL management
//! - **CostTracker**: Budget enforcement and spending monitoring
//! - **NightwatchMonitor**: Drift detection and rate limiting
//! - **MetaCoordinator**: Cross-project issue-driven agent dispatch with PageRank prioritisation
//!
//! # Example
//!
//! ```rust,ignore
//! use terraphim_orchestrator::{AgentOrchestrator, OrchestratorConfig};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let config = OrchestratorConfig::default();
//! let mut orchestrator = AgentOrchestrator::new(config).await?;
//!
//! // Run the orchestration loop
//! orchestrator.run().await?;
//! # Ok(())
//! # }
//! ```
pub mod adf_commands;
pub mod agent_run_command;
pub mod agent_run_record;
pub mod agent_runner;
pub mod compound;
pub mod concurrency;
pub mod config;
pub mod control_plane;
pub mod cost_tracker;
pub mod dispatcher;
pub mod dual_mode;
pub mod error;
pub mod error_signatures;
pub mod evolution;
pub mod flow;
pub mod gitea_skill_loader;
pub mod handoff;
pub mod kg_router;
pub mod learning;
pub mod mention;
pub mod mention_chain;
pub mod meta_coordinator;
pub mod metrics_persistence;
pub mod mode;
pub mod nightwatch;
pub mod output_poster;
pub mod persona;
pub mod post_merge_gate;
pub mod pr_dispatch;
pub mod pr_gate;
pub mod pr_poller;
pub mod pr_review;
pub mod project_adf;
pub mod project_control;
pub mod provider_budget;
pub mod provider_probe;
#[cfg(feature = "quickwit")]
pub mod quickwit;
#[cfg(feature = "quickwit")]
pub mod quickwit_bulk;
pub mod rate_limiter;
pub mod scheduler;
pub mod scope;
pub mod webhook;
pub mod worktree_guard;
pub use agent_run_command::{
applicable_modes, is_cron_schedule_valid, parse_agent_args, run_synthetic, run_validate,
run_validate_all, schedule_for_agent, validate_agent_all_modes, AgentSubcommand,
AgentValidateAllReport, OutputFormat,
};
pub use agent_run_record::{
AgentRunRecord, ExitClass, ExitClassification, ExitClassifier, RunTrigger,
};
pub use agent_runner::{
probe_cli_tool, probe_model_available, run_agent_synthetic, validate_agent_runtime,
AgentRunRequest, AgentRuntimeValidationReport, GiteaTargetReport, ModeResult, SyntheticEvent,
TriggerMode,
};
pub use compound::{CompoundReviewResult, CompoundReviewWorkflow, ReviewGroupDef, SwarmConfig};
pub use concurrency::{ConcurrencyController, FairnessPolicy, ModeQuotas};
#[cfg(feature = "quickwit")]
pub use config::QuickwitConfig;
pub use config::{
AgentDefinition, AgentLayer, CompoundReviewConfig, ConcurrencyConfig, EvolutionConfig,
GiteaOutputConfig, LearningConfig, MentionConfig, NightwatchConfig, OrchestratorConfig,
PreCheckStrategy, TrackerConfig, TrackerStates, WebhookConfig, WorkflowConfig,
};
pub use cost_tracker::{AgentMetrics, BudgetVerdict, CostSnapshot, CostTracker, ExecutionMetrics};
pub use dispatcher::{DispatchTask, Dispatcher, DispatcherStats};
pub use dual_mode::DualModeOrchestrator;
pub use error::OrchestratorError;
pub use handoff::{HandoffBuffer, HandoffContext, HandoffLedger};
pub use mention::{
migrate_legacy_mention_cursor, parse_mention_tokens, parse_mentions, resolve_mention,
resolve_persona_mention, DetectedMention, MentionCursor, MentionTokens, MentionTracker,
};
pub use mention_chain::{
MentionChainError, MentionChainTracker, MentionContextArgs, DEFAULT_MAX_MENTION_DEPTH,
};
pub use metrics_persistence::{
InMemoryMetricsPersistence, MetricsPersistence, MetricsPersistenceConfig,
MetricsPersistenceError, PersistedAgentMetrics,
};
pub use mode::{IssueMode, TimeMode};
pub use nightwatch::{
dual_panel_evaluate, validate_certificate, Claim, CorrectionAction, CorrectionLevel,
DriftAlert, DriftMetrics, DriftScore, DualPanelResult, NightwatchMonitor, RateLimitTracker,
RateLimitWindow, ReasoningCertificate,
};
pub use output_poster::OutputPoster;
pub use persona::{MetapromptRenderError, MetapromptRenderer, PersonaRegistry};
pub use project_adf::ProjectAdfConfig;
#[cfg(feature = "quickwit")]
pub use quickwit_bulk::QuickwitEsBulkSink;
pub use rate_limiter::{is_rate_limit_backoff_enabled, RateLimiter};
pub use scheduler::{ScheduleEvent, TimeScheduler};
use terraphim_types::{FindingSeverity, ReviewFinding};
pub use worktree_guard::{with_worktree_guard, with_worktree_guard_async, WorktreeGuard};
use chrono::Timelike;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::{Duration, Instant};
use std::sync::{Arc, Mutex};
use terraphim_router::RoutingEngine;
use terraphim_spawner::health::{CircuitBreaker, HealthStatus};
use terraphim_spawner::output::OutputEvent;
use terraphim_spawner::{AgentHandle, AgentSpawner, ResourceLimits, SpawnContext, SpawnRequest};
use tokio::sync::broadcast;
use tracing::{debug, error, info, warn};
/// Result of evaluating a pre-check strategy before spawning an agent.
#[derive(Debug, Clone)]
pub enum PreCheckResult {
/// Pre-check found actionable findings. Agent should spawn with findings prepended.
Findings(String),
/// Nothing to do. Skip spawn.
NoFindings,
/// Pre-check execution itself failed. Fail-open: spawn anyway.
Failed(String),
}
/// Status of a single agent in the fleet.
#[derive(Debug, Clone)]
pub struct AgentStatus {
pub name: String,
pub layer: AgentLayer,
pub running: bool,
pub health: HealthStatus,
pub drift_score: Option<f64>,
pub uptime: Duration,
pub restart_count: u32,
/// API calls remaining per provider (None if no limit known).
pub api_calls_remaining: HashMap<String, Option<u32>>,
}
/// Runtime state for a managed agent.
struct ManagedAgent {
definition: AgentDefinition,
handle: AgentHandle,
started_at: Instant,
restart_count: u32,
output_rx: broadcast::Receiver<OutputEvent>,
spawned_by_mention: bool,
worktree_path: Option<PathBuf>,
routed_model: Option<String>,
session_id: String,
mention_chain_id: Option<String>,
mention_depth: Option<u32>,
mention_parent_agent: Option<String>,
/// Concurrency permit held while the agent is running. Released on drop.
#[allow(dead_code)]
concurrency_permit: Option<concurrency::AgentPermit>,
/// When set, post a terminal commit status on agent exit.
/// Tuple of (head_sha, context).
commit_status_post: Option<(String, String)>,
/// Temp file path for streaming agent output. Renamed to final path on exit.
output_tmp_path: Option<PathBuf>,
/// Worktree guard for automatic cleanup on agent crash.
#[allow(dead_code)]
worktree_guard: Option<crate::worktree_guard::WorktreeGuard>,
}
#[cfg(not(test))]
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct PersistedRestartState {
/// project -> agent -> restart count
#[serde(default)]
counts_by_project: HashMap<String, HashMap<String, u32>>,
/// project -> agent -> last failure timestamp (unix seconds)
#[serde(default)]
last_failure_unix_secs_by_project: HashMap<String, HashMap<String, i64>>,
/// Legacy flat map retained for backward-compatible deserialisation.
#[serde(default, skip_serializing)]
counts: HashMap<String, u32>,
/// Legacy flat map retained for backward-compatible deserialisation.
#[serde(default, skip_serializing)]
last_failure_unix_secs: HashMap<String, i64>,
}
/// The main orchestrator that runs the dark factory.
pub struct AgentOrchestrator {
config: OrchestratorConfig,
spawner: AgentSpawner,
router: RoutingEngine,
nightwatch: NightwatchMonitor,
scheduler: TimeScheduler,
compound_workflow: CompoundReviewWorkflow,
active_agents: HashMap<String, ManagedAgent>,
rate_limiter: RateLimitTracker,
shutdown_requested: bool,
/// Total restart count per (project, agent) pair (persists across agent lifecycle).
restart_counts: HashMap<(String, String), u32>,
/// Last non-zero exit timestamp per (project, agent), used for budget windowing.
restart_last_failure_unix_secs: HashMap<(String, String), i64>,
/// Last exit time per (project, agent) (for cooldown enforcement).
restart_cooldowns: HashMap<(String, String), Instant>,
/// Timestamp of the last reconciliation tick (for cron comparison).
last_tick_time: chrono::DateTime<chrono::Utc>,
/// In-memory buffer for handoff contexts with TTL.
handoff_buffer: HandoffBuffer,
/// Append-only JSONL ledger for handoff history.
handoff_ledger: HandoffLedger,
/// Per-agent cost tracking with budget enforcement.
cost_tracker: CostTracker,
/// Registry of persona definitions for metaprompt generation.
persona_registry: PersonaRegistry,
/// Renderer for persona metaprompts.
metaprompt_renderer: MetapromptRenderer,
/// Output poster for posting agent output to Gitea issues.
output_poster: Option<OutputPoster>,
/// Circuit breakers for each provider to prevent cascading failures.
#[allow(dead_code)]
circuit_breakers: Arc<Mutex<HashMap<String, CircuitBreaker>>>,
/// Per-agent last-run commit hash for GitDiff strategy.
/// Key: agent name. Value: commit SHA.
last_run_commits: HashMap<String, String>,
/// Per-agent last cron fire timestamp to prevent re-triggering within same schedule window.
/// Key: agent name. Value: timestamp of last fire.
last_cron_fire: HashMap<String, chrono::DateTime<chrono::Utc>>,
/// Last compound-review fire time, used to gate the compound schedule
/// independently of `last_tick_time`. Mirrors the `last_cron_fire`
/// pattern for per-agent crons. Without this cursor, if the
/// `reconcile_tick` future is cancelled mid-await by its 90 s
/// `tokio::time::timeout` safety wrapper, `last_tick_time` is never
/// advanced and the same compound-review occurrence re-fires on the
/// very next tick, producing a worktree storm (#1562).
last_compound_review_fired_at: Option<chrono::DateTime<chrono::Utc>>,
/// Lazy-initialised Gitea tracker for gitea-issue pre-check.
pre_check_tracker: Option<terraphim_tracker::GiteaTracker>,
/// Active flow executions keyed by flow name.
#[allow(dead_code)]
active_flows: HashMap<String, tokio::task::JoinHandle<flow::state::FlowRunState>>,
/// Per-project mention cursors, keyed by project id.
///
/// Each project gets its own cursor so repo-wide polls can advance
/// independently. Legacy single-project mode uses the synthetic
/// [`dispatcher::LEGACY_PROJECT_ID`] key.
mention_cursors: HashMap<String, MentionCursor>,
/// Receiver for webhook dispatch requests.
webhook_dispatch_rx: Option<tokio::sync::mpsc::Receiver<webhook::WebhookDispatch>>,
/// Monotonically increasing tick counter for poll_modulo gating.
tick_count: u64,
#[cfg(feature = "quickwit")]
quickwit_sink: Option<quickwit::QuickwitFleetSink>,
/// Classifier for structured agent exit classification using KG-boosted matching.
exit_classifier: ExitClassifier,
/// KG-driven model router loaded from taxonomy markdown files.
kg_router: Option<kg_router::KgRouter>,
/// Per-provider health tracking with circuit breakers.
provider_health: provider_probe::ProviderHealthMap,
/// Live telemetry store for model performance tracking from CLI output.
telemetry_store: control_plane::TelemetryStore,
/// Per-provider hour/day spend tracker consulted by the routing
/// engine. `None` when the config declares no [[providers]] entries.
provider_budget_tracker: Option<Arc<provider_budget::ProviderBudgetTracker>>,
/// Compiled per-provider stderr classifiers built from
/// `[[providers]].error_signatures`. Providers without signatures
/// are absent from the map and classify as
/// [`error_signatures::ErrorKind::Unknown`] (fail-safe).
provider_error_signatures: error_signatures::ProviderSignatureMap,
provider_rate_limits: ProviderRateLimitWindow,
retry_counts: HashMap<String, (u32, Instant)>,
/// Dedupe set of [`error_signatures::unknown_dedupe_key`] values so we
/// don't open a new `[ADF]` Gitea issue for every retry of the same
/// stderr shape. Process-lifetime in-memory; intentional since the
/// window between duplicates is short and restarting the orchestrator
/// is an acceptable dedupe reset.
unknown_error_dedupe: Arc<Mutex<std::collections::HashSet<String>>>,
/// Counter of consecutive `project-meta` failures per project. Tripped
/// entries cause the orchestrator to create a pause flag and open an
/// `[ADF]` Gitea escalation issue.
project_failure_counter: project_control::ProjectFailureCounter,
/// Resolved pause-flag directory. Derived from
/// [`OrchestratorConfig::pause_dir`] or [`project_control::DEFAULT_PAUSE_DIR`].
pause_dir: PathBuf,
/// Unified priority queue for all dispatch sources (time, issue, mention,
/// review-pr, auto-merge, post-merge-gate).
dispatcher: dispatcher::Dispatcher,
/// Per-(project, PR) rate limiter for verdict polling. Keeps the
/// orchestrator from re-hitting Gitea for the same PR every tick.
pr_poll_rate_limiter: pr_poller::PrPollRateLimiter,
/// Per-project dedupe set of `(pr_number, head_sha)` already enqueued
/// for auto-merge so the same revision is never dispatched twice.
auto_merge_enqueued: pr_poller::AutoMergeDedupeSet,
/// TTL-based dedupe cache for auto-merge failure issues. Prevents
/// duplicate `[ADF] Auto-merge failed` issues for the same PR within
/// a 24-hour window.
auto_merge_failure_dedupe: pr_poller::AutoMergeFailureDedupe,
/// Shared learning store. `None` when `learning.enabled = false` or
/// when initialisation failed (graceful degradation).
learning_store: Option<learning::SharedLearningStore>,
/// Learning config snapshot (min_trust, max_tokens, etc.).
learning_config: config::LearningConfig,
/// Agent name -> learning IDs injected at spawn time, used to record
/// outcome feedback at exit.
injected_learning_ids: HashMap<String, Vec<String>>,
/// Global concurrency controller enforcing agent limits and fairness.
concurrency_controller: concurrency::ConcurrencyController,
/// Directory for per-agent output log files. Each completed agent run
/// writes its stdout+stderr to `<agent_log_dir>/<name>-<timestamp>.log`.
agent_log_dir: PathBuf,
/// Cache directory populated from Gitea at startup (issue #1434).
/// `None` when `gitea_skill_repo` is not configured. When `Some`, this
/// directory is prepended to the skill search path so remote skills
/// shadow local ones while local directories remain as fallback.
gitea_skill_cache_dir: Option<PathBuf>,
/// Agent evolution manager. No-op when evolution feature is disabled
/// or `evolution.enabled = false` in config.
evolution_manager: evolution::EvolutionManager,
config_error_counters: HashMap<String, u32>,
quarantined_agents: std::collections::HashSet<String>,
}
/// Build the composite restart-state key for an agent definition.
///
/// Legacy (project-less) agents use [`crate::dispatcher::LEGACY_PROJECT_ID`]
/// so restart counts never collide across projects once projects are added.
fn agent_key(def: &AgentDefinition) -> (String, String) {
(
def.project
.clone()
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string()),
def.name.clone(),
)
}
struct ProviderRateLimitWindow {
blocked_until: HashMap<String, Instant>,
}
impl ProviderRateLimitWindow {
fn new() -> Self {
Self {
blocked_until: HashMap::new(),
}
}
fn block_until(&mut self, provider: &str, until: Instant) {
self.blocked_until.insert(provider.to_string(), until);
}
#[allow(dead_code)]
fn is_blocked(&self, provider: &str) -> bool {
self.blocked_until
.get(provider)
.is_some_and(|until| Instant::now() < *until)
}
fn blocked_providers(&self) -> Vec<String> {
let now = Instant::now();
self.blocked_until
.iter()
.filter(|(_, until)| **until > now)
.map(|(k, _)| k.clone())
.collect()
}
fn clean_expired(&mut self) {
let now = Instant::now();
self.blocked_until.retain(|_, until| *until > now);
}
}
/// Conservative fallback block applied at the quota-detect site when no
/// "resets" line is present in stderr at all (i.e. `parse_reset_time` cannot
/// even be invoked with useful input). Long enough to skip the next cron
/// firing (~30 min active-window cadence); short enough that a misclassified
/// non-quota error does not disable the provider for the day.
pub(crate) const DEFAULT_RATE_LIMIT_BLOCK: Duration = Duration::from_secs(900);
fn parse_reset_time(quota_line: &str) -> Option<Instant> {
let line = quota_line.to_lowercase();
if let Some(idx) = line.find("resets in ") {
let rest = &line[idx + "resets in ".len()..];
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
if let Ok(n) = digits.parse::<u64>() {
if rest.contains("hour") {
return Some(Instant::now() + Duration::from_secs(n * 3600));
}
if rest.contains("minute") {
return Some(Instant::now() + Duration::from_secs(n * 60));
}
// Short abbreviations used by Claude Code: "resets in 4h", "resets in 30m".
// The character immediately after the digits disambiguates the unit.
let unit = rest.chars().nth(digits.len());
match unit {
Some('h') => return Some(Instant::now() + Duration::from_secs(n * 3600)),
Some('m') => {
// Guard against "min..." which is already handled above; the
// "minute" branch returned first, so any remaining 'm' here
// is the short form.
return Some(Instant::now() + Duration::from_secs(n * 60));
}
_ => {}
}
}
}
// "resets 11pm" / "resets 7am" -- wall-clock hour with am/pm suffix, no "in"/"at".
// Treat the hour as UTC (bigbox locale); compute next future occurrence.
if let Some(idx) = line.find("resets ") {
let rest = line[idx + "resets ".len()..].trim_start();
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
if !digits.is_empty() {
let after_digits = &rest[digits.len()..];
let is_pm = after_digits.starts_with("pm");
let is_am = after_digits.starts_with("am");
if is_pm || is_am {
if let Ok(h) = digits.parse::<u32>() {
if h <= 12 {
let hour_24 = match (h, is_pm) {
(12, true) => 12,
(12, false) => 0,
(h, true) => h + 12,
(h, false) => h,
};
if let Some(time) = chrono::NaiveTime::from_hms_opt(hour_24, 0, 0) {
let now = chrono::Utc::now();
let mut target_date = now.date_naive();
let mut target_utc =
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
target_date.and_time(time),
chrono::Utc,
);
if target_utc <= now {
target_date += chrono::Duration::days(1);
target_utc =
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
target_date.and_time(time),
chrono::Utc,
);
}
if let Ok(delta) = (target_utc - now).to_std() {
return Some(Instant::now() + delta);
}
}
}
}
}
}
}
if let Some(idx) = line.find("resets at ") {
let rest = &line[idx + "resets at ".len()..];
if let Some(time_str) = rest
.strip_suffix(" utc")
.or_else(|| rest.strip_suffix(" utc."))
{
if let Ok(hour_min) = chrono::NaiveTime::parse_from_str(time_str.trim(), "%H:%M") {
let now = chrono::Utc::now();
let mut target_date = now.date_naive();
let target = target_date.and_time(hour_min);
let mut target_utc =
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(target, chrono::Utc);
if target_utc <= now {
target_date += chrono::Duration::days(1);
let target = target_date.and_time(hour_min);
target_utc = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
target,
chrono::Utc,
);
}
let delta = (target_utc - now).to_std().ok()?;
return Some(Instant::now() + delta);
}
}
}
if line.contains("resets ") {
return Some(Instant::now() + Duration::from_secs(3600));
}
None
}
/// Build the optional provider-level hour/day budget tracker from the
/// [[providers]] config block. Returns `Ok(None)` when no providers are
/// declared (no cap = no tracker, routing works unchanged).
fn build_provider_budget_tracker(
config: &OrchestratorConfig,
) -> Result<Option<Arc<provider_budget::ProviderBudgetTracker>>, OrchestratorError> {
if config.providers.is_empty() {
if config.provider_budget_state_file.is_some() {
warn!("provider_budget_state_file set but no [[providers]] entries; tracker disabled");
}
return Ok(None);
}
let tracker = match config.provider_budget_state_file.as_ref() {
Some(path) => provider_budget::ProviderBudgetTracker::with_persistence(
config.providers.clone(),
path.clone(),
)
.map_err(|e| {
OrchestratorError::Config(format!(
"failed to load provider budget state from {}: {}",
path.display(),
e
))
})?,
None => provider_budget::ProviderBudgetTracker::new(config.providers.clone()),
};
info!(
providers = tracker.providers().collect::<Vec<_>>().join(","),
persistence = ?config.provider_budget_state_file,
"provider budget tracker initialised"
);
Ok(Some(Arc::new(tracker)))
}
/// Build the global concurrency controller from orchestrator config.
///
/// Uses `workflow.concurrency` when workflow mode is configured; otherwise
/// falls back to sensible defaults (global_max = 10, time_max = 10,
/// issue_max = 5, round-robin fairness).
fn build_concurrency_controller(config: &OrchestratorConfig) -> concurrency::ConcurrencyController {
let (global_max, time_max, issue_max, fairness) = config
.workflow
.as_ref()
.map(|w| {
(
w.concurrency.global_max,
w.concurrency.global_max, // time-driven shares global pool
w.concurrency.issue_max,
w.concurrency
.fairness
.parse::<concurrency::FairnessPolicy>()
.unwrap_or(concurrency::FairnessPolicy::RoundRobin),
)
})
.unwrap_or((10, 10, 5, concurrency::FairnessPolicy::RoundRobin));
let quotas = concurrency::ModeQuotas {
time_max,
issue_max,
};
let project_caps: HashMap<String, concurrency::ProjectCaps> = config
.projects
.iter()
.filter_map(|p| {
p.max_concurrent_agents.map(|max| {
(
p.id.clone(),
concurrency::ProjectCaps {
max_concurrent_agents: max,
max_concurrent_mention_agents: p.max_concurrent_mention_agents,
},
)
})
})
.collect();
concurrency::ConcurrencyController::with_project_caps(
global_max,
quotas,
fairness,
project_caps,
)
}
/// Build the per-project runtime map consumed by
/// [`flow::executor::FlowExecutor::with_projects`].
fn build_flow_project_runtimes(
config: &OrchestratorConfig,
) -> HashMap<String, flow::executor::ProjectRuntime> {
config
.projects
.iter()
.map(|p| {
(
p.id.clone(),
flow::executor::ProjectRuntime {
working_dir: p.working_dir.clone(),
gitea_owner: p.gitea.as_ref().map(|g| g.owner.clone()),
gitea_repo: p.gitea.as_ref().map(|g| g.repo.clone()),
},
)
})
.collect()
}
/// Build a [`SpawnContext`] for an agent, resolving per-project working_dir,
/// Gitea owner/repo, and the project id itself into the child process's
/// environment (`ADF_PROJECT_ID`, `ADF_WORKING_DIR`, `GITEA_OWNER`,
/// `GITEA_REPO`). Legacy (project-less) agents use [`SpawnContext::global()`].
///
/// When an [`OutputPoster`] is available and has a per-agent Gitea token
/// for `(project, agent_name)` (loaded from `agent_tokens.json`), the
/// token is injected as `GITEA_TOKEN` so the agent's own `gtr` / API
/// calls inside its task shell post under its own Gitea identity. Without
/// this, `source ~/.profile` would overlay the shared root token.
fn build_spawn_context_for_agent(
config: &OrchestratorConfig,
def: &AgentDefinition,
output_poster: Option<&OutputPoster>,
) -> SpawnContext {
let Some(pid) = def.project.as_deref() else {
return SpawnContext::global();
};
let Some(project) = config.project_by_id(pid) else {
return SpawnContext::global();
};
let working_dir_str = project.working_dir.to_string_lossy().into_owned();
let mut ctx = SpawnContext::with_working_dir(project.working_dir.clone())
.with_env("ADF_PROJECT_ID", pid)
.with_env("ADF_WORKING_DIR", working_dir_str);
if let Some(gitea) = project.gitea.as_ref() {
ctx = ctx
.with_env("GITEA_URL", gitea.base_url.clone())
.with_env("GITEA_OWNER", gitea.owner.clone())
.with_env("GITEA_REPO", gitea.repo.clone());
}
if let Some(poster) = output_poster {
if let Some(token) = poster.agent_token(pid, &def.name) {
ctx = ctx.with_env("GITEA_TOKEN", token.to_string());
}
}
ctx
}
/// Flatten persisted nested maps (project -> agent -> count) and any legacy
/// flat entries into the in-memory composite key map. Legacy flat entries are
/// mapped to [`crate::dispatcher::LEGACY_PROJECT_ID`].
#[cfg(not(test))]
fn flatten_restart_counts(state: &PersistedRestartState) -> HashMap<(String, String), u32> {
let mut out: HashMap<(String, String), u32> = HashMap::new();
for (project, per_agent) in &state.counts_by_project {
for (agent, count) in per_agent {
out.insert((project.clone(), agent.clone()), *count);
}
}
for (agent, count) in &state.counts {
out.entry((
crate::dispatcher::LEGACY_PROJECT_ID.to_string(),
agent.clone(),
))
.or_insert(*count);
}
out
}
/// Flatten persisted nested maps for last-failure timestamps into the
/// composite key format.
#[cfg(not(test))]
fn flatten_restart_failures(state: &PersistedRestartState) -> HashMap<(String, String), i64> {
let mut out: HashMap<(String, String), i64> = HashMap::new();
for (project, per_agent) in &state.last_failure_unix_secs_by_project {
for (agent, ts) in per_agent {
out.insert((project.clone(), agent.clone()), *ts);
}
}
for (agent, ts) in &state.last_failure_unix_secs {
out.entry((
crate::dispatcher::LEGACY_PROJECT_ID.to_string(),
agent.clone(),
))
.or_insert(*ts);
}
out
}
/// Re-nest composite keyed maps into the persisted `project -> agent -> value`
/// shape for serialisation.
#[cfg(not(test))]
fn nest_by_project<V: Clone>(
flat: &HashMap<(String, String), V>,
) -> HashMap<String, HashMap<String, V>> {
let mut out: HashMap<String, HashMap<String, V>> = HashMap::new();
for ((project, agent), value) in flat {
out.entry(project.clone())
.or_default()
.insert(agent.clone(), value.clone());
}
out
}
/// Validate agent name for safe use in file paths.
/// Rejects empty names, names containing path separators or traversal sequences.
fn validate_agent_name(name: &str) -> Result<(), OrchestratorError> {
if name.is_empty()
|| name.contains('/')
|| name.contains('\\')
|| name.contains("..")
|| !name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(OrchestratorError::InvalidAgentName(name.to_string()));
}
Ok(())
}
/// Truncate a string to at most `max_bytes` UTF-8 bytes, honouring char
/// boundaries. If truncation occurs, append a marker so the reader knows.
fn truncate_for_issue(s: &str, max_bytes: usize) -> String {
if s.len() <= max_bytes {
return s.to_string();
}
let mut end = max_bytes;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
format!("{}... (truncated)", &s[..end])
}
impl AgentOrchestrator {
/// Create a new orchestrator from configuration.
pub fn new(config: OrchestratorConfig) -> Result<Self, OrchestratorError> {
// Set CARGO_TARGET_DIR so worktree agents share the main build cache,
// and RUSTC_WRAPPER=sccache for cross-worktree compilation caching.
let mut spawn_env = std::collections::HashMap::new();
let target_dir = config.working_dir.join("target");
spawn_env.insert(
"CARGO_TARGET_DIR".to_string(),
target_dir.to_string_lossy().to_string(),
);
if std::process::Command::new("sccache")
.arg("--version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok()
{
spawn_env.insert("RUSTC_WRAPPER".to_string(), "sccache".to_string());
info!("sccache detected, enabling shared compilation cache for worktrees");
}
let spawner = AgentSpawner::new()
.with_working_dir(&config.working_dir)
.with_env_vars(spawn_env);
let router = RoutingEngine::new();
let nightwatch = NightwatchMonitor::new(config.nightwatch.clone());
let scheduler = TimeScheduler::new(&config.agents, Some(&config.compound_review.schedule))?;
let compound_workflow =
CompoundReviewWorkflow::from_compound_config(config.compound_review.clone());
// Layer 2 startup sweep (epic #1567, issue #1570).
//
// Reconcile any worktree residue left by a previous instance
// before we accept ticks. Synchronous: must finish before the
// tick thread is spawned in `run()` so a fresh review cycle
// never races against half-killed `review-*` directories.
//
// `extra_roots` mirrors the per-agent worktree convention
// from `lib.rs:5393`. If you change that literal there, change
// it here too.
//
// `cfg(not(test))` gate: the in-lib `test_config()` (see
// `lib.rs:7926`) points `repo_path` at the live terraphim-ai
// checkout. Without this gate, the sweep's
// `git worktree prune --verbose` races against
// `test_orchestrator_compound_review_manual`'s concurrent
// `git worktree add` on that shared real repo's
// `.git/worktrees/` admin registry. The production wiring is
// exercised end-to-end by `tests/sweep_on_startup_test.rs`,
// which builds an isolated `TempDir` repo and asserts the
// sweep DOES run from `AgentOrchestrator::new`. Do not remove
// this gate without first migrating the in-lib `test_config()`
// to a TempDir-based `repo_path`.
#[cfg(not(test))]
{
let sweep_report = compound_workflow
.worktree_manager()
.sweep_stale(&[PathBuf::from("/tmp/adf-worktrees")]);
if sweep_report.swept_count + sweep_report.root_owned_skipped > 10 {
warn!(
swept_count = sweep_report.swept_count,
root_owned_skipped = sweep_report.root_owned_skipped,
failed_count = sweep_report.failed_count,
"large worktree backlog at startup -- prior crash storm likely"
);
}
}
let handoff_buffer = HandoffBuffer::new(config.handoff_buffer_ttl_secs.unwrap_or(86400));
let handoff_ledger = HandoffLedger::new(config.working_dir.join("handoff-ledger.jsonl"));
// Initialize cost tracker and register all agents with their budgets
let mut cost_tracker = CostTracker::new();
for agent_def in &config.agents {
cost_tracker.register(&agent_def.name, agent_def.budget_monthly_cents);
}
// Initialize persona registry - load from configured directory or create empty
let persona_registry = match &config.persona_data_dir {
Some(dir) => {
info!(dir = %dir.display(), "loading persona registry from directory");
PersonaRegistry::load_from_dir(dir).unwrap_or_else(|e| {
warn!(dir = %dir.display(), error = %e, "failed to load persona directory, using empty registry");
PersonaRegistry::new()
})
}
None => {
info!("no persona_data_dir configured, using empty registry");
PersonaRegistry::new()
}
};
// Initialize metaprompt renderer - check for custom template or use default
let metaprompt_renderer = match &config.persona_data_dir {
Some(dir) => {
let custom_template = dir.join("metaprompt-template.hbs");
if custom_template.exists() {
info!(path = %custom_template.display(), "using custom metaprompt template");
MetapromptRenderer::from_template_file(&custom_template).unwrap_or_else(|e| {
warn!(path = %custom_template.display(), error = %e, "failed to load custom template, using default");
MetapromptRenderer::new().expect("default template should always compile")
})
} else {
MetapromptRenderer::new().expect("default template should always compile")
}
}
None => MetapromptRenderer::new().expect("default template should always compile"),
};
// Initialize output poster. In multi-project mode this wires one
// tracker per project plus a legacy fallback from `config.gitea`; in
// legacy single-project mode it collapses to the top-level config.
let output_poster = OutputPoster::from_orchestrator_config(&config);
// Initialize KG router from taxonomy directory if configured
let kg_router = config.routing.as_ref().and_then(|routing_config| {
match kg_router::KgRouter::load(&routing_config.taxonomy_path) {
Ok(router) => {
info!(
path = %routing_config.taxonomy_path.display(),
rules = router.rule_count(),
"KG model router loaded"
);
Some(router)
}
Err(e) => {
warn!(error = %e, "KG router failed to load, using static model config");
None
}
}
});
let probe_ttl = config
.routing
.as_ref()
.map(|r| r.probe_ttl_secs)
.unwrap_or(300);
let provider_health =
provider_probe::ProviderHealthMap::new(std::time::Duration::from_secs(probe_ttl))
.with_rate_limiter(crate::rate_limiter::RateLimiter::new());
let telemetry_store = control_plane::TelemetryStore::new(3600);
let provider_budget_tracker = build_provider_budget_tracker(&config)?;
// Compile per-provider stderr signatures declared under
// `[[providers]].error_signatures`. Invalid regexes fail loud
// at startup so misconfiguration can never silently disable
// runtime classification.
let provider_error_signatures = error_signatures::build_signature_map(&config.providers)
.map_err(|e| OrchestratorError::Config(e.to_string()))?;
let project_failure_counter =
project_control::ProjectFailureCounter::new(config.project_circuit_breaker_threshold);
let pause_dir = config
.pause_dir
.clone()
.unwrap_or_else(|| PathBuf::from(project_control::DEFAULT_PAUSE_DIR));
#[cfg(not(test))]
let restart_state = Self::load_restart_state();
let learning_config = config.learning.clone();
// MentionCursor loaded lazily on first poll (async)
Ok(Self {
config: config.clone(),
spawner,
router,
nightwatch,
scheduler,
compound_workflow,
active_agents: HashMap::new(),
rate_limiter: RateLimitTracker::default(),
shutdown_requested: false,
restart_counts: {
#[cfg(not(test))]
{
flatten_restart_counts(&restart_state)
}
#[cfg(test)]
{
HashMap::new()
}
},
restart_last_failure_unix_secs: {
#[cfg(not(test))]
{
flatten_restart_failures(&restart_state)
}
#[cfg(test)]
{
HashMap::new()
}
},
restart_cooldowns: HashMap::new(),
last_tick_time: chrono::Utc::now(),
handoff_buffer,
handoff_ledger,
cost_tracker,
persona_registry,
metaprompt_renderer,
output_poster,
circuit_breakers: Arc::new(Mutex::new(HashMap::new())),
last_run_commits: HashMap::new(),
last_cron_fire: HashMap::new(),
last_compound_review_fired_at: None,
pre_check_tracker: None,
active_flows: HashMap::new(),
mention_cursors: HashMap::new(),
webhook_dispatch_rx: None,
tick_count: 0,
#[cfg(feature = "quickwit")]
quickwit_sink: None,
exit_classifier: ExitClassifier::new(),
kg_router,
provider_health,
telemetry_store,
provider_budget_tracker,
provider_error_signatures,
provider_rate_limits: ProviderRateLimitWindow::new(),
retry_counts: HashMap::new(),
unknown_error_dedupe: Arc::new(Mutex::new(std::collections::HashSet::new())),
project_failure_counter,
pause_dir,
dispatcher: dispatcher::Dispatcher::new(),
pr_poll_rate_limiter: pr_poller::PrPollRateLimiter::new(
pr_poller::PR_POLL_MIN_INTERVAL,
),
auto_merge_enqueued: pr_poller::AutoMergeDedupeSet::new(),
auto_merge_failure_dedupe: pr_poller::AutoMergeFailureDedupe::new(
std::time::Duration::from_secs(86400),
),
learning_store: None,
learning_config,
injected_learning_ids: HashMap::new(),
concurrency_controller: build_concurrency_controller(&config),
agent_log_dir: {
let adf_logs = std::path::PathBuf::from("/opt/ai-dark-factory/logs/agents");
if adf_logs.parent().map(|p| p.exists()).unwrap_or(false) {
adf_logs
} else {
config.working_dir.join("logs").join("agents")
}
},
gitea_skill_cache_dir: None,
evolution_manager: evolution::EvolutionManager::new(config.evolution.clone()),
config_error_counters: HashMap::new(),
quarantined_agents: std::collections::HashSet::new(),
})
}
/// Load persisted restart state from a JSON file in the temp directory.
/// Falls back to the legacy `HashMap<String, u32>` format for compatibility.
#[cfg(not(test))]
fn load_restart_state() -> PersistedRestartState {
let path = std::env::temp_dir().join("adf_restart_counts.json");
match std::fs::read_to_string(&path) {
Ok(json) => {
if let Ok(state) = serde_json::from_str::<PersistedRestartState>(&json) {
state
} else if let Ok(counts) = serde_json::from_str::<HashMap<String, u32>>(&json) {
PersistedRestartState {
counts,
..Default::default()
}
} else {
PersistedRestartState::default()
}
}
Err(_) => PersistedRestartState::default(),
}
}
/// Persist restart state so it survives orchestrator restarts.
fn save_restart_state(&self) {
// Skip persistence in test builds to avoid cross-test contamination
#[cfg(test)]
return;
#[cfg(not(test))]
{
let path = std::env::temp_dir().join("adf_restart_counts.json");
let state = PersistedRestartState {
counts_by_project: nest_by_project(&self.restart_counts),
last_failure_unix_secs_by_project: nest_by_project(
&self.restart_last_failure_unix_secs,
),
counts: HashMap::new(),
last_failure_unix_secs: HashMap::new(),
};
if let Ok(json) = serde_json::to_string(&state) {
if let Err(e) = std::fs::write(&path, json) {
warn!(error = %e, "failed to persist restart state");
}
}
}
}
fn restart_budget_window_secs(&self) -> i64 {
self.config.restart_budget_window_secs as i64
}
/// Open a temp log file for an agent and spawn a background task that
/// continuously drains its output broadcast into the file. Returns the
/// temp-file path so it can be renamed to the final name on exit.
fn start_output_log_drain(&self, agent_name: &str, handle: &AgentHandle) -> Option<PathBuf> {
let _ = std::fs::create_dir_all(&self.agent_log_dir);
let ts = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
let tmp_name = format!(".tmp-{}-{}.log", agent_name, ts);
let tmp_path = self.agent_log_dir.join(&tmp_name);
let file = match std::fs::File::create(&tmp_path) {
Ok(f) => f,
Err(e) => {
warn!(agent = %agent_name, error = %e, "failed to create output log temp file");
return None;
}
};
let mut rx = handle.subscribe_output();
let name = agent_name.to_string();
let path = tmp_path.clone();
tokio::spawn(async move {
use std::io::Write;
let mut writer = std::io::BufWriter::new(file);
loop {
match rx.recv().await {
Ok(event) => match &event {
crate::OutputEvent::Stdout { line, .. } => {
let _ = writeln!(writer, "{}", line);
}
crate::OutputEvent::Stderr { line, .. } => {
let _ = writeln!(writer, "[stderr] {}", line);
}
_ => {}
},
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
let _ = writeln!(writer, "[... {} output lines dropped ...]", n);
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
break;
}
}
}
let _ = writer.flush();
debug!(agent = %name, path = %path.display(), "output log drain finished");
});
Some(tmp_path)
}
fn current_restart_count(&mut self, key: &(String, String)) -> u32 {
let now = chrono::Utc::now().timestamp();
let window = self.restart_budget_window_secs();
let last_failure = self.restart_last_failure_unix_secs.get(key).copied();
if let Some(last) = last_failure {
if now.saturating_sub(last) > window {
self.restart_counts.remove(key);
self.restart_last_failure_unix_secs.remove(key);
self.save_restart_state();
}
}
self.restart_counts.get(key).copied().unwrap_or(0)
}
fn increment_restart_count(&mut self, key: &(String, String)) -> u32 {
let _ = self.current_restart_count(key);
let next_count = {
let count = self.restart_counts.entry(key.clone()).or_insert(0);
*count += 1;
*count
};
self.restart_last_failure_unix_secs
.insert(key.clone(), chrono::Utc::now().timestamp());
self.save_restart_state();
next_count
}
/// Check disk usage percentage for the root filesystem.
/// Returns None if the check fails (non-Linux, command error, etc.).
fn check_disk_usage_percent() -> Option<u8> {
let output = std::process::Command::new("df")
.args(["--output=pcent", "/"])
.output()
.ok()?;
let stdout = String::from_utf8_lossy(&output.stdout);
// Output format: "Use%\n 86%\n"
for line in stdout.lines().skip(1) {
let trimmed = line.trim().trim_end_matches('%');
if let Ok(pct) = trimmed.parse::<u8>() {
return Some(pct);
}
}
None
}
/// Create from a TOML config file path.
///
/// Loads the config, resolves include globs, and runs full validation
/// (banned providers, duplicate project ids, unknown project refs, mixed
/// mode). Returns `Err` if any check fails -- does not panic or warn-and-
/// continue.
pub fn from_config_file(path: impl AsRef<Path>) -> Result<Self, OrchestratorError> {
let config = OrchestratorConfig::load_and_validate(path)?;
Self::new(config)
}
/// Return the validated configuration stored in this orchestrator.
pub fn config(&self) -> &OrchestratorConfig {
&self.config
}
/// Read-only access to the unified dispatcher queue.
///
/// Integration tests use this to assert that ROC v1 Step F polling
/// enqueued the expected [`dispatcher::DispatchTask::AutoMerge`] work without the
/// test itself holding a reference to the internal dispatcher.
pub fn dispatcher(&self) -> &dispatcher::Dispatcher {
&self.dispatcher
}
/// Read-only access to the in-memory `(project, pr_number, head_sha)`
/// dedupe set populated by ROC v1 Step F polling and the Step G
/// AutoMerge handler. Integration tests use this to assert that a
/// successful merge leaves the revision recorded so subsequent polls
/// never re-enqueue the same auto-merge.
pub fn auto_merge_enqueued(&self) -> &pr_poller::AutoMergeDedupeSet {
&self.auto_merge_enqueued
}
/// Run the orchestrator (blocks until shutdown signal).
///
/// 1. Spawns all Safety-layer agents immediately
/// 2. Enters the select! loop handling schedule events, drift alerts, and periodic tick
pub async fn run(&mut self) -> Result<(), OrchestratorError> {
info!(
"starting orchestrator with {} agent definitions",
self.config.agents.len()
);
// D-2: Run provider probes on startup if configured
if self
.config
.routing
.as_ref()
.is_some_and(|r| r.probe_on_startup)
{
if let Some(ref kg_router) = self.kg_router {
info!("running startup provider probe via KG action:: templates");
self.provider_health.probe_all(kg_router).await;
// Save probe results if directory configured
if let Some(ref dir) = self
.config
.routing
.as_ref()
.and_then(|r| r.probe_results_dir.clone())
{
if let Err(e) = self.provider_health.save_results(dir).await {
warn!(error = %e, "failed to save probe results");
}
}
// Send probe results to Quickwit for cost-aware routing
if let Some(ref sink) = self.quickwit_sink {
let project_id = self
.config
.projects
.first()
.map(|p| p.id.clone())
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string());
self.provider_health
.send_to_quickwit(sink, &project_id)
.await;
}
}
}
// Restore persisted telemetry from previous runs
self.restore_telemetry().await;
// Populate Gitea skill cache if configured (issue #1434).
// On success, the cache dir becomes the first skill root.
// On any error, populate_skill_cache logs a warning and returns the
// cache dir path anyway; local skill roots are used as fallback.
if let Some(ref skill_repo) = self.config.gitea_skill_repo.clone() {
let cache_dir = gitea_skill_loader::populate_skill_cache(skill_repo, false).await;
self.gitea_skill_cache_dir = Some(cache_dir);
}
// One-shot migration of the legacy top-level `adf/mention_cursor`
// key into per-project keys. No-op after the first successful
// startup.
mention::migrate_legacy_mention_cursor(&self.config.projects).await;
// Spawn Safety-layer agents immediately
let immediate = self.scheduler.immediate_agents();
for agent_def in &immediate {
if let Err(e) = self.spawn_agent(agent_def).await {
error!(agent = %agent_def.name, error = %e, "failed to spawn safety agent");
}
}
info!(
safety_agents = immediate.len(),
active = self.active_agents.len(),
"safety agents spawned, entering reconciliation loop"
);
// Start webhook server if configured
if let Some(ref webhook_cfg) = self.config.webhook {
let (dispatch_tx, dispatch_rx) = tokio::sync::mpsc::channel(64);
self.webhook_dispatch_rx = Some(dispatch_rx);
let agent_names: Vec<String> =
self.config.agents.iter().map(|a| a.name.clone()).collect();
let project_by_repo: std::collections::HashMap<String, String> = self
.config
.projects
.iter()
.filter_map(|p| {
p.gitea
.as_ref()
.map(|g| (format!("{}/{}", g.owner, g.repo), p.id.clone()))
})
.collect();
let state = webhook::WebhookState {
agent_names,
persona_registry: Arc::new(self.persona_registry.clone()),
dispatch_tx,
secret: webhook_cfg.secret.clone(),
project_by_repo,
};
let router = webhook::webhook_router(state);
let bind = webhook_cfg.bind.clone();
tokio::spawn(async move {
let listener = match tokio::net::TcpListener::bind(&bind).await {
Ok(l) => l,
Err(e) => {
error!(bind = %bind, error = %e, "failed to bind webhook server");
return;
}
};
info!(bind = %bind, "webhook server listening");
if let Err(e) = axum::serve(listener, router).await {
error!(error = %e, "webhook server error");
}
});
}
enum LoopEvent {
Tick,
Schedule(ScheduleEvent),
DriftAlert(DriftAlert),
Webhook(webhook::WebhookDispatch),
}
let tick_interval = self.config.tick_interval_secs;
let (loop_tx, loop_rx) = std::sync::mpsc::channel::<LoopEvent>();
let loop_tx = Arc::new(std::sync::Mutex::new(loop_tx));
let sched_tx = loop_tx.clone();
let sched_rx = self.scheduler.take_event_rx();
if let Some(rx) = sched_rx {
tokio::spawn(async move {
let mut rx = rx;
while let Some(event) = rx.recv().await {
if sched_tx
.lock()
.unwrap()
.send(LoopEvent::Schedule(event))
.is_err()
{
break;
}
}
});
}
let alert_tx = loop_tx.clone();
let alert_rx = self.nightwatch.take_alert_rx();
if let Some(rx) = alert_rx {
tokio::spawn(async move {
let mut rx = rx;
while let Some(alert) = rx.recv().await {
if alert_tx
.lock()
.unwrap()
.send(LoopEvent::DriftAlert(alert))
.is_err()
{
break;
}
}
});
}
let tick_stx = loop_tx.clone();
let tick_interval_secs = tick_interval;
std::thread::spawn(move || loop {
std::thread::sleep(std::time::Duration::from_secs(tick_interval_secs));
if tick_stx.lock().unwrap().send(LoopEvent::Tick).is_err() {
break;
}
});
let webhook_rx = self.webhook_dispatch_rx.take();
if let Some(rx) = webhook_rx {
let wh_tx = loop_tx.clone();
tokio::spawn(async move {
let mut rx = rx;
while let Some(dispatch) = rx.recv().await {
if wh_tx
.lock()
.unwrap()
.send(LoopEvent::Webhook(dispatch))
.is_err()
{
break;
}
}
});
}
let reconcile_timeout = Duration::from_secs(self.config.tick_interval_secs.max(30) * 3);
loop {
if self.shutdown_requested {
info!("shutdown requested, stopping reconciliation loop");
break;
}
match loop_rx.recv_timeout(reconcile_timeout) {
Ok(LoopEvent::Webhook(dispatch)) => {
let comment_id = dispatch.comment_id();
self.handle_webhook_dispatch(dispatch).await;
self.mark_webhook_comment_processed(comment_id).await;
let _ = loop_tx.lock().unwrap().send(LoopEvent::Tick);
}
Ok(LoopEvent::Schedule(event)) => {
self.handle_schedule_event(event).await;
}
Ok(LoopEvent::DriftAlert(alert)) => {
self.handle_drift_alert(alert).await;
}
Ok(LoopEvent::Tick) => {
loop {
match loop_rx.try_recv() {
Ok(LoopEvent::Webhook(dispatch)) => {
let comment_id = dispatch.comment_id();
self.handle_webhook_dispatch(dispatch).await;
self.mark_webhook_comment_processed(comment_id).await;
}
Ok(LoopEvent::Schedule(event)) => {
self.handle_schedule_event(event).await;
}
Ok(LoopEvent::DriftAlert(alert)) => {
self.handle_drift_alert(alert).await;
}
Ok(LoopEvent::Tick) => {
// Coalesce stale ticks so long reconciliation runs do not
// starve webhook and schedule events queued behind them.
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
}
}
match tokio::time::timeout(reconcile_timeout, self.reconcile_tick()).await {
Ok(()) => {}
Err(_) => {
warn!(
timeout_secs = reconcile_timeout.as_secs(),
"reconcile_tick exceeded timeout, forcing continuation"
);
}
}
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
warn!("loop: recv timeout, no events received");
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
info!("all event sources closed, exiting loop");
break;
}
}
}
// Graceful shutdown of all agents
self.persist_telemetry();
if let Some(tracker) = self.provider_budget_tracker.as_ref() {
if let Err(e) = tracker.persist() {
warn!(error = %e, "failed to persist provider budget snapshot during shutdown");
}
}
self.shutdown_all_agents().await;
Ok(())
}
/// Request graceful shutdown of all agents and the orchestrator.
pub fn shutdown(&mut self) {
info!("shutdown requested");
self.shutdown_requested = true;
}
async fn mark_webhook_comment_processed(&mut self, comment_id: u64) {
let project_ids: Vec<String> = if self.config.projects.is_empty() {
vec![dispatcher::LEGACY_PROJECT_ID.to_string()]
} else {
self.config.projects.iter().map(|p| p.id.clone()).collect()
};
for pid in &project_ids {
let cursor = self
.mention_cursors
.entry(pid.clone())
.or_insert_with(mention::MentionCursor::now);
cursor.mark_processed(comment_id);
}
for pid in &project_ids {
if let Some(cursor) = self.mention_cursors.get(pid) {
cursor.save(pid).await;
}
}
}
/// Get current status of all agents.
pub fn agent_statuses(&self) -> Vec<AgentStatus> {
self.active_agents
.values()
.map(|managed| {
let drift = self.nightwatch.drift_score(&managed.definition.name);
AgentStatus {
name: managed.definition.name.clone(),
layer: managed.definition.layer,
running: true,
health: managed.handle.health_status(),
drift_score: drift.map(|d| d.score),
uptime: managed.started_at.elapsed(),
restart_count: managed.restart_count,
api_calls_remaining: HashMap::new(),
}
})
.collect()
}
/// Manually trigger a compound review (outside normal schedule).
pub async fn trigger_compound_review(
&mut self,
git_ref: &str,
base_ref: &str,
) -> Result<CompoundReviewResult, OrchestratorError> {
info!("triggering manual compound review");
self.compound_workflow.run(git_ref, base_ref).await
}
/// Hand off a task from one agent to another.
pub async fn handoff(
&mut self,
from_agent: &str,
to_agent: &str,
context: HandoffContext,
) -> Result<(), OrchestratorError> {
// Validate agent names for path safety (prevents path traversal)
validate_agent_name(from_agent)?;
validate_agent_name(to_agent)?;
// Validate context fields match parameters
if context.from_agent != from_agent || context.to_agent != to_agent {
return Err(OrchestratorError::HandoffFailed {
from: from_agent.to_string(),
to: to_agent.to_string(),
reason: format!(
"context field mismatch: context.from_agent='{}', context.to_agent='{}'",
context.from_agent, context.to_agent
),
});
}
if !self.active_agents.contains_key(from_agent) {
return Err(OrchestratorError::AgentNotFound(from_agent.to_string()));
}
// Find the target agent definition
let to_def = self
.config
.agents
.iter()
.find(|a| a.name == to_agent)
.cloned()
.ok_or_else(|| OrchestratorError::AgentNotFound(to_agent.to_string()))?;
// If target isn't running, spawn it
if !self.active_agents.contains_key(to_agent) {
self.spawn_agent(&to_def).await?;
}
// Write handoff context to file for the target agent
let handoff_path = self
.config
.working_dir
.join(format!(".handoff-{}.json", to_agent));
context
.write_to_file(&handoff_path)
.map_err(|e| OrchestratorError::HandoffFailed {
from: from_agent.to_string(),
to: to_agent.to_string(),
reason: e.to_string(),
})?;
// Insert into in-memory buffer for fast retrieval
let handoff_id = self.handoff_buffer.insert(context.clone());
// Append to persistent ledger
self.handoff_ledger
.append(&context)
.map_err(|e| OrchestratorError::HandoffFailed {
from: from_agent.to_string(),
to: to_agent.to_string(),
reason: format!("ledger append failed: {}", e),
})?;
info!(
from = from_agent,
to = to_agent,
handoff_file = %handoff_path.display(),
handoff_id = %handoff_id,
"handoff context written"
);
Ok(())
}
/// Get the most recent handoff for a specific target agent.
/// Returns the handoff context with the latest timestamp that hasn't expired.
pub fn latest_handoff_for(&self, to_agent: &str) -> Option<&HandoffContext> {
self.handoff_buffer.latest_for_agent(to_agent)
}
/// Get a reference to the routing engine.
pub fn router(&self) -> &RoutingEngine {
&self.router
}
/// Get a mutable reference to the routing engine.
pub fn router_mut(&mut self) -> &mut RoutingEngine {
&mut self.router
}
/// Get a reference to the rate limiter.
pub fn rate_limiter(&self) -> &RateLimitTracker {
&self.rate_limiter
}
/// Get a mutable reference to the rate limiter.
pub fn rate_limiter_mut(&mut self) -> &mut RateLimitTracker {
&mut self.rate_limiter
}
/// Get a reference to the cost tracker.
pub fn cost_tracker(&self) -> &CostTracker {
&self.cost_tracker
}
/// Get a mutable reference to the cost tracker.
pub fn cost_tracker_mut(&mut self) -> &mut CostTracker {
&mut self.cost_tracker
}
#[cfg(feature = "quickwit")]
pub fn set_quickwit_sink(&mut self, sink: quickwit::QuickwitFleetSink) {
self.quickwit_sink = Some(sink);
}
#[cfg(feature = "quickwit")]
pub fn quickwit_config(&self) -> Option<&QuickwitConfig> {
self.config.quickwit.as_ref()
}
/// Enumerate per-project Quickwit configurations plus a legacy fallback
/// for the top-level config, so the binary can build a
/// [`quickwit::QuickwitFleetSink`] covering every project.
///
/// Returns `(project_id, QuickwitConfig)` pairs. Projects without a
/// per-project Quickwit block inherit the top-level config. The legacy
/// single-project path emits a single entry keyed on
/// [`crate::dispatcher::LEGACY_PROJECT_ID`].
#[cfg(feature = "quickwit")]
pub fn quickwit_fleet_configs(&self) -> Vec<(String, QuickwitConfig)> {
let mut out: Vec<(String, QuickwitConfig)> = Vec::new();
for project in &self.config.projects {
if let Some(cfg) = project
.quickwit
.as_ref()
.or(self.config.quickwit.as_ref())
.cloned()
{
if cfg.enabled {
out.push((project.id.clone(), cfg));
}
}
}
if self.config.projects.is_empty() {
if let Some(cfg) = self.config.quickwit.as_ref().cloned() {
if cfg.enabled {
out.push((crate::dispatcher::LEGACY_PROJECT_ID.to_string(), cfg));
}
}
}
out
}
/// Load skill chain content from skill definition files for the given agent definition.
///
/// Reads each skill named in `def.skill_chain` from `{skill_data_dir}/{name}/SKILL.md`.
/// If that path is missing, it falls back to `skill.md` and well-known HOME skill roots
/// (`~/.opencode/skills`, then `~/.claude/skills`). Returns a formatted string with all
/// skill contents, or empty string if no skills can be loaded.
fn load_skill_chain_content(&self, def: &AgentDefinition) -> String {
if def.skill_chain.is_empty() {
return String::new();
}
let home_dir = std::env::var("HOME").ok().map(std::path::PathBuf::from);
let skill_roots = Self::skill_roots(
self.config.skill_data_dir.as_deref(),
home_dir.as_deref(),
self.gitea_skill_cache_dir.as_deref(),
);
if skill_roots.is_empty() {
return String::new();
}
let mut sections = Vec::new();
for skill_name in &def.skill_chain {
let mut selected_path = None;
let mut content = None;
for root in &skill_roots {
let skill_dir = root.join(skill_name);
let candidates = [skill_dir.join("SKILL.md"), skill_dir.join("skill.md")];
for candidate in candidates {
match std::fs::read_to_string(&candidate) {
Ok(raw) => {
selected_path = Some(candidate);
content = Some(raw);
break;
}
Err(_) => continue,
}
}
if content.is_some() {
break;
}
}
match content {
Some(content) => {
// Strip YAML frontmatter (between --- markers) to keep just instructions
let body = if let Some(after_prefix) = content.strip_prefix("---") {
if let Some(end) = after_prefix.find("---") {
after_prefix[end + 3..].trim_start().to_string()
} else {
content
}
} else {
content
};
sections.push(format!("### Skill: {}\n\n{}", skill_name, body.trim()));
info!(
agent = %def.name,
skill = %skill_name,
path = %selected_path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "unknown".to_string()),
bytes = body.len(),
"loaded skill content"
);
}
None => {
let tried: Vec<String> = skill_roots
.iter()
.flat_map(|root| {
let skill_dir = root.join(skill_name);
[
skill_dir.join("SKILL.md").display().to_string(),
skill_dir.join("skill.md").display().to_string(),
]
})
.collect();
warn!(
agent = %def.name,
skill = %skill_name,
tried = ?tried,
"failed to load skill, skipping"
);
}
}
}
if sections.is_empty() {
return String::new();
}
format!(
"\n\n## Active Skills\n\nApply the following skill instructions to your work:\n\n{}\n",
sections.join("\n\n---\n\n")
)
}
fn render_lessons_section(&self, agent_name: &str) -> (String, Vec<String>) {
let store = match self.learning_store {
Some(ref s) => s,
None => return (String::new(), Vec::new()),
};
let learnings = match tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(store.query_relevant(agent_name))
}) {
Ok(l) => l,
Err(e) => {
warn!(agent = %agent_name, error = %e, "failed to query learnings");
return (String::new(), Vec::new());
}
};
if learnings.is_empty() {
return (String::new(), Vec::new());
}
let max_entries = self.learning_config.max_entries;
let max_tokens = self.learning_config.max_tokens;
let truncated: Vec<_> = learnings.into_iter().take(max_entries).collect();
let ids: Vec<String> = truncated.iter().map(|l| l.id.clone()).collect();
let mut section = String::from("## Prior Lessons\n\nLessons learned from previous agent runs. Apply relevant insights:\n\n");
for l in &truncated {
section.push_str(&format!(
"- [{}] {} (trust: {}, verified {}x)\n",
l.category, l.summary, l.trust_level, l.effective_count
));
if let Some(ref details) = l.details {
if let Some(first_line) = details.lines().next() {
section.push_str(&format!(" > {}\n", first_line));
}
}
}
if section.len() > max_tokens {
let mut end = max_tokens;
while end > 0 && !section.is_char_boundary(end) {
end -= 1;
}
section.truncate(end);
section.push_str("\n... (truncated)\n");
}
(section, ids)
}
/// Build the ordered list of directories to search for SKILL.md files.
///
/// Priority (highest first):
/// 1. Gitea skill cache dir (populated at startup from remote, if configured)
/// 2. Configured `skill_data_dir` from TOML
/// 3. `~/.opencode/skills`
/// 4. `~/.claude/skills`
fn skill_roots(
configured: Option<&std::path::Path>,
home_dir: Option<&std::path::Path>,
gitea_cache: Option<&std::path::Path>,
) -> Vec<std::path::PathBuf> {
let mut roots = Vec::new();
// Remote skills take priority — operators push updates to Gitea
// without modifying local files.
if let Some(dir) = gitea_cache {
roots.push(dir.to_path_buf());
}
if let Some(dir) = configured {
if !roots.iter().any(|r| r == dir) {
roots.push(dir.to_path_buf());
}
}
if let Some(home) = home_dir {
for root in [
home.join(".opencode").join("skills"),
home.join(".claude").join("skills"),
] {
if !roots.iter().any(|existing| existing == &root) {
roots.push(root);
}
}
}
roots
}
/// Spawn an agent from its definition.
///
/// Model selection: if the agent has an explicit `model` field, use it.
/// Otherwise, route the task prompt through the RoutingEngine to select
/// a model based on keyword matching.
async fn spawn_agent(&mut self, def: &AgentDefinition) -> Result<(), OrchestratorError> {
// === PROJECT PAUSE GATE ===
// Operators and the project circuit breaker can block all dispatches
// for a given project by creating a sentinel file at
// `<pause_dir>/<project_id>`. The gate is project-scoped; legacy /
// global agents (`def.project == None`) are never blocked here.
if project_control::is_project_paused(&self.pause_dir, def.project.as_deref()) {
info!(
agent = %def.name,
project = ?def.project,
pause_dir = %self.pause_dir.display(),
"skipping spawn: project is paused"
);
return Ok(());
}
// === DISK SPACE GUARD ===
let threshold = self.config.disk_usage_threshold;
if threshold < 100 {
if let Some(usage) = Self::check_disk_usage_percent() {
if usage >= threshold {
error!(
agent = %def.name,
disk_usage_percent = usage,
threshold,
"refusing to spawn agent: disk usage above threshold"
);
return Err(OrchestratorError::Config(format!(
"disk usage {}% >= {}% threshold, refusing to spawn {}",
usage, threshold, def.name
)));
}
}
}
// === BUDGET GATE ===
// Skip spawn entirely if the agent's monthly budget is exhausted.
// CostTracker::check is already called during routing (for budget
// pressure scoring), but routing only deprioritises cheaper models;
// it does not short-circuit dispatch. A fully exhausted agent must
// not run at all this cycle.
let budget_check = self.cost_tracker.check(&def.name);
if budget_check.should_pause() {
warn!(
agent = %def.name,
verdict = %budget_check,
"skipping spawn: monthly budget exhausted"
);
return Ok(());
}
if budget_check.should_warn() {
warn!(
agent = %def.name,
verdict = %budget_check,
"budget near exhaustion; routing will prefer cheaper models"
);
}
// === PRE-CHECK GATE ===
let pre_check_result = self.run_pre_check(def).await;
let findings = match pre_check_result {
PreCheckResult::NoFindings => {
info!(agent = %def.name, "skipping spawn: pre-check found nothing actionable");
return Ok(());
}
PreCheckResult::Findings(f) if f.is_empty() => None,
PreCheckResult::Findings(f) => Some(f),
PreCheckResult::Failed(reason) => {
warn!(agent = %def.name, reason = %reason,
"pre-check failed, spawning anyway (fail-open)");
None
}
};
// Select model via keyword routing or explicit config.
// Skip keyword routing for CLIs that use OAuth and don't support -m
// (e.g. codex with ChatGPT account). Only apply routed models when the
// CLI tool is known to accept --model flags with arbitrary model IDs.
let cli_name = std::path::Path::new(&def.cli_tool)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&def.cli_tool);
let supports_model_flag = matches!(cli_name, "claude" | "claude-code" | "opencode");
// Track KG decision for CLI override (set inside the routing block below)
let mut kg_cli_override: Option<String> = None;
#[allow(clippy::manual_let_else)]
let model = if self
.config
.routing
.as_ref()
.is_some_and(|r| r.use_routing_engine)
{
let kg_arc = self
.kg_router
.as_ref()
.map(|r| std::sync::Arc::new(r.clone()));
let unhealthy = self.provider_health.unhealthy_providers();
let telemetry_arc = std::sync::Arc::new(self.telemetry_store.clone());
let strategy = self
.config
.routing
.as_ref()
.map(|r| r.route_selection_strategy)
.unwrap_or(crate::control_plane::RouteSelectionStrategy::Fastest);
let engine = control_plane::RoutingDecisionEngine::with_provider_budget_and_strategy(
kg_arc,
unhealthy,
terraphim_router::Router::new(),
Some(telemetry_arc),
self.provider_budget_tracker.clone(),
strategy,
);
let ctx = control_plane::DispatchContext {
agent_name: def.name.clone(),
task: def.task.clone(),
static_model: def.model.clone(),
cli_tool: def.cli_tool.clone(),
layer: def.layer,
session_id: None,
};
let budget_verdict = self.cost_tracker.check(&def.name);
let decision = engine.decide_route(&ctx, &budget_verdict).await;
info!(
agent = %def.name,
rationale = %decision.rationale,
telemetry_influenced = decision.telemetry_influenced,
"routing engine selected model"
);
if decision.candidate.model.is_empty() {
None
} else {
// Extract CLI tool override from routing decision so that
// anthropic models routed via KG use claude CLI, not opencode.
if decision.candidate.cli_tool != def.cli_tool {
kg_cli_override = Some(decision.candidate.cli_tool.clone());
}
Some(decision.candidate.model)
}
} else if supports_model_flag && def.bypass_kg_routing {
// Fallback respawn (quota exit, wall-clock timeout, or KG-fallback
// route already selected): the caller has explicitly chosen
// `cli_tool` and `model`, and re-running KG tier routing here
// would override their decision and route the spawn back to the
// just-blocked primary. Honour the static config verbatim.
info!(
agent = %def.name,
"bypassing KG tier routing per agent definition (fallback respawn)"
);
def.model.clone()
} else if supports_model_flag {
// KG routing first (phase-aware tier selection from markdown rules).
// Takes priority over static model config so tier routing controls selection.
let mut unhealthy = self.provider_health.unhealthy_providers();
unhealthy.extend(self.provider_rate_limits.blocked_providers());
let kg_decision = self.kg_router.as_ref().and_then(|router| {
let decision = router.route_agent(&def.task)?;
// If primary provider is unhealthy, try fallback routes
if !unhealthy.is_empty() {
if let Some(healthy_route) = decision.first_healthy_route(&unhealthy) {
info!(
agent = %def.name,
concept = %decision.matched_concept,
provider = %healthy_route.provider,
model = %healthy_route.model,
skipped_unhealthy = ?unhealthy,
"KG routed to fallback (primary unhealthy)"
);
return Some(kg_router::KgRouteDecision {
provider: healthy_route.provider.clone(),
model: healthy_route.model.clone(),
action: healthy_route.action.clone(),
confidence: decision.confidence * 0.9,
matched_concept: decision.matched_concept,
priority: decision.priority,
fallback_routes: decision.fallback_routes,
});
}
}
Some(decision)
});
if let Some(ref kg) = kg_decision {
info!(
agent = %def.name,
concept = %kg.matched_concept,
provider = %kg.provider,
model = %kg.model,
confidence = kg.confidence,
"model selected via KG tier routing"
);
// Extract CLI tool from action template (first word = CLI path)
if let Some(ref action) = kg.action {
if let Some(cli) = action.split_whitespace().next() {
kg_cli_override = Some(cli.to_string());
}
}
Some(kg.model.clone())
} else if let Some(m) = &def.model {
// Static config fallback when KG has no match
info!(agent = %def.name, model = %m, "using static model (no KG tier match)");
Some(m.clone())
} else {
// Fall back to keyword routing engine
let context = terraphim_router::RoutingContext::default();
match self.router.route(&def.task, &context) {
Ok(decision) => {
if let terraphim_types::capability::ProviderType::Llm { model_id, .. } =
&decision.provider.provider_type
{
info!(
agent = %def.name,
model = %model_id,
confidence = decision.confidence,
"model selected via keyword routing"
);
Some(model_id.clone())
} else {
None
}
}
Err(_) => {
info!(agent = %def.name, "no model matched, using CLI default");
None
}
}
}
} else {
info!(agent = %def.name, cli = %def.cli_tool, "skipping model routing (CLI uses OAuth/default)");
None
};
// For opencode, compose "provider/model" format when both fields are set.
// opencode requires `-m provider/model` whereas the TOML config stores them
// separately (provider = "kimi-for-coding", model = "k2p5").
// Skip composition if the model already contains a provider prefix (e.g.
// from KG routing which returns full model ids like "kimi-for-coding/k2p5").
let model = if cli_name == "opencode" {
match (&def.provider, &model) {
(Some(provider), Some(m)) if !m.contains('/') => {
let composed = format!("{}/{}", provider, m);
info!(agent = %def.name, composed_model = %composed, "composed provider/model for opencode");
Some(composed)
}
_ => model,
}
} else {
model
};
// If KG routing selected a different CLI tool (e.g., claude instead of opencode),
// use the KG-selected CLI to match the routed model.
let effective_cli = kg_cli_override
.as_deref()
.unwrap_or(&def.cli_tool)
.to_string();
info!(agent = %def.name, layer = ?def.layer, cli = %effective_cli, model = ?model, "spawning agent");
// Compose persona-enriched task prompt
let (composed_task, persona_found) = if let Some(ref persona_name) = def.persona {
if let Some(persona) = self.persona_registry.get(persona_name) {
let composed = self.metaprompt_renderer.compose_prompt(persona, &def.task);
info!(
agent = %def.name,
persona = %persona_name,
original_len = def.task.len(),
composed_len = composed.len(),
"composed persona-enriched prompt"
);
(composed, true)
} else {
warn!(
agent = %def.name,
persona = %persona_name,
"persona not found in registry, using bare task"
);
(def.task.clone(), false)
}
} else {
(def.task.clone(), false)
};
// === FINDINGS INJECTION ===
let composed_task = if let Some(ref findings) = findings {
format!(
"## Pre-flight findings (automated checks already ran)\n\n{}\n\n---\n\n{}",
findings, composed_task
)
} else {
composed_task
};
// Inject skill_chain content between persona preamble and task
let skill_content = self.load_skill_chain_content(def);
let composed_task = if skill_content.is_empty() {
composed_task
} else {
info!(
agent = %def.name,
skills = def.skill_chain.len(),
skill_bytes = skill_content.len(),
"injecting skill_chain into prompt"
);
format!("{}{}", composed_task, skill_content)
};
// Inject prior lessons from shared learning store
let (lessons_section, lesson_ids) = self.render_lessons_section(&def.name);
let mut composed_task = if lessons_section.is_empty() {
composed_task
} else {
info!(
agent = %def.name,
lessons = lesson_ids.len(),
"injecting prior lessons into prompt"
);
self.injected_learning_ids
.insert(def.name.clone(), lesson_ids);
format!("{}\n\n{}", composed_task, lessons_section)
};
// Inject evolution memory context if enabled for this agent.
if def.evolution_enabled && self.evolution_manager.is_enabled() {
self.evolution_manager.ensure_agent(&def.name);
let _ = self
.evolution_manager
.record_task_start(&def.name, &def.task);
let evo_ctx = self.evolution_manager.render_context(&def.name);
if !evo_ctx.is_empty() {
info!(agent = %def.name, "injecting evolution memory context");
composed_task = format!("{}\n\n{}", composed_task, evo_ctx);
}
}
// Inject RLM session info if enabled for this agent.
if def.rlm_enabled.unwrap_or(false) {
info!(agent = %def.name, "injecting RLM sandboxed execution context");
composed_task = format!(
"{}\n\n## RLM Sandboxed Code Execution\n\
You have access to sandboxed code execution via terraphim_rlm. \
Use the terraphim-rlm MCP tools to execute code in an isolated environment \
when you need to run, test, or validate code changes. \
Sessions are resource-limited and automatically cleaned up.",
composed_task
);
}
// Use stdin only when persona was actually resolved (prompt is enriched)
// or when the task exceeds ARG_MAX safety threshold.
// Do NOT use stdin for unfound personas -- the bare task is small and
// stdin delivery to short-lived processes (echo) causes broken pipe races.
const STDIN_THRESHOLD: usize = 32_768; // 32 KB
let use_stdin =
persona_found || !skill_content.is_empty() || composed_task.len() > STDIN_THRESHOLD;
// Create isolated git worktree for implementation-tier agents that modify code.
// Review-tier agents (haiku) are read-only and don't need isolation.
let needs_isolation = model.as_ref().map(|m| !m.contains("haiku")).unwrap_or(true);
// Resolve the git repo directory for worktree operations. Project-bound
// agents need a worktree from their own repo, not the orchestrator's.
let repo_dir: &Path = if let Some(pid) = def.project.as_deref() {
match self.config.project_by_id(pid) {
Some(p) => p.working_dir.as_path(),
None => {
warn!(
agent = %def.name,
project_id = %pid,
fallback = %self.config.working_dir.display(),
"project_by_id returned None, falling back to orchestrator working_dir"
);
&self.config.working_dir
}
}
} else {
&self.config.working_dir
};
let (worktree_path, worktree_guard) = if needs_isolation {
if let Some(path) = self.create_agent_worktree(&def.name, repo_dir).await {
let guard = crate::worktree_guard::WorktreeGuard::new(&path);
(Some(path), Some(guard))
} else {
(None, None)
}
} else {
(None, None)
};
let agent_working_dir = worktree_path.as_deref().unwrap_or(repo_dir).to_path_buf();
// Build primary Provider from the agent definition for the spawner.
let primary_provider = terraphim_types::capability::Provider {
id: def.name.clone(),
name: def.name.clone(),
provider_type: terraphim_types::capability::ProviderType::Agent {
agent_id: def.name.clone(),
cli_command: effective_cli.clone(),
working_dir: agent_working_dir.clone(),
},
capabilities: vec![],
cost_level: terraphim_types::capability::CostLevel::Cheap,
latency: terraphim_types::capability::Latency::Medium,
keywords: def.capabilities.clone(),
};
// Build fallback Provider if fallback_provider is configured
let fallback_provider = def.fallback_provider.as_ref().map(|fallback_cli| {
terraphim_types::capability::Provider {
id: format!("{}-fallback", def.name),
name: format!("{} (fallback)", def.name),
provider_type: terraphim_types::capability::ProviderType::Agent {
agent_id: format!("{}-fallback", def.name),
cli_command: fallback_cli.clone(),
working_dir: agent_working_dir.clone(),
},
capabilities: vec![],
cost_level: terraphim_types::capability::CostLevel::Cheap,
latency: terraphim_types::capability::Latency::Medium,
keywords: def.capabilities.clone(),
}
});
// Build the spawn request with primary and fallback
let mut request = SpawnRequest::new(primary_provider, &composed_task)
.with_primary_model(model.as_deref().unwrap_or(""));
if let Some(fallback) = fallback_provider {
request = request.with_fallback_provider(fallback);
if let Some(fallback_model) = &def.fallback_model {
request = request.with_fallback_model(fallback_model);
}
}
if use_stdin {
request = request.with_stdin();
}
// Thread resource limits from agent definition to spawner
let mut limits = ResourceLimits::default();
if let Some(max_cpu) = def.max_cpu_seconds {
limits.max_cpu_seconds = Some(max_cpu);
}
if let Some(max_mem) = def.max_memory_bytes {
limits.max_memory_bytes = Some(max_mem);
}
request = request.with_resource_limits(limits);
// === CONCURRENCY GATE ===
let project_id = def
.project
.as_deref()
.unwrap_or(crate::dispatcher::LEGACY_PROJECT_ID);
let permit = self.concurrency_controller.acquire_any(project_id).await;
if permit.is_none() {
warn!(
agent = %def.name,
project = %project_id,
active = self.active_agents.len(),
"skipping spawn: global concurrency limit reached"
);
return Ok(());
}
let spawn_ctx =
build_spawn_context_for_agent(&self.config, def, self.output_poster.as_ref());
let handle = self
.spawner
.spawn_with_fallback(&request, spawn_ctx)
.await
.map_err(|e| OrchestratorError::SpawnFailed {
agent: def.name.clone(),
reason: e.to_string(),
})?;
// Subscribe to the output broadcast for nightwatch drain
let output_rx = handle.subscribe_output();
// Open a streaming log file and spawn a background drain task so
// output is captured to disk even when the tick interval is long.
let output_tmp_path = self.start_output_log_drain(&def.name, &handle);
// Get the restart count from the orchestrator-level counter
let restart_count = self
.restart_counts
.get(&agent_key(def))
.copied()
.unwrap_or(0);
self.active_agents.insert(
def.name.clone(),
ManagedAgent {
definition: def.clone(),
handle,
started_at: Instant::now(),
restart_count,
output_rx,
spawned_by_mention: false,
worktree_path,
worktree_guard,
routed_model: model.clone(),
session_id: format!("{}-{}", def.name, ulid::Ulid::new()),
mention_chain_id: None,
mention_depth: None,
mention_parent_agent: None,
concurrency_permit: permit,
commit_status_post: None,
output_tmp_path,
},
);
// === RECORD COMMIT FOR GIT-DIFF STRATEGY ===
if let Ok(head) = self.get_current_head().await {
self.last_run_commits.insert(def.name.clone(), head);
}
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let doc = quickwit::LogDocument {
timestamp: chrono::Utc::now().to_rfc3339(),
project_id: def
.project
.clone()
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string()),
level: "INFO".into(),
agent_name: def.name.clone(),
layer: format!("{:?}", def.layer),
source: "orchestrator".into(),
message: "agent spawned".into(),
model: model.clone(),
..Default::default()
};
let _ = sink.send(doc).await;
}
Ok(())
}
/// Handle a `DispatchTask::ReviewPr` dispatch: run the routing engine,
/// enforce the C1/C3 provider allow-list, and spawn the pr-reviewer agent
/// with `ADF_PR_*` env overrides carrying the per-dispatch context.
///
/// The task is a no-op (with a warn log) when no `pr-reviewer` agent is
/// configured for the project yet. Step E adds the canonical
/// `pr-reviewer.toml` fragment; until then this method must not crash the
/// reconcile loop.
///
/// Unlike [`spawn_agent`], this path skips persona composition, skill
/// chain injection, and worktree creation. The pr-reviewer is review-tier
/// (read-only), so the heavyweight scaffolding from the implementation
/// spawn path is intentionally left out.
///
/// [`spawn_agent`]: AgentOrchestrator::spawn_agent
pub(crate) async fn handle_review_pr(
&mut self,
task: dispatcher::DispatchTask,
) -> Result<(), OrchestratorError> {
let (pr_number, project, head_sha, author_login, title, diff_loc) = match task {
dispatcher::DispatchTask::ReviewPr {
pr_number,
project,
head_sha,
author_login,
title,
diff_loc,
} => (pr_number, project, head_sha, author_login, title, diff_loc),
other => {
warn!(task = ?other, "handle_review_pr invoked with non-ReviewPr task; ignoring");
return Ok(());
}
};
let req = pr_dispatch::ReviewPrRequest {
pr_number,
project: project.clone(),
head_sha: head_sha.clone(),
author_login,
title,
diff_loc,
};
// ADF Phase 2 (issue #944): fan-out over the configured
// `agents_on_pr_open` list. Each entry is gated independently
// (subscription allow-list + per-agent monthly budget). Only
// entries that successfully spawn get a `pending` commit status
// — a `pending` from a skipped agent would block the PR forever.
// When `[pr_dispatch]` is absent the legacy default ships a single
// pr-reviewer entry, preserving pre-Phase-2 behaviour.
let entries = self.config.agents_on_pr_open_for_project(&project);
for entry in entries {
let spawned = match entry.name.as_str() {
"build-runner" => {
self.dispatch_build_runner_for_pr(&req, &entry.context)
.await?
}
_ => {
self.dispatch_pr_reviewer_for_pr(&req, &entry.name, &entry.context)
.await?
}
};
if spawned {
self.post_pending_status(
&head_sha,
pr_number,
&project,
&entry.context,
&format!("{} dispatched", entry.name),
)
.await;
}
}
Ok(())
}
/// Phase 2 helper: spawn the LLM-style PR review agent (`pr-reviewer`
/// or any future fan-out entry that runs through the routing engine).
///
/// Returns `Ok(true)` when the agent was spawned and is now in
/// `active_agents`; `Ok(false)` when it was gated out (no agent
/// configured for the project, banned static or routed model, or
/// budget exhausted). The caller posts a `pending` commit status only
/// when this returns `true`.
async fn dispatch_pr_reviewer_for_pr(
&mut self,
req: &pr_dispatch::ReviewPrRequest,
agent_name: &str,
commit_status_context: &str,
) -> Result<bool, OrchestratorError> {
let pr_number = req.pr_number;
let project = req.project.clone();
let head_sha = req.head_sha.clone();
// Look up the agent for this project. Missing entries in the
// fan-out list must skip silently (no `pending` posted) — a
// hung pending would block the PR forever.
let def = match self
.config
.agents
.iter()
.find(|a| a.name == agent_name && a.project.as_deref() == Some(project.as_str()))
{
Some(d) => d.clone(),
None => {
warn!(
pr_number,
project = %project,
agent = %agent_name,
"ReviewPr skipped: no agent configured for project"
);
return Ok(false);
}
};
// === STATIC ALLOW-LIST GATE (pre-routing) ===
// Belt-and-braces: the load-time config validator rejects banned
// providers, and `RoutingDecisionEngine` filters them from the
// candidate pool, but this check guarantees the spawn never runs
// against a banned static `model` even if the config was mutated
// at runtime or a future refactor drops the routing filter.
if let Some(static_model) = def.model.as_deref() {
if !config::is_allowed_provider(static_model) {
warn!(
agent = %def.name,
pr_number,
project = %project,
model = %static_model,
"ReviewPr skipped: static model rejected by subscription allow-list"
);
return Ok(false);
}
}
// === BUDGET GATE ===
let budget_verdict = self.cost_tracker.check(&def.name);
if budget_verdict.should_pause() {
warn!(
agent = %def.name,
pr_number,
project = %project,
verdict = %budget_verdict,
"ReviewPr skipped: monthly budget exhausted"
);
return Ok(false);
}
// === ROUTING ===
// Build a DispatchContext off the per-PR task string so KG/keyword
// routing can pick a model based on "review" keywords and PR shape.
let task_string = pr_dispatch::build_review_task(req);
let kg_arc = self
.kg_router
.as_ref()
.map(|r| std::sync::Arc::new(r.clone()));
let unhealthy = self.provider_health.unhealthy_providers();
let telemetry_arc = std::sync::Arc::new(self.telemetry_store.clone());
let strategy = self
.config
.routing
.as_ref()
.map(|r| r.route_selection_strategy)
.unwrap_or(crate::control_plane::RouteSelectionStrategy::Fastest);
let engine = control_plane::RoutingDecisionEngine::with_provider_budget_and_strategy(
kg_arc,
unhealthy,
terraphim_router::Router::new(),
Some(telemetry_arc),
self.provider_budget_tracker.clone(),
strategy,
);
let dispatch_ctx = control_plane::DispatchContext {
agent_name: def.name.clone(),
task: task_string.clone(),
static_model: def.model.clone(),
cli_tool: def.cli_tool.clone(),
layer: def.layer,
session_id: None,
};
let decision = engine.decide_route(&dispatch_ctx, &budget_verdict).await;
info!(
agent = %def.name,
pr_number,
project = %project,
model = %decision.candidate.model,
rationale = %decision.rationale,
"ReviewPr routing decision"
);
// === C1/C3 ALLOW-LIST GATE ===
// Routing may suggest a banned provider (e.g. via stale KG rules); the
// subscription-only allow-list must still short-circuit the spawn so
// unsanctioned providers never launch.
let routed_model = decision.candidate.model.clone();
let effective_cli = if decision.candidate.cli_tool.is_empty() {
def.cli_tool.clone()
} else {
decision.candidate.cli_tool.clone()
};
if !routed_model.is_empty() && !config::is_allowed_provider(&routed_model) {
warn!(
agent = %def.name,
pr_number,
project = %project,
model = %routed_model,
"ReviewPr skipped: routed model rejected by subscription allow-list"
);
return Ok(false);
}
// === SPAWN ===
let primary_provider = terraphim_types::capability::Provider {
id: def.name.clone(),
name: def.name.clone(),
provider_type: terraphim_types::capability::ProviderType::Agent {
agent_id: def.name.clone(),
cli_command: effective_cli.clone(),
working_dir: self.config.working_dir_for_agent(&def),
},
capabilities: vec![],
cost_level: terraphim_types::capability::CostLevel::Cheap,
latency: terraphim_types::capability::Latency::Medium,
keywords: def.capabilities.clone(),
};
let fallback_provider = def.fallback_provider.as_ref().map(|fallback_cli| {
terraphim_types::capability::Provider {
id: format!("{}-fallback", def.name),
name: format!("{} (fallback)", def.name),
provider_type: terraphim_types::capability::ProviderType::Agent {
agent_id: format!("{}-fallback", def.name),
cli_command: fallback_cli.clone(),
working_dir: self.config.working_dir_for_agent(&def),
},
capabilities: vec![],
cost_level: terraphim_types::capability::CostLevel::Cheap,
latency: terraphim_types::capability::Latency::Medium,
keywords: def.capabilities.clone(),
}
});
// Issue #1020: pass the TOML `task` body (script / system prompt)
// to the spawner -- not the runtime informational summary.
// The summary is layered as ADF_TASK_SUMMARY env so future TOML
// scripts can reference it without a code change.
// Bug #2450 fix: pr-reviewer agent was receiving `def.task` ("review")
// instead of `task_string` (the full PR review description), causing
// the agent to exit with empty_success in 2s. The TOML `task` field
// is a label/placeholder for pr-reviewer; the actual work is built
// by build_review_task(req) into task_string.
let mut request = SpawnRequest::new(primary_provider, &task_string);
if !routed_model.is_empty() {
request = request.with_primary_model(&routed_model);
}
if let Some(fallback) = fallback_provider {
request = request.with_fallback_provider(fallback);
if let Some(fallback_model) = &def.fallback_model {
request = request.with_fallback_model(fallback_model);
}
}
let mut limits = ResourceLimits::default();
if let Some(max_cpu) = def.max_cpu_seconds {
limits.max_cpu_seconds = Some(max_cpu);
}
if let Some(max_mem) = def.max_memory_bytes {
limits.max_memory_bytes = Some(max_mem);
}
request = request.with_resource_limits(limits);
let base_ctx =
build_spawn_context_for_agent(&self.config, &def, self.output_poster.as_ref());
let spawn_ctx = pr_dispatch::layer_pr_env(base_ctx, req)
.with_env("ADF_TASK_SUMMARY", task_string.clone());
let handle = self
.spawner
.spawn_with_fallback(&request, spawn_ctx)
.await
.map_err(|e| OrchestratorError::SpawnFailed {
agent: def.name.clone(),
reason: e.to_string(),
})?;
let output_rx = handle.subscribe_output();
let output_tmp_path = self.start_output_log_drain(&def.name, &handle);
let restart_count = self
.restart_counts
.get(&agent_key(&def))
.copied()
.unwrap_or(0);
self.active_agents.insert(
def.name.clone(),
ManagedAgent {
definition: def.clone(),
handle,
started_at: Instant::now(),
restart_count,
output_rx,
spawned_by_mention: false,
worktree_path: None,
worktree_guard: None,
routed_model: if routed_model.is_empty() {
None
} else {
Some(routed_model)
},
session_id: format!("{}-{}", def.name, ulid::Ulid::new()),
mention_chain_id: None,
mention_depth: None,
mention_parent_agent: None,
concurrency_permit: None,
commit_status_post: Some((head_sha.clone(), commit_status_context.to_string())),
output_tmp_path,
},
);
info!(
agent = %def.name,
pr_number,
project = %project,
head_sha = %head_sha,
"ReviewPr spawned LLM review agent"
);
Ok(true)
}
/// Phase 2 helper: spawn the deterministic `build-runner` agent on a
/// `pull_request.opened` event. Mirrors `handle_push`'s spawn pipeline
/// but injects PR-shaped `ADF_PUSH_*` env (using
/// `refs/pull/<n>/head` as the synthetic ref) so the same bash task
/// script handles both push events and PR opens.
///
/// Skips the routing engine — `build-runner` is bash-only (no LLM, no
/// model) so a routing decision would invite a false-positive
/// banned-provider check on an unset `def.model`. Logs a synthetic
/// `model = "n/a"` row for parity with the LLM path.
///
/// Returns `Ok(true)` on successful spawn (caller posts pending);
/// `Ok(false)` when gated out.
async fn dispatch_build_runner_for_pr(
&mut self,
req: &pr_dispatch::ReviewPrRequest,
commit_status_context: &str,
) -> Result<bool, OrchestratorError> {
let pr_number = req.pr_number;
let project = req.project.clone();
let head_sha = req.head_sha.clone();
if self.active_agents.contains_key("build-runner") {
info!(
pr_number,
project = %project,
head_sha = %head_sha,
"ReviewPr skipped build-runner: already active from concurrent push dispatch"
);
return Ok(false);
}
// Look up the build-runner agent for this project. Missing must
// skip silently — no `pending` posted by the caller.
let def =
match self.config.agents.iter().find(|a| {
a.name == "build-runner" && a.project.as_deref() == Some(project.as_str())
}) {
Some(d) => d.clone(),
None => {
warn!(
pr_number,
project = %project,
"ReviewPr skipped: no build-runner agent configured for project"
);
return Ok(false);
}
};
// === STATIC ALLOW-LIST GATE ===
// build-runner is bash-only (no LLM), so def.model is normally None
// and this gate is a no-op. The check is retained for defence in
// depth so a future config that mis-sets `model` cannot bypass C1/C3.
if let Some(static_model) = def.model.as_deref() {
if !config::is_allowed_provider(static_model) {
warn!(
agent = %def.name,
pr_number,
project = %project,
model = %static_model,
"ReviewPr skipped: build-runner static model rejected by subscription allow-list"
);
return Ok(false);
}
}
// === BUDGET GATE ===
let budget_verdict = self.cost_tracker.check(&def.name);
if budget_verdict.should_pause() {
warn!(
agent = %def.name,
pr_number,
project = %project,
verdict = %budget_verdict,
"ReviewPr skipped: build-runner monthly budget exhausted"
);
return Ok(false);
}
// === ROUTING DECISION (observability only) ===
// build-runner is bash; mirror handle_push's synthetic log row so
// dashboards see one entry per dispatch. No call to decide_route —
// an LLM router on an unset model would surface false positives.
info!(
agent = %def.name,
pr_number,
project = %project,
model = "n/a",
cost_estimate_cents = 0,
rationale = "deterministic build-runner (no LLM)",
"ReviewPr routing decision"
);
// === SPAWN ===
let primary_provider = terraphim_types::capability::Provider {
id: def.name.clone(),
name: def.name.clone(),
provider_type: terraphim_types::capability::ProviderType::Agent {
agent_id: def.name.clone(),
cli_command: def.cli_tool.clone(),
working_dir: self.config.working_dir_for_agent(&def),
},
capabilities: vec![],
cost_level: terraphim_types::capability::CostLevel::Cheap,
latency: terraphim_types::capability::Latency::Medium,
keywords: def.capabilities.clone(),
};
let task_string = format!(
"Build/test verdict for PR #{} (head={}, {} LOC, project={}, author={})",
pr_number, head_sha, req.diff_loc, project, req.author_login,
);
// Issue #1020: pass the TOML `task` body (the bash script that
// does git fetch / rch exec / curl status post) to the spawner
// -- not the runtime informational summary, which would have
// been interpreted as `bash -c "Build/test verdict ..."` and
// exited 127 on the first non-existent command.
let mut request = SpawnRequest::new(primary_provider, &def.task);
let mut limits = ResourceLimits::default();
if let Some(max_cpu) = def.max_cpu_seconds {
limits.max_cpu_seconds = Some(max_cpu);
}
if let Some(max_mem) = def.max_memory_bytes {
limits.max_memory_bytes = Some(max_mem);
}
request = request.with_resource_limits(limits);
// Layer ADF_PUSH_* env on top of the per-agent base context.
// The ref is synthesised as `refs/pull/<n>/head` so the task
// script can `git fetch origin <ref> && git checkout <sha>`
// identically to a push-event dispatch. `ADF_PUSH_BEFORE_SHA`
// is empty because the ReviewPr dispatch task does not carry
// the PR base SHA — the build-runner script only requires
// `ADF_PUSH_SHA` and `ADF_PUSH_REF`.
// ADF_TASK_SUMMARY exposes the runtime summary so the task can
// log it without a code change (issue #1020).
let mut spawn_ctx =
build_spawn_context_for_agent(&self.config, &def, self.output_poster.as_ref());
spawn_ctx = spawn_ctx
.with_env("ADF_PUSH_SHA", head_sha.clone())
.with_env("ADF_PUSH_REF", format!("refs/pull/{}/head", pr_number))
.with_env("ADF_PUSH_PROJECT", project.clone())
.with_env("ADF_PUSH_BEFORE_SHA", String::new())
.with_env("ADF_PUSH_PUSHER", req.author_login.clone())
.with_env("ADF_PUSH_FILES", String::new())
.with_env("ADF_TASK_SUMMARY", task_string.clone());
let handle = self
.spawner
.spawn_with_fallback(&request, spawn_ctx)
.await
.map_err(|e| OrchestratorError::SpawnFailed {
agent: def.name.clone(),
reason: e.to_string(),
})?;
let output_rx = handle.subscribe_output();
let output_tmp_path = self.start_output_log_drain(&def.name, &handle);
let restart_count = self
.restart_counts
.get(&agent_key(&def))
.copied()
.unwrap_or(0);
self.active_agents.insert(
def.name.clone(),
ManagedAgent {
definition: def.clone(),
handle,
started_at: Instant::now(),
restart_count,
output_rx,
spawned_by_mention: false,
worktree_path: None,
worktree_guard: None,
routed_model: None,
session_id: format!("{}-{}", def.name, ulid::Ulid::new()),
mention_chain_id: None,
mention_depth: None,
mention_parent_agent: None,
concurrency_permit: None,
commit_status_post: Some((head_sha.clone(), commit_status_context.to_string())),
output_tmp_path,
},
);
info!(
agent = %def.name,
pr_number,
project = %project,
head_sha = %head_sha,
"ReviewPr spawned build-runner"
);
Ok(true)
}
/// Post a `pending` commit status for the given `context` against the
/// PR head SHA.
///
/// Generalised from Phase 1's `post_pr_reviewer_pending_status` so the
/// Phase 2 PR-fan-out path can post one pending per dispatched agent
/// (one row per `agents_on_pr_open` entry that successfully spawned).
///
/// Best-effort: when the workflow tracker isn't configured (e.g. in
/// unit tests) or the API call fails we log and return without
/// surfacing the error. The agent itself owns the final state
/// transition (success / failure / error).
async fn post_pending_status(
&mut self,
head_sha: &str,
pr_number: u64,
project: &str,
context: &str,
description: &str,
) {
let tracker = match self.get_or_init_pre_check_tracker() {
Some(t) => t,
None => {
debug!(
pr_number,
project,
context,
"ReviewPr: no workflow tracker configured; skipping pending status"
);
return;
}
};
let owner = tracker.owner().to_string();
let repo = tracker.repo().to_string();
let result = tracker
.set_commit_status(
&owner,
&repo,
head_sha,
terraphim_tracker::StatusState::Pending,
context,
description,
None,
)
.await;
match result {
Ok(()) => {
info!(
pr_number,
project, head_sha, context, "ReviewPr: posted pending status"
);
}
Err(e) => {
warn!(
error = %e,
pr_number,
project,
head_sha,
context,
"ReviewPr: failed to post pending status"
);
}
}
}
/// Post a terminal (success/failure) commit status for an agent that
/// exited. Best-effort: logs on failure but does not propagate errors.
async fn post_terminal_commit_status(
&mut self,
head_sha: &str,
context: &str,
state: terraphim_tracker::StatusState,
description: &str,
) {
let tracker = match self.get_or_init_pre_check_tracker() {
Some(t) => t,
None => {
debug!(
head_sha,
context, "post_terminal_commit_status: no workflow tracker; skipping"
);
return;
}
};
let owner = tracker.owner().to_string();
let repo = tracker.repo().to_string();
match tracker
.set_commit_status(&owner, &repo, head_sha, state, context, description, None)
.await
{
Ok(()) => {
info!(head_sha, context, "posted terminal commit status");
}
Err(e) => {
warn!(
error = %e,
head_sha,
context,
"failed to post terminal commit status"
);
}
}
}
/// Handle a `DispatchTask::Push` dispatch (Phase 3 — ADF replaces Gitea
/// Actions): look up the project's `build-runner` agent, gate on the
/// subscription allow-list and monthly budget, log a routing decision row
/// for observability (even though `build-runner` is bash, not LLM), then
/// spawn it with `ADF_PUSH_*` env injection so the bash task can shell
/// out to `rch exec` for the deterministic cargo gates.
///
/// The handler is a no-op (with warn log) when no `build-runner` agent is
/// configured for the project — repos without build-runner must not break
/// the orchestrator drain loop.
pub(crate) async fn handle_push(
&mut self,
task: dispatcher::DispatchTask,
) -> Result<(), OrchestratorError> {
let (project, ref_name, before_sha, after_sha, pusher_login, files_changed) = match task {
dispatcher::DispatchTask::Push {
project,
ref_name,
before_sha,
after_sha,
pusher_login,
files_changed,
} => (
project,
ref_name,
before_sha,
after_sha,
pusher_login,
files_changed,
),
other => {
warn!(task = ?other, "handle_push invoked with non-Push task; ignoring");
return Ok(());
}
};
// Look up the build-runner agent for this project. Repos without
// build-runner shouldn't break the orchestrator -- log and skip.
let def =
match self.config.agents.iter().find(|a| {
a.name == "build-runner" && a.project.as_deref() == Some(project.as_str())
}) {
Some(d) => d.clone(),
None => {
warn!(
project = %project,
after_sha = %after_sha,
"Push skipped: no build-runner agent configured for project"
);
return Ok(());
}
};
if self.active_agents.contains_key("build-runner") {
info!(
project = %project,
after_sha = %after_sha,
"Push skipped build-runner: already active from concurrent dispatch"
);
return Ok(());
}
// === STATIC ALLOW-LIST GATE ===
// build-runner is bash-only (no LLM), so def.model is normally None
// and this gate is a no-op. The check is retained for defence in
// depth so a future config that mis-sets `model` cannot bypass C1/C3.
if let Some(static_model) = def.model.as_deref() {
if !config::is_allowed_provider(static_model) {
warn!(
agent = %def.name,
project = %project,
model = %static_model,
"Push skipped: static model rejected by subscription allow-list"
);
return Ok(());
}
}
// === BUDGET GATE ===
// build-runner has no LLM cost but the budget tracker still records
// its dispatches; pause if the operator deliberately capped it.
let budget_verdict = self.cost_tracker.check(&def.name);
if budget_verdict.should_pause() {
warn!(
agent = %def.name,
project = %project,
verdict = %budget_verdict,
"Push skipped: build-runner monthly budget exhausted"
);
return Ok(());
}
// === ROUTING DECISION (observability only) ===
// Even though build-runner is bash, we still log a routing decision
// row so the dashboard sees one entry per dispatch. Cost is 0 because
// there is no LLM, and the model column reads "n/a".
info!(
agent = %def.name,
project = %project,
ref_name = %ref_name,
after_sha = %after_sha,
model = "n/a",
cost_estimate_cents = 0,
rationale = "deterministic build-runner (no LLM)",
"Push routing decision"
);
// === SPAWN ===
// build-runner is a plain bash agent: cli_tool from the def, no
// primary model, no fallback model. Mirror the SpawnRequest shape
// used by handle_review_pr but skip the LLM-specific overrides.
let primary_provider = terraphim_types::capability::Provider {
id: def.name.clone(),
name: def.name.clone(),
provider_type: terraphim_types::capability::ProviderType::Agent {
agent_id: def.name.clone(),
cli_command: def.cli_tool.clone(),
working_dir: self.config.working_dir_for_agent(&def),
},
capabilities: vec![],
cost_level: terraphim_types::capability::CostLevel::Cheap,
latency: terraphim_types::capability::Latency::Medium,
keywords: def.capabilities.clone(),
};
let task_string = format!(
"Build/test verdict for push to {} ({} → {}, {} files changed) on project={}, pushed by {}",
ref_name,
before_sha,
after_sha,
files_changed.len(),
project,
pusher_login,
);
// Issue #1020: pass the TOML `task` body (build-runner bash
// script) to the spawner -- not the runtime informational
// summary. The summary is layered as ADF_TASK_SUMMARY env.
let mut request = SpawnRequest::new(primary_provider, &def.task);
let mut limits = ResourceLimits::default();
if let Some(max_cpu) = def.max_cpu_seconds {
limits.max_cpu_seconds = Some(max_cpu);
}
if let Some(max_mem) = def.max_memory_bytes {
limits.max_memory_bytes = Some(max_mem);
}
request = request.with_resource_limits(limits);
// Layer the ADF_PUSH_* env on top of the per-agent base context.
let mut spawn_ctx =
build_spawn_context_for_agent(&self.config, &def, self.output_poster.as_ref());
spawn_ctx = spawn_ctx
.with_env("ADF_PUSH_SHA", after_sha.clone())
.with_env("ADF_PUSH_REF", ref_name.clone())
.with_env("ADF_PUSH_PROJECT", project.clone())
.with_env("ADF_PUSH_BEFORE_SHA", before_sha.clone())
.with_env("ADF_PUSH_PUSHER", pusher_login.clone())
.with_env("ADF_PUSH_FILES", files_changed.join("\n"))
.with_env("ADF_TASK_SUMMARY", task_string.clone());
let handle = self
.spawner
.spawn_with_fallback(&request, spawn_ctx)
.await
.map_err(|e| OrchestratorError::SpawnFailed {
agent: def.name.clone(),
reason: e.to_string(),
})?;
let output_rx = handle.subscribe_output();
let output_tmp_path = self.start_output_log_drain(&def.name, &handle);
let restart_count = self
.restart_counts
.get(&agent_key(&def))
.copied()
.unwrap_or(0);
self.active_agents.insert(
def.name.clone(),
ManagedAgent {
definition: def.clone(),
handle,
started_at: Instant::now(),
restart_count,
output_rx,
spawned_by_mention: false,
worktree_path: None,
worktree_guard: None,
routed_model: None,
session_id: format!("{}-{}", def.name, ulid::Ulid::new()),
mention_chain_id: None,
mention_depth: None,
mention_parent_agent: None,
concurrency_permit: None,
commit_status_post: Some((after_sha.clone(), "adf/build".to_string())),
output_tmp_path,
},
);
self.post_pending_status(
&after_sha,
0,
&project,
"adf/build",
"build-runner dispatched",
)
.await;
info!(
agent = %def.name,
project = %project,
ref_name = %ref_name,
after_sha = %after_sha,
"Push spawned build-runner"
);
Ok(())
}
/// Evaluate the pre-check strategy for an agent.
async fn run_pre_check(&mut self, def: &AgentDefinition) -> PreCheckResult {
match &def.pre_check {
None | Some(PreCheckStrategy::Always) => PreCheckResult::Findings(String::new()),
Some(PreCheckStrategy::GitDiff { watch_paths }) => {
self.git_diff_pre_check(&def.name, watch_paths).await
}
Some(PreCheckStrategy::GiteaIssue { issue_number }) => {
self.gitea_issue_pre_check(*issue_number).await
}
Some(PreCheckStrategy::Shell {
script,
timeout_secs,
}) => self.shell_pre_check(script, *timeout_secs).await,
}
}
/// Git diff pre-check: compare last_run_commit to HEAD.
async fn git_diff_pre_check(&self, agent_name: &str, watch_paths: &[String]) -> PreCheckResult {
let last_commit = match self.last_run_commits.get(agent_name) {
Some(c) => c.clone(),
None => {
info!(agent = %agent_name, "no last_run_commit recorded, spawning (first run)");
return PreCheckResult::Findings(String::new());
}
};
// Get current HEAD
let head = match self.get_current_head().await {
Ok(h) => h,
Err(e) => {
warn!(agent = %agent_name, error = %e, "failed to get HEAD, spawning (fail-open)");
return PreCheckResult::Failed(format!("git rev-parse failed: {}", e));
}
};
if head == last_commit {
info!(agent = %agent_name, commit = %head, "HEAD unchanged since last run, skipping");
return PreCheckResult::NoFindings;
}
// Get changed files
let diff_range = format!("{}..{}", last_commit, head);
let output = match tokio::time::timeout(
Duration::from_secs(30),
tokio::process::Command::new("git")
.args(["diff", "--name-only", &diff_range])
.current_dir(&self.config.working_dir)
.output(),
)
.await
{
Ok(Ok(o)) => o,
Ok(Err(e)) => {
warn!(agent = %agent_name, error = %e, "git diff failed, spawning (fail-open)");
return PreCheckResult::Failed(format!("git diff failed: {}", e));
}
Err(_) => {
warn!(agent = %agent_name, "git diff timed out after 30s, spawning (fail-open)");
return PreCheckResult::Failed("git diff timed out after 30s".into());
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
warn!(agent = %agent_name, stderr = %stderr, "git diff non-zero exit, spawning (fail-open)");
return PreCheckResult::Failed(format!("git diff exit {}: {}", output.status, stderr));
}
let changed_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
.lines()
.filter(|l| !l.is_empty())
.map(|l| l.to_string())
.collect();
if changed_files.is_empty() {
info!(agent = %agent_name, "no files changed, skipping");
return PreCheckResult::NoFindings;
}
if has_matching_changes(&changed_files, watch_paths) {
let summary = format!("{} files changed matching watch_paths", changed_files.len());
info!(agent = %agent_name, files = changed_files.len(), "matching changes found");
PreCheckResult::Findings(summary)
} else {
info!(agent = %agent_name, files = changed_files.len(), "changes found but none match watch_paths, skipping");
PreCheckResult::NoFindings
}
}
/// Shell pre-check: run script via sh -c.
async fn shell_pre_check(&self, script: &str, timeout_secs: u64) -> PreCheckResult {
let result = tokio::time::timeout(
Duration::from_secs(timeout_secs),
tokio::process::Command::new("sh")
.arg("-c")
.arg(script)
.current_dir(&self.config.working_dir)
.output(),
)
.await;
match result {
Ok(Ok(output)) => {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
if stdout.is_empty() {
PreCheckResult::NoFindings
} else {
PreCheckResult::Findings(stdout)
}
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
PreCheckResult::Failed(format!("script exit {}: {}", output.status, stderr))
}
}
Ok(Err(e)) => PreCheckResult::Failed(format!("script I/O error: {}", e)),
Err(_) => PreCheckResult::Failed(format!("script timed out after {}s", timeout_secs)),
}
}
/// Get or lazily construct the GiteaTracker for pre-check.
fn get_or_init_pre_check_tracker(&mut self) -> Option<&terraphim_tracker::GiteaTracker> {
if self.pre_check_tracker.is_some() {
return self.pre_check_tracker.as_ref();
}
let workflow = self.config.workflow.as_ref()?;
let tc = &workflow.tracker;
let config = terraphim_tracker::GiteaConfig {
base_url: tc.endpoint.clone(),
token: tc.api_key.clone(),
owner: tc.owner.clone(),
repo: tc.repo.clone(),
active_states: tc.states.active.clone(),
terminal_states: tc.states.terminal.clone(),
use_robot_api: tc.use_robot_api,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
match terraphim_tracker::GiteaTracker::new(config) {
Ok(tracker) => {
self.pre_check_tracker = Some(tracker);
self.pre_check_tracker.as_ref()
}
Err(e) => {
warn!(error = %e, "failed to construct GiteaTracker for pre-check");
None
}
}
}
/// Evaluate the gitea-issue pre-check strategy.
async fn gitea_issue_pre_check(&mut self, issue_number: u64) -> PreCheckResult {
let tracker = match self.get_or_init_pre_check_tracker() {
Some(t) => t,
None => {
return PreCheckResult::Failed(
"no workflow config for gitea-issue pre-check".into(),
);
}
};
// Fetch comments with 15s timeout
let comments = match tokio::time::timeout(
Duration::from_secs(15),
tracker.fetch_comments(issue_number, None),
)
.await
{
Ok(Ok(comments)) => comments,
Ok(Err(e)) => {
warn!(
issue = issue_number,
error = %e,
"gitea comment fetch failed, spawning (fail-open)"
);
return PreCheckResult::Failed(format!("comment fetch failed: {}", e));
}
Err(_) => {
warn!(
issue = issue_number,
"gitea comment fetch timed out, spawning (fail-open)"
);
return PreCheckResult::Failed("comment fetch timed out after 15s".into());
}
};
if comments.is_empty() {
info!(issue = issue_number, "no comments on issue, spawning");
return PreCheckResult::Findings(String::new());
}
// Check the most recent comment for PASS verdict
let latest = comments.last().expect("checked non-empty above");
let body_lower = latest.body.to_lowercase();
if body_lower.contains("verdict: pass") {
// Check if there are new commits since this comment
let comment_time = &latest.created_at;
// Use git log to check for commits after the comment time
let output = match tokio::time::timeout(
Duration::from_secs(30),
tokio::process::Command::new("git")
.args(["log", "--oneline", &format!("--since={}", comment_time)])
.current_dir(&self.config.working_dir)
.output(),
)
.await
{
Ok(Ok(o)) => o,
Ok(Err(e)) => {
warn!(error = %e, "git log failed, spawning (fail-open)");
return PreCheckResult::Failed(format!("git log failed: {}", e));
}
Err(_) => {
warn!("git log --since timed out after 30s, spawning (fail-open)");
return PreCheckResult::Failed("git log timed out after 30s".into());
}
};
let log_output = String::from_utf8_lossy(&output.stdout);
if log_output.trim().is_empty() {
info!(
issue = issue_number,
"PASS verdict and no new commits, skipping"
);
return PreCheckResult::NoFindings;
} else {
let commit_count = log_output.lines().count();
info!(
issue = issue_number,
new_commits = commit_count,
"PASS verdict but new commits found, spawning"
);
return PreCheckResult::Findings(format!(
"{} new commits since last PASS verdict",
commit_count
));
}
}
info!(
issue = issue_number,
"no PASS verdict in latest comment, spawning"
);
PreCheckResult::Findings(String::new())
}
/// Get current HEAD commit hash.
async fn get_current_head(&self) -> Result<String, OrchestratorError> {
let output = tokio::time::timeout(
Duration::from_secs(5),
tokio::process::Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(&self.config.working_dir)
.output(),
)
.await
.map_err(|_| OrchestratorError::Config("git rev-parse HEAD timed out after 5s".into()))?
.map_err(OrchestratorError::from)?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
Err(OrchestratorError::Config(
"git rev-parse HEAD failed".into(),
))
}
}
/// Poll configured Gitea issues for new @adf: mentions and enqueue MentionDriven tasks.
///
/// Skipped when no mention configuration is present or when the Gitea tracker
/// is not configured. Uses `tick_count % poll_modulo` to avoid polling on
/// every reconciliation tick.
/// Cursor-based mention polling: single API call, no replay on restart.
///
/// Handle a dispatch request received from the webhook endpoint.
/// This is the webhook equivalent of poll_mentions but immediate.
async fn handle_webhook_dispatch(&mut self, dispatch: webhook::WebhookDispatch) {
// Rate limiting: check concurrent mention-spawned agents
let mention_cfg = match self.config.mentions.as_ref() {
Some(cfg) => cfg,
None => return,
};
let active_mention_agents = self
.active_agents
.values()
.filter(|a| a.spawned_by_mention)
.count() as u32;
if active_mention_agents >= mention_cfg.max_concurrent_mention_agents {
warn!(
active = active_mention_agents,
max = mention_cfg.max_concurrent_mention_agents,
"webhook dispatch rejected: mention agents at capacity"
);
return;
}
let agents = self.config.agents.clone();
let agent_names: Vec<String> = agents.iter().map(|a| a.name.clone()).collect();
let max_mention_depth = mention_cfg.max_mention_depth;
match dispatch {
webhook::WebhookDispatch::SpawnAgent {
agent_name,
detected_project,
issue_number,
comment_id,
context,
} => {
info!(
agent = %agent_name,
project = ?detected_project,
issue = issue_number,
comment_id = comment_id,
"webhook: dispatching agent spawn"
);
// Use project-aware resolver. For webhook dispatches we don't know which
// project's repo the webhook came from, so we use LEGACY_PROJECT_ID as the
// hint for unqualified mentions; qualified mentions carry detected_project.
if let Some(def) = mention::resolve_mention(
detected_project.as_deref(),
dispatcher::LEGACY_PROJECT_ID,
&agent_name,
&agents,
) {
// Event-only agents (e.g. build-runner) must not be dispatched
// from comment mentions. They are spawned by handle_push or
// other event handlers with the appropriate context env vars.
// Rejecting here prevents ghost-issue posts and wasted spawns.
if def.event_only {
info!(
agent = %agent_name,
issue = issue_number,
comment_id = comment_id,
"webhook dispatch rejected: agent is event-only (push/event-driven), not mention-dispatchable"
);
return;
}
// Dedup: check Gitea assignment + active_agents before spawning
if self.should_skip_dispatch(&agent_name, issue_number).await {
return;
}
let chain_id = ulid::Ulid::new().to_string();
let depth: u32 = 0;
let parent_agent = String::new();
if let Err(e) = mention_chain::MentionChainTracker::check(
depth,
&parent_agent,
&agent_name,
max_mention_depth,
) {
warn!(
agent = %agent_name,
chain_id = %chain_id,
depth,
error = %e,
"webhook mention chain check rejected dispatch"
);
if let Some(ref poster) = self.output_poster {
let body = format!(
"## Mention Dispatch Blocked\n\n\
Agent `{}` was not spawned: {}.\n\n\
_Webhook chain `{}` blocked._",
agent_name, e, chain_id
);
if let Err(pe) = poster.post_raw(issue_number, &body).await {
warn!(error = %pe, "failed to post webhook chain rejection comment");
}
}
return;
}
let ctx_args = mention_chain::MentionContextArgs {
parent_agent: parent_agent.clone(),
issue_number,
comment_body: context.clone(),
depth,
chain_id: chain_id.clone(),
available_agents: agent_names
.iter()
.filter(|n| *n != &agent_name)
.cloned()
.collect(),
};
let chain_ctx = mention_chain::MentionChainTracker::build_context(
&ctx_args,
max_mention_depth,
);
let mut mention_def = def.clone();
mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
mention_def.gitea_issue = Some(issue_number);
if let Err(e) = self.spawn_agent(&mention_def).await {
error!(agent = %agent_name, issue = issue_number, error = %e, "webhook: failed to spawn agent");
} else if let Some(agent) = self.active_agents.get_mut(&mention_def.name) {
agent.spawned_by_mention = true;
agent.mention_chain_id = Some(chain_id);
agent.mention_depth = Some(depth);
agent.mention_parent_agent = None;
}
}
}
webhook::WebhookDispatch::SpawnPersona {
persona_name,
issue_number,
comment_id: _,
context,
} => {
if let Some((agent_name, _)) = mention::resolve_persona_mention(
&persona_name,
&agents,
&self.persona_registry,
&context,
) {
info!(
persona = %persona_name,
agent = %agent_name,
issue = issue_number,
"webhook: dispatching persona-resolved agent"
);
if let Some(def) = agents.iter().find(|a| a.name == agent_name).cloned() {
// Event-only agents must not be dispatched via persona-mention
// either. Same rationale as the SpawnAgent arm.
if def.event_only {
info!(
persona = %persona_name,
agent = %agent_name,
issue = issue_number,
"webhook dispatch rejected: persona-resolved agent is event-only (push/event-driven), not mention-dispatchable"
);
return;
}
// Dedup: check Gitea assignment + active_agents before spawning
if self.should_skip_dispatch(&agent_name, issue_number).await {
return;
}
let chain_id = ulid::Ulid::new().to_string();
let depth: u32 = 0;
let parent_agent = String::new();
if let Err(e) = mention_chain::MentionChainTracker::check(
depth,
&parent_agent,
&agent_name,
max_mention_depth,
) {
warn!(
agent = %agent_name,
chain_id = %chain_id,
depth,
error = %e,
"webhook mention chain check rejected persona dispatch"
);
if let Some(ref poster) = self.output_poster {
let body = format!(
"## Mention Dispatch Blocked\n\n\
Agent `{}` (via persona) was not spawned: {}.\n\n\
_Webhook chain `{}` blocked._",
agent_name, e, chain_id
);
if let Err(pe) = poster.post_raw(issue_number, &body).await {
warn!(error = %pe, "failed to post webhook chain rejection comment");
}
}
return;
}
let ctx_args = mention_chain::MentionContextArgs {
parent_agent: parent_agent.clone(),
issue_number,
comment_body: context.clone(),
depth,
chain_id: chain_id.clone(),
available_agents: agent_names
.iter()
.filter(|n| *n != &agent_name)
.cloned()
.collect(),
};
let chain_ctx = mention_chain::MentionChainTracker::build_context(
&ctx_args,
max_mention_depth,
);
let mut mention_def = def.clone();
mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
mention_def.gitea_issue = Some(issue_number);
if let Err(e) = self.spawn_agent(&mention_def).await {
error!(agent = %agent_name, issue = issue_number, error = %e, "webhook: failed to spawn agent");
} else if let Some(agent) = self.active_agents.get_mut(&mention_def.name) {
agent.spawned_by_mention = true;
agent.mention_chain_id = Some(chain_id);
agent.mention_depth = Some(depth);
agent.mention_parent_agent = None;
}
}
}
}
webhook::WebhookDispatch::CompoundReview {
issue_number,
comment_id,
} => {
info!(
issue = issue_number,
comment_id = comment_id,
"webhook: compound review triggered"
);
self.handle_schedule_event(ScheduleEvent::CompoundReview)
.await;
// Post acknowledgment via existing output_poster
if let Some(ref poster) = self.output_poster {
let ack_body = format!(
"## Compound Review Triggered (webhook)\n\n\
Manual trigger received from issue #{} comment {}.\n\
Running 6-agent review swarm now...",
issue_number, comment_id
);
if let Err(e) = poster.post_raw(issue_number, &ack_body).await {
warn!(error = %e, "failed to post compound review acknowledgment");
}
}
}
webhook::WebhookDispatch::ReviewPr {
pr_number,
project,
head_sha,
author_login,
title,
diff_loc,
} => {
info!(
pr = pr_number,
project = %project,
head_sha = %head_sha,
author = %author_login,
diff_loc = diff_loc,
"webhook: enqueuing ReviewPr dispatch task"
);
self.dispatcher.enqueue(dispatcher::DispatchTask::ReviewPr {
pr_number,
project,
head_sha,
author_login,
title,
diff_loc,
});
}
webhook::WebhookDispatch::Push {
project,
ref_name,
before_sha,
after_sha,
pusher_login,
files_changed,
} => {
info!(
project = %project,
ref_name = %ref_name,
after_sha = %after_sha,
pusher = %pusher_login,
files = files_changed.len(),
"webhook: enqueuing Push dispatch task"
);
self.dispatcher.enqueue(dispatcher::DispatchTask::Push {
project,
ref_name,
before_sha,
after_sha,
pusher_login,
files_changed,
});
}
}
}
/// Uses repo-wide comments endpoint with `since` cursor. On first run
/// (no persisted cursor), cursor is set to `now` to skip all historical
/// mentions — preventing the mention replay storm.
async fn poll_mentions(&mut self) {
// Build the list of (project_id, gitea_cfg, mention_cfg) targets.
//
// - Legacy mode (no `[[projects]]`): one pass under the synthetic
// `__global__` id using the top-level `gitea` and `mentions`.
// - Multi-project mode: one pass per configured project that
// declares a `gitea` block. Per-project `mentions` override the
// top-level `mentions`, which in turn falls back to
// `MentionConfig::default()` so operators need not repeat caps
// in every project.
let targets: Vec<(String, config::GiteaOutputConfig, config::MentionConfig)> =
if self.config.projects.is_empty() {
match (self.config.mentions.clone(), self.config.gitea.clone()) {
(Some(m), Some(g)) => {
vec![(dispatcher::LEGACY_PROJECT_ID.to_string(), g, m)]
}
_ => {
tracing::debug!(
"mention polling skipped: legacy mode but no Gitea/mentions config"
);
return;
}
}
} else {
let global_mentions = self.config.mentions.clone();
self.config
.projects
.iter()
.filter_map(|project| {
if project.gitea.is_none() {
tracing::debug!(
project = project.id.as_str(),
"skipping mention poll: project has no gitea config"
);
}
let gitea = project.gitea.clone()?;
let mentions = project
.mentions
.clone()
.or_else(|| global_mentions.clone())
.unwrap_or_default();
Some((project.id.clone(), gitea, mentions))
})
.collect()
};
if targets.is_empty() {
tracing::debug!("mention polling skipped: no projects with Gitea config");
return;
}
for (project_id, gitea_cfg, mention_cfg) in targets {
self.poll_mentions_for_project(&project_id, &gitea_cfg, &mention_cfg)
.await;
}
}
/// Run a single mention-poll pass for one project.
///
/// Invoked by [`AgentOrchestrator::poll_mentions`] for each configured
/// project (or once for legacy single-project mode under
/// `__global__`). Loads/persists the project's cursor, honours the
/// project's `MentionConfig`, and threads `project_id` onto every
/// dispatched mention.
async fn poll_mentions_for_project(
&mut self,
project_id: &str,
gitea_cfg: &config::GiteaOutputConfig,
mention_cfg: &config::MentionConfig,
) {
// Respect poll_modulo to reduce API traffic.
if self.tick_count % mention_cfg.poll_modulo != 0 {
return;
}
// Count currently active mention-spawned agents for this project.
//
// We filter by the agent definition's project field so one noisy
// project cannot exhaust the fleet-wide mention budget for others.
// In legacy mode (project_id == "__global__") every agent
// contributes because project binding isn't meaningful there.
let active_mention_agents = if project_id == dispatcher::LEGACY_PROJECT_ID {
self.active_agents
.values()
.filter(|a| a.spawned_by_mention)
.count() as u32
} else {
self.active_agents
.values()
.filter(|a| {
a.spawned_by_mention && a.definition.project.as_deref() == Some(project_id)
})
.count() as u32
};
if active_mention_agents >= mention_cfg.max_concurrent_mention_agents {
tracing::debug!(
project = project_id,
active = active_mention_agents,
max = mention_cfg.max_concurrent_mention_agents,
"mention agents at capacity, skipping poll"
);
return;
}
// Lazy-load the project's cursor.
let mut cursor = match self.mention_cursors.remove(project_id) {
Some(c) => c,
None => mention::MentionCursor::load_or_now(project_id).await,
};
cursor.dispatches_this_tick = 0;
// Create Gitea tracker for repo-wide comment polling
let tracker_cfg = terraphim_tracker::GiteaConfig {
base_url: gitea_cfg.base_url.clone(),
token: gitea_cfg.token.clone(),
owner: gitea_cfg.owner.clone(),
repo: gitea_cfg.repo.clone(),
active_states: vec!["open".to_string()],
terminal_states: vec!["closed".to_string()],
use_robot_api: false,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
let tracker = match terraphim_tracker::GiteaTracker::new(tracker_cfg) {
Ok(t) => t,
Err(e) => {
tracing::warn!(
project = project_id,
error = %e,
"failed to create GiteaTracker for mention polling"
);
self.mention_cursors.insert(project_id.to_string(), cursor);
return;
}
};
// Single API call: all comments since cursor
let comments = match tracker
.fetch_repo_comments(Some(&cursor.last_seen_at), Some(50))
.await
{
Ok(c) => c,
Err(e) => {
tracing::warn!(
project = project_id,
error = %e,
"failed to fetch repo comments for mention polling"
);
self.mention_cursors.insert(project_id.to_string(), cursor);
return;
}
};
if comments.is_empty() {
cursor.save(project_id).await;
self.mention_cursors.insert(project_id.to_string(), cursor);
return;
}
let agents = self.config.agents.clone();
let persona_registry = self.persona_registry.clone();
let max_dispatches = mention_cfg.max_dispatches_per_tick;
// Build ADF command parser with known agents and personas
let agent_names: Vec<String> = agents.iter().map(|a| a.name.clone()).collect();
let persona_names: Vec<String> = persona_registry
.persona_names()
.into_iter()
.map(|s| s.to_string())
.collect();
let command_parser =
crate::adf_commands::AdfCommandParser::new(&agent_names, &persona_names);
let max_mention_depth = mention_cfg.max_mention_depth;
for comment in &comments {
if cursor.dispatches_this_tick >= max_dispatches {
tracing::debug!(
dispatched = cursor.dispatches_this_tick,
max = max_dispatches,
"max dispatches per tick reached"
);
break;
}
// Skip already-processed comments (persisted dedup across restarts)
if cursor.is_processed(comment.id) {
tracing::debug!(
comment_id = comment.id,
issue = comment.issue_number,
"skipping already-processed comment"
);
cursor.advance_to(&comment.created_at);
continue;
}
// Parse ADF commands using terraphim-automata Aho-Corasick
let commands =
command_parser.parse_commands(&comment.body, comment.issue_number, comment.id);
// Handle qualified `@adf:project/name` mentions that AdfCommandParser cannot
// see (its patterns are `@adf:{name}`; a `project/` prefix is not a substring).
for token in mention::parse_mention_tokens(&comment.body) {
if cursor.dispatches_this_tick >= max_dispatches {
break;
}
let proj = match token.project.as_deref() {
Some(p) => p,
None => continue, // unqualified mentions are handled by parse_commands below
};
match mention::resolve_mention(Some(proj), project_id, &token.agent, &agents) {
Some(def) => {
info!(
agent = %token.agent,
project = proj,
issue = comment.issue_number,
comment_id = comment.id,
"dispatching qualified mention-driven agent"
);
// Event-only agents (e.g. build-runner) must not be dispatched
// from comment mentions. Reject before any spawn-related work.
if def.event_only {
info!(
agent = %token.agent,
issue = comment.issue_number,
comment_id = comment.id,
"poll mention dispatch rejected: agent is event-only (push/event-driven), not mention-dispatchable"
);
cursor.dispatches_this_tick += 1;
continue;
}
if self
.should_skip_dispatch(&token.agent, comment.issue_number)
.await
{
cursor.dispatches_this_tick += 1;
continue;
}
let (chain_id, depth, parent_agent) = self.resolve_mention_chain(
&comment.user.login,
&agent_names,
max_mention_depth,
);
if let Err(e) = mention_chain::MentionChainTracker::check(
depth,
&parent_agent,
&token.agent,
max_mention_depth,
) {
warn!(
agent = %token.agent,
chain_id = %chain_id,
depth,
error = %e,
"mention chain check rejected dispatch"
);
if let Some(ref poster) = self.output_poster {
let body = format!(
"## Mention Dispatch Blocked\n\n\
Agent `{}` was not spawned: {}.\n\n\
_Chain `{}` at depth {} exceeds the configured limit._",
token.agent, e, chain_id, depth
);
if let Err(pe) = poster
.post_raw_for_project(project_id, comment.issue_number, &body)
.await
{
warn!(error = %pe, "failed to post chain rejection comment");
}
}
cursor.dispatches_this_tick += 1;
continue;
}
let ctx_args = mention_chain::MentionContextArgs {
parent_agent: parent_agent.clone(),
issue_number: comment.issue_number,
comment_body: comment.body.clone(),
depth,
chain_id: chain_id.clone(),
available_agents: agent_names
.iter()
.filter(|n| *n != &token.agent)
.cloned()
.collect(),
};
let chain_ctx = mention_chain::MentionChainTracker::build_context(
&ctx_args,
max_mention_depth,
);
let mut mention_def = def.clone();
mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
mention_def.gitea_issue = Some(comment.issue_number);
if let Err(e) = self.spawn_agent(&mention_def).await {
tracing::error!(
agent = %token.agent,
project = proj,
issue = comment.issue_number,
error = %e,
"failed to spawn agent for qualified mention"
);
} else if let Some(active) = self.active_agents.get_mut(&mention_def.name) {
active.spawned_by_mention = true;
active.mention_chain_id = Some(chain_id);
active.mention_depth = Some(depth);
active.mention_parent_agent = if parent_agent.is_empty() {
None
} else {
Some(parent_agent)
};
}
cursor.dispatches_this_tick += 1;
}
None => {
tracing::warn!(
mention = format!("@adf:{}/{}", proj, token.agent),
project = project_id,
issue = comment.issue_number,
"qualified mention matched no agent"
);
}
}
}
for cmd in commands {
if cursor.dispatches_this_tick >= max_dispatches {
break;
}
match cmd {
crate::adf_commands::AdfCommand::CompoundReview {
issue_number,
comment_id,
} => {
info!(
issue = issue_number,
comment_id = comment_id,
"compound review triggered via @adf:compound-review mention"
);
// Trigger compound review
self.handle_schedule_event(ScheduleEvent::CompoundReview)
.await;
// Post acknowledgment
if let Some(ref poster) = self.output_poster {
let ack_body = format!(
"## 🔍 Compound Review Triggered\n\n\
Manual trigger received from issue #{} comment {}.\n\
Running 6-agent review swarm now...\n\n\
_Results will be posted to issue #{} when complete._",
issue_number,
comment_id,
self.config.compound_review.gitea_issue.unwrap_or(108)
);
if let Err(e) = poster.post_raw(issue_number, &ack_body).await {
warn!(error = %e, "failed to post compound review acknowledgment");
}
}
cursor.dispatches_this_tick += 1;
}
crate::adf_commands::AdfCommand::SpawnAgent {
agent_name,
issue_number,
comment_id,
context,
} => {
info!(
agent = %agent_name,
issue = issue_number,
comment_id = comment_id,
"dispatching mention-driven agent via terraphim-automata parser"
);
if let Some(def) =
mention::resolve_mention(None, project_id, &agent_name, &agents)
{
// Event-only agents (e.g. build-runner) must not be dispatched
// from comment mentions. Reject before any spawn-related work.
if def.event_only {
info!(
agent = %agent_name,
issue = issue_number,
comment_id = comment_id,
"poll mention dispatch rejected: agent is event-only (push/event-driven), not mention-dispatchable"
);
cursor.dispatches_this_tick += 1;
continue;
}
if self.should_skip_dispatch(&agent_name, issue_number).await {
cursor.dispatches_this_tick += 1;
continue;
}
let (chain_id, depth, parent_agent) = self.resolve_mention_chain(
&comment.user.login,
&agent_names,
max_mention_depth,
);
if let Err(e) = mention_chain::MentionChainTracker::check(
depth,
&parent_agent,
&agent_name,
max_mention_depth,
) {
warn!(
agent = %agent_name,
chain_id = %chain_id,
depth,
error = %e,
"mention chain check rejected dispatch"
);
if let Some(ref poster) = self.output_poster {
let body = format!(
"## Mention Dispatch Blocked\n\n\
Agent `{}` was not spawned: {}.\n\n\
_Chain `{}` at depth {} exceeds the configured limit._",
agent_name, e, chain_id, depth
);
if let Err(pe) = poster
.post_raw_for_project(project_id, issue_number, &body)
.await
{
warn!(error = %pe, "failed to post chain rejection comment");
}
}
cursor.dispatches_this_tick += 1;
continue;
}
let ctx_args = mention_chain::MentionContextArgs {
parent_agent: parent_agent.clone(),
issue_number,
comment_body: context.clone(),
depth,
chain_id: chain_id.clone(),
available_agents: agent_names
.iter()
.filter(|n| *n != &agent_name)
.cloned()
.collect(),
};
let chain_ctx = mention_chain::MentionChainTracker::build_context(
&ctx_args,
max_mention_depth,
);
let mut mention_def = def.clone();
mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
mention_def.gitea_issue = Some(issue_number);
if let Err(e) = self.spawn_agent(&mention_def).await {
tracing::error!(agent = %agent_name, issue = issue_number, error = %e, "failed to spawn agent");
} else if let Some(agent) =
self.active_agents.get_mut(&mention_def.name)
{
agent.spawned_by_mention = true;
agent.mention_chain_id = Some(chain_id);
agent.mention_depth = Some(depth);
agent.mention_parent_agent = if parent_agent.is_empty() {
None
} else {
Some(parent_agent)
};
}
cursor.dispatches_this_tick += 1;
}
}
crate::adf_commands::AdfCommand::SpawnPersona {
persona_name,
issue_number,
comment_id: _,
context,
} => {
// Resolve persona to agent
if let Some((agent_name, _)) = mention::resolve_persona_mention(
&persona_name,
&agents,
&persona_registry,
&context,
) {
info!(
persona = %persona_name,
agent = %agent_name,
issue = issue_number,
"dispatching persona-resolved agent via terraphim-automata parser"
);
if let Some(def) = agents.iter().find(|a| a.name == agent_name).cloned()
{
// Event-only agents (e.g. build-runner) must not be dispatched
// from persona mentions. Reject before any spawn-related work.
if def.event_only {
info!(
persona = %persona_name,
agent = %agent_name,
issue = issue_number,
"poll mention dispatch rejected: persona-resolved agent is event-only (push/event-driven), not mention-dispatchable"
);
cursor.dispatches_this_tick += 1;
continue;
}
// Dedup: check Gitea assignment + active_agents before spawning
if self.should_skip_dispatch(&agent_name, issue_number).await {
cursor.dispatches_this_tick += 1;
continue;
}
let (chain_id, depth, parent_agent) = self.resolve_mention_chain(
&comment.user.login,
&agent_names,
max_mention_depth,
);
if let Err(e) = mention_chain::MentionChainTracker::check(
depth,
&parent_agent,
&agent_name,
max_mention_depth,
) {
warn!(
agent = %agent_name,
chain_id = %chain_id,
depth,
error = %e,
"mention chain check rejected persona dispatch"
);
if let Some(ref poster) = self.output_poster {
let body = format!(
"## Mention Dispatch Blocked\n\n\
Agent `{}` (via persona) was not spawned: {}.\n\n\
_Chain `{}` at depth {} exceeds the configured limit._",
agent_name, e, chain_id, depth
);
if let Err(pe) = poster
.post_raw_for_project(project_id, issue_number, &body)
.await
{
warn!(error = %pe, "failed to post chain rejection comment");
}
}
cursor.dispatches_this_tick += 1;
continue;
}
let ctx_args = mention_chain::MentionContextArgs {
parent_agent: parent_agent.clone(),
issue_number,
comment_body: context.clone(),
depth,
chain_id: chain_id.clone(),
available_agents: agent_names
.iter()
.filter(|n| *n != &agent_name)
.cloned()
.collect(),
};
let chain_ctx = mention_chain::MentionChainTracker::build_context(
&ctx_args,
max_mention_depth,
);
let mut mention_def = def.clone();
mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
mention_def.gitea_issue = Some(issue_number);
if let Err(e) = self.spawn_agent(&mention_def).await {
tracing::error!(agent = %agent_name, issue = issue_number, error = %e, "failed to spawn agent");
} else if let Some(agent) =
self.active_agents.get_mut(&mention_def.name)
{
agent.spawned_by_mention = true;
agent.mention_chain_id = Some(chain_id);
agent.mention_depth = Some(depth);
agent.mention_parent_agent = if parent_agent.is_empty() {
None
} else {
Some(parent_agent)
};
}
cursor.dispatches_this_tick += 1;
}
}
}
crate::adf_commands::AdfCommand::Unknown { raw } => {
warn!(raw = %raw, "unknown ADF command");
}
}
}
// Mark comment as processed and advance cursor
cursor.mark_processed(comment.id);
cursor.advance_to(&comment.created_at);
}
// Persist cursor for next poll / restart
cursor.save(project_id).await;
self.mention_cursors.insert(project_id.to_string(), cursor);
}
/// Poll every project with a Gitea config for open PRs, parse the latest
/// structural-pr-review comment, and enqueue [`dispatcher::DispatchTask::AutoMerge`]
/// for any PR that clears every gate in
/// [`pr_review::AutoMergeCriteria::default`].
///
/// Called once per reconcile tick after the
/// dispatcher has been drained so AutoMerge tasks enqueued here are
/// serviced on the next tick (deterministic ordering). The method is a
/// no-op when no project has a `gitea` config.
///
/// This is ROC v1 Step F — it enqueues auto-merge but does **not**
/// actually merge the PR; that lands in Step G. Dedupe is process-local
/// via [`pr_poller::AutoMergeDedupeSet`]; durable tracking is Step I.
pub async fn poll_pending_reviews(&mut self) -> Result<(), OrchestratorError> {
// Build the list of (project_id, gitea_cfg) targets. Mirrors the
// legacy/multi-project split used by [`Self::poll_mentions`] so the
// two pollers stay aligned as the config surface evolves.
let targets: Vec<(String, config::GiteaOutputConfig)> = if self.config.projects.is_empty() {
match self.config.gitea.clone() {
Some(g) => vec![(dispatcher::LEGACY_PROJECT_ID.to_string(), g)],
None => {
tracing::debug!(
"verdict polling skipped: legacy mode with no top-level gitea config"
);
return Ok(());
}
}
} else {
self.config
.projects
.iter()
.filter_map(|project| {
let gitea = project.gitea.clone()?;
Some((project.id.clone(), gitea))
})
.collect()
};
if targets.is_empty() {
tracing::debug!("verdict polling skipped: no projects with Gitea config");
return Ok(());
}
let criteria = pr_review::AutoMergeCriteria::default();
for (project_id, gitea_cfg) in targets {
let tracker_cfg = terraphim_tracker::GiteaConfig {
base_url: gitea_cfg.base_url.clone(),
token: gitea_cfg.token.clone(),
owner: gitea_cfg.owner.clone(),
repo: gitea_cfg.repo.clone(),
active_states: vec!["open".to_string()],
terminal_states: vec!["closed".to_string()],
use_robot_api: false,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
let tracker = match terraphim_tracker::GiteaTracker::new(tracker_cfg) {
Ok(t) => pr_poller::GiteaPrTracker::new(t),
Err(e) => {
tracing::warn!(
project = %project_id,
error = %e,
"failed to create GiteaTracker for verdict polling"
);
continue;
}
};
self.poll_pending_reviews_for_project(&project_id, &tracker, &criteria)
.await;
}
Ok(())
}
/// Inner per-project verdict poll. Accepts a generic [`pr_poller::PrTracker`]
/// so integration tests can drive it with an in-memory tracker.
pub async fn poll_pending_reviews_for_project<T: pr_poller::PrTracker + ?Sized>(
&mut self,
project_id: &str,
tracker: &T,
criteria: &pr_review::AutoMergeCriteria,
) {
let prs = match tracker.list_open_prs().await {
Ok(prs) => prs,
Err(e) => {
tracing::warn!(
project = %project_id,
error = %e,
"failed to list open PRs"
);
return;
}
};
let now = std::time::Instant::now();
for pr in prs {
if !self.pr_poll_rate_limiter.allow(project_id, pr.number, now) {
tracing::trace!(
project = %project_id,
pr = pr.number,
"skipping PR: poll rate limited"
);
continue;
}
let comments = match tracker.fetch_pr_comments(pr.number).await {
Ok(c) => c,
Err(e) => {
tracing::warn!(
project = %project_id,
pr = pr.number,
error = %e,
"failed to fetch PR comments"
);
continue;
}
};
let outcome = pr_poller::evaluate_pr_verdict(&pr, &comments, criteria);
// Emit PrReviewed for any outcome that resolved a parsed verdict.
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let has_verdict = matches!(
outcome,
pr_poller::EvaluationOutcome::Merge { .. }
| pr_poller::EvaluationOutcome::HumanReviewNeeded { .. }
);
if has_verdict {
if let Some(rc) = pr_poller::latest_reviewer_comment(&comments) {
if let Ok(v) = pr_review::parse_verdict(&rc.body, rc.id) {
let verdict_str = match &outcome {
pr_poller::EvaluationOutcome::Merge { .. } => "GO",
_ if v.p0_count > 0 => "NO-GO",
_ => "CONDITIONAL",
};
let event = quickwit::OrchestratorEvent::PrReviewed {
pr_number: pr.number,
project: project_id.to_string(),
head_sha: pr.head_sha.clone(),
reviewer_login: rc.user_login.clone(),
confidence: v.confidence,
p0_count: v.p0_count,
p1_count: v.p1_count,
verdict: verdict_str.to_string(),
};
let _ = sink.emit_event(project_id, event).await;
}
}
}
}
match outcome {
pr_poller::EvaluationOutcome::Merge { head_sha } => {
if !self
.auto_merge_enqueued
.record_if_new(project_id, pr.number, &head_sha)
{
tracing::debug!(
project = %project_id,
pr = pr.number,
head = %head_sha,
"auto-merge already enqueued for this revision"
);
continue;
}
tracing::info!(
project = %project_id,
pr = pr.number,
head = %head_sha,
"enqueuing AutoMerge for PR that cleared every gate"
);
self.dispatcher.enqueue(DispatchTask::AutoMerge {
pr_number: pr.number,
project: project_id.to_string(),
head_sha,
});
}
pr_poller::EvaluationOutcome::HumanReviewNeeded { reason } => {
tracing::info!(
project = %project_id,
pr = pr.number,
reason = %reason,
"PR requires human review"
);
}
pr_poller::EvaluationOutcome::NoReviewerComment => {
tracing::debug!(
project = %project_id,
pr = pr.number,
"no pr-reviewer comment yet; skipping"
);
}
pr_poller::EvaluationOutcome::ParseError { reason } => {
tracing::warn!(
project = %project_id,
pr = pr.number,
reason = %reason,
"reviewer comment failed to parse; skipping"
);
}
}
}
}
/// Execute a [`DispatchTask::AutoMerge`] task — ROC v1 Step G.
///
/// Builds the per-project [`pr_poller::GiteaPrTracker`] from config and
/// delegates to [`AgentOrchestrator::handle_auto_merge_for_project`].
/// The task's `project` field must match a configured project with a
/// `gitea` block (or, for legacy configs, the top-level `gitea`);
/// otherwise the call logs-and-skips so the dispatcher keeps draining.
pub async fn handle_auto_merge(
&mut self,
task: dispatcher::DispatchTask,
) -> Result<(), OrchestratorError> {
let (pr_number, project, head_sha) = match &task {
dispatcher::DispatchTask::AutoMerge {
pr_number,
project,
head_sha,
} => (*pr_number, project.clone(), head_sha.clone()),
other => {
warn!(task = ?other, "handle_auto_merge invoked with non-AutoMerge task; ignoring");
return Ok(());
}
};
// Resolve the Gitea config for this project. Mirrors the legacy /
// multi-project split used by `poll_pending_reviews`.
let gitea_cfg: config::GiteaOutputConfig = if self.config.projects.is_empty() {
match self.config.gitea.clone() {
Some(g) if project == dispatcher::LEGACY_PROJECT_ID => g,
Some(_) => {
warn!(
pr_number,
project = %project,
"AutoMerge skipped: legacy mode but task project id does not match LEGACY_PROJECT_ID"
);
return Ok(());
}
None => {
warn!(
pr_number,
project = %project,
"AutoMerge skipped: legacy mode with no top-level gitea config"
);
return Ok(());
}
}
} else {
match self
.config
.projects
.iter()
.find(|p| p.id == project)
.and_then(|p| p.gitea.clone())
{
Some(g) => g,
None => {
warn!(
pr_number,
project = %project,
"AutoMerge skipped: project has no gitea config"
);
return Ok(());
}
}
};
let tracker_cfg = terraphim_tracker::GiteaConfig {
base_url: gitea_cfg.base_url.clone(),
token: gitea_cfg.token.clone(),
owner: gitea_cfg.owner.clone(),
repo: gitea_cfg.repo.clone(),
active_states: vec!["open".to_string()],
terminal_states: vec!["closed".to_string()],
use_robot_api: false,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
let tracker = match terraphim_tracker::GiteaTracker::new(tracker_cfg) {
Ok(t) => pr_poller::GiteaPrTracker::new(t),
Err(e) => {
warn!(
pr_number,
project = %project,
head = %head_sha,
error = %e,
"AutoMerge skipped: failed to create GiteaTracker"
);
return Ok(());
}
};
self.handle_auto_merge_for_project(task, &tracker).await
}
/// Inner AutoMerge executor. Accepts any [`pr_poller::AutoMergeExecutor`]
/// so integration tests can drive the full handler with an in-memory
/// tracker. Real production code funnels through
/// [`AgentOrchestrator::handle_auto_merge`].
///
/// Steps:
/// 1. Defensive re-check: list open PRs on the project. Skip when the
/// PR is absent (already closed/merged) or the HEAD SHA has moved.
/// 2. Attempt the merge.
/// 3. On success — enqueue [`DispatchTask::PostMergeTestGate`], record
/// the `(pr, head_sha)` in the dedupe set so late polls never
/// re-enqueue the same revision.
/// 4. On failure — open an `[ADF]` tracking issue with the failure
/// reason via [`pr_poller::AutoMergeExecutor::open_failure_issue`];
/// do **not** enqueue a post-merge gate.
pub async fn handle_auto_merge_for_project<T: pr_poller::AutoMergeExecutor + ?Sized>(
&mut self,
task: dispatcher::DispatchTask,
tracker: &T,
) -> Result<(), OrchestratorError> {
let (pr_number, project, head_sha) = match task {
dispatcher::DispatchTask::AutoMerge {
pr_number,
project,
head_sha,
} => (pr_number, project, head_sha),
other => {
warn!(task = ?other, "handle_auto_merge_for_project invoked with non-AutoMerge task; ignoring");
return Ok(());
}
};
// 1. Defensive re-check: ensure the PR is still open and the HEAD
// SHA matches what the verdict was computed against. If either has
// moved, the merge decision is stale — skip silently.
let open_prs = match tracker.list_open_prs().await {
Ok(prs) => prs,
Err(e) => {
warn!(
pr_number,
project = %project,
head = %head_sha,
error = %e,
"AutoMerge skipped: failed to list open PRs for head_sha re-check"
);
return Ok(());
}
};
let live = match open_prs.iter().find(|p| p.number == pr_number) {
Some(p) => p,
None => {
info!(
pr_number,
project = %project,
head = %head_sha,
"AutoMerge skipped: PR no longer in open list (closed/merged already)"
);
return Ok(());
}
};
if live.head_sha != head_sha {
info!(
pr_number,
project = %project,
expected_head = %head_sha,
live_head = %live.head_sha,
"AutoMerge skipped: PR HEAD SHA moved since verdict (stale auto-merge decision)"
);
return Ok(());
}
// 2. Merge.
match tracker.merge_pr(pr_number).await {
Ok(outcome) => {
info!(
pr_number,
project = %project,
merge_sha = %outcome.merge_commit_sha,
"pr_auto_merged"
);
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let event = quickwit::OrchestratorEvent::PrAutoMerged {
pr_number,
project: project.clone(),
merge_sha: outcome.merge_commit_sha.clone(),
title: outcome.title.clone(),
};
let _ = sink.emit_event(&project, event).await;
}
// 3a. Defensive dedupe write — covers AutoMerge tasks that
// reached the handler by a path other than the poller
// (webhook, manual enqueue, etc.). `record_if_new` is a
// no-op when the entry already exists.
let _ = self
.auto_merge_enqueued
.record_if_new(&project, pr_number, &head_sha);
// 3b. Enqueue the post-merge test gate (Step H stub).
self.dispatcher
.enqueue(dispatcher::DispatchTask::PostMergeTestGate {
pr_number,
project: project.clone(),
merge_sha: outcome.merge_commit_sha,
title: outcome.title,
});
Ok(())
}
Err(e) => {
warn!(
pr_number,
project = %project,
head = %head_sha,
error = %e,
"pr_auto_merge_failed"
);
// 4. Open an [ADF] tracking issue with the failure reason,
// unless we already created one for this (project, pr, sha)
// within the TTL window.
if self
.auto_merge_failure_dedupe
.is_recent(&project, pr_number, &head_sha)
{
info!(
pr_number,
project = %project,
head = %head_sha,
"AutoMerge failure issue already exists for this PR/SHA; skipping duplicate"
);
} else {
let title = format!("[ADF] Auto-merge failed for PR #{pr_number}");
let body = format!(
"AutoMerge handler failed to merge PR #{pr_number} on project `{project}`.\n\n\
Head SHA: `{head_sha}`\n\n\
Error: {e}\n\n\
The PR was left open; a human needs to investigate (merge conflict, \
protected branch, permissions, transient API failure).\n\n\
Refs: ROC v1 Step G handler, adf-fleet#35."
);
let labels = ["adf", "auto-merge-failed", "status/needs-triage"];
self.auto_merge_failure_dedupe
.record(&project, pr_number, &head_sha);
match tracker.open_failure_issue(&title, &body, &labels).await {
Ok(_issue_number) => {}
Err(issue_err) => {
warn!(
pr_number,
project = %project,
error = %issue_err,
"AutoMerge failure issue creation also failed; nothing to retry automatically"
);
}
}
}
Ok(())
}
}
}
/// Execute a [`DispatchTask::PostMergeTestGate`] task — ROC v1 Step H.
///
/// Defers the heavy lifting to [`post_merge_gate::run_workspace_tests`]
/// and [`post_merge_gate::revert_merge`] so those helpers stay fully
/// testable without orchestrator state. This method resolves the
/// project's `working_dir` as `repo_root`, constructs the [`post_merge_gate::GateConfig`]
/// (picking up any overrides from `[post_merge_gate]` in
/// orchestrator.toml), and funnels the result through the inner
/// `handle_post_merge_test_gate_for_project` helper which takes a
/// [`post_merge_gate::CommandRunner`] so integration tests can drive the
/// full handler with a scripted runner.
pub async fn handle_post_merge_test_gate(
&mut self,
task: dispatcher::DispatchTask,
) -> Result<(), OrchestratorError> {
let runner = post_merge_gate::TokioCommandRunner;
self.handle_post_merge_test_gate_with_runner(task, &runner)
.await
}
/// Inner handler that accepts any [`post_merge_gate::CommandRunner`].
/// Integration tests use a [`post_merge_gate::ScriptedRunner`] here to
/// assert on the exact `cargo test` / `git revert` / `git push` call
/// sequence without spawning real processes.
///
/// On green: logs `post_merge_gate_verified` at info.
/// On red: classifies the failure, runs `git revert`, pushes to the
/// configured remote, opens an `[ADF] post-merge test gate reverted`
/// tracking issue on the project's Gitea repo, and logs
/// `post_merge_gate_reverted` at warn. Returns `Ok(())` in every
/// case the dispatcher should continue draining — only hard I/O
/// errors that prevent even the attempt return `Err`.
pub async fn handle_post_merge_test_gate_with_runner<R>(
&mut self,
task: dispatcher::DispatchTask,
runner: &R,
) -> Result<(), OrchestratorError>
where
R: post_merge_gate::CommandRunner + ?Sized,
{
let (pr_number, project, merge_sha, title) = match task {
dispatcher::DispatchTask::PostMergeTestGate {
pr_number,
project,
merge_sha,
title,
} => (pr_number, project, merge_sha, title),
other => {
warn!(task = ?other, "handle_post_merge_test_gate invoked with non-PostMergeTestGate task; ignoring");
return Ok(());
}
};
// Resolve repo_root + gitea tracking target for this project.
// Legacy mode uses the top-level `working_dir` and `gitea`.
let (repo_root, gitea_cfg) = if self.config.projects.is_empty() {
if project != dispatcher::LEGACY_PROJECT_ID {
warn!(
pr_number,
project = %project,
"PostMergeTestGate skipped: legacy mode but task project id does not match LEGACY_PROJECT_ID"
);
return Ok(());
}
(self.config.working_dir.clone(), self.config.gitea.clone())
} else {
match self.config.projects.iter().find(|p| p.id == project) {
Some(p) => (p.working_dir.clone(), p.gitea.clone()),
None => {
warn!(
pr_number,
project = %project,
"PostMergeTestGate skipped: no project entry for id"
);
return Ok(());
}
}
};
// Build GateConfig from orchestrator overrides (if any).
let gate_override = self.config.post_merge_gate.clone().unwrap_or_default();
let cfg = post_merge_gate::GateConfig {
repo_root,
merge_sha: merge_sha.clone(),
max_test_duration: std::time::Duration::from_secs(gate_override.max_test_duration_secs),
revert_push_remote: gate_override.revert_push_remote,
revert_push_branch: gate_override.revert_push_branch,
};
info!(
pr_number,
project = %project,
merge_sha = %merge_sha,
max_test_duration_secs = cfg.max_test_duration.as_secs(),
title = %title,
"post_merge_gate_start"
);
let outcome = match post_merge_gate::run_workspace_tests(runner, &cfg).await {
Ok(o) => o,
Err(e) => {
warn!(
pr_number,
project = %project,
merge_sha = %merge_sha,
error = %e,
"post_merge_gate: run_workspace_tests failed before producing an outcome"
);
return Ok(());
}
};
if outcome.passed {
info!(
pr_number,
project = %project,
merge_sha = %merge_sha,
wall_time_secs = outcome.wall_time.as_secs_f64(),
"post_merge_gate_verified"
);
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let event = quickwit::OrchestratorEvent::PrAutoMergedVerified {
pr_number,
project: project.clone(),
merge_sha: merge_sha.clone(),
wall_time_secs: outcome.wall_time.as_secs_f64(),
};
let _ = sink.emit_event(&project, event).await;
}
return Ok(());
}
let classification = post_merge_gate::classify_failure(&outcome);
warn!(
pr_number,
project = %project,
merge_sha = %merge_sha,
kind = ?classification.kind,
failing_tests = ?classification.failing_tests,
wall_time_secs = outcome.wall_time.as_secs_f64(),
"post_merge_gate_failed"
);
let revert = match post_merge_gate::revert_merge(runner, &cfg).await {
Ok(r) => r,
Err(e) => {
warn!(
pr_number,
project = %project,
merge_sha = %merge_sha,
error = %e,
"post_merge_gate: revert_merge failed — manual intervention required"
);
// Still try to file the tracking issue below so a human notices.
post_merge_gate::RevertOutcome {
revert_sha: String::new(),
pushed: false,
}
}
};
warn!(
pr_number,
project = %project,
merge_sha = %merge_sha,
revert_sha = %revert.revert_sha,
pushed = revert.pushed,
reason = ?classification.kind,
"post_merge_gate_reverted"
);
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let event = quickwit::OrchestratorEvent::PrAutoReverted {
pr_number,
project: project.clone(),
merge_sha: merge_sha.clone(),
revert_sha: revert.revert_sha.clone(),
reason: format!("{:?}", classification.kind),
stderr_tail_bytes: outcome.stderr_tail.len() as u32,
};
let _ = sink.emit_event(&project, event).await;
}
// Open an [ADF] tracking issue. Best-effort — a failure here is
// logged but does not propagate: the revert has already landed.
if let Some(gitea) = gitea_cfg {
let issue_title =
format!("[ADF] post-merge test gate reverted PR #{pr_number}: {title}");
let stderr_excerpt = truncate_for_issue(&outcome.stderr_tail, 4000);
let failing_list = if classification.failing_tests.is_empty() {
"(none parsed)".to_string()
} else {
classification
.failing_tests
.iter()
.map(|t| format!("- `{t}`"))
.collect::<Vec<_>>()
.join("\n")
};
let body = format!(
"Auto-merged PR #{pr_number} on project `{project}` failed the post-merge test gate.\n\n\
Merge SHA: `{merge_sha}`\n\
Revert SHA: `{}`\n\
Revert pushed: {}\n\
Failure kind: `{:?}`\n\
Wall time: {:.1}s\n\n\
Failing tests:\n\n{failing_list}\n\n\
stderr tail (truncated):\n\n```\n{stderr_excerpt}\n```\n\n\
Refs: ROC v1 Step H, adf-fleet#36.",
revert.revert_sha,
revert.pushed,
classification.kind,
outcome.wall_time.as_secs_f64(),
);
let labels = ["adf", "post-merge-gate", "status/needs-triage"];
let tracker_cfg = terraphim_tracker::GiteaConfig {
base_url: gitea.base_url.clone(),
token: gitea.token.clone(),
owner: gitea.owner.clone(),
repo: gitea.repo.clone(),
active_states: vec!["open".to_string()],
terminal_states: vec!["closed".to_string()],
use_robot_api: false,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
match terraphim_tracker::GiteaTracker::new(tracker_cfg) {
Ok(tracker) => {
if let Err(e) = tracker.create_issue(&issue_title, &body, &labels).await {
warn!(
pr_number,
project = %project,
error = %e,
"post_merge_gate: failed to open [ADF] tracking issue"
);
}
}
Err(e) => {
warn!(
pr_number,
project = %project,
error = %e,
"post_merge_gate: failed to construct tracker for [ADF] issue"
);
}
}
} else {
warn!(
pr_number,
project = %project,
"post_merge_gate: no gitea config for project; skipping [ADF] issue creation"
);
}
Ok(())
}
/// Check if an agent is already assigned to this issue and currently active.
///
/// Returns `true` if dispatch should be **skipped** (duplicate), `false` if
/// dispatch should proceed. When dispatch proceeds, the issue is assigned
/// to the agent as a side-effect.
///
/// The dedup logic:
/// - If the issue is already assigned to the agent AND the agent is currently
/// in `active_agents` -> skip (duplicate dispatch).
/// - If assigned but agent is NOT active -> allow (agent crashed, re-dispatch).
/// - If not assigned -> allow (first dispatch) and assign.
async fn should_skip_dispatch(&self, agent_name: &str, issue_number: u64) -> bool {
if issue_number == 0 {
return false;
}
// Fast local check: if agent is already running, skip immediately.
// This prevents races where the Gitea API returns stale assignee data
// because a concurrent dispatch path just assigned the issue milliseconds ago.
if self.active_agents.contains_key(agent_name) {
warn!(
agent = %agent_name,
issue = issue_number,
"skipping dispatch: agent already active (local guard)"
);
return true;
}
let Some(ref poster) = self.output_poster else {
return false;
};
// Resolve the agent's owning project so the tracker uses the
// correct owner/repo (multi-project) or falls back to legacy.
let project = self
.config
.agents
.iter()
.find(|a| a.name == agent_name)
.and_then(|a| a.project.clone())
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string());
let Some(tracker) = poster.tracker_for(&project, agent_name) else {
warn!(
agent = %agent_name,
project = %project,
"no Gitea tracker for project; treating dispatch as not-duplicate"
);
return false;
};
// Remote check: if agent is assigned in Gitea but not active (crash recovery)
match tracker.fetch_issue_assignees(issue_number).await {
Ok(assignees) => {
if assignees.iter().any(|a| a == agent_name) {
// Already assigned -- check if agent is actively running
if self.active_agents.contains_key(agent_name) {
warn!(
agent = %agent_name,
issue = issue_number,
"skipping duplicate dispatch: agent already assigned and active"
);
return true;
}
// Assigned but not active (crashed or completed) -- allow re-dispatch
info!(
agent = %agent_name,
issue = issue_number,
"agent assigned but not active, allowing re-dispatch"
);
}
}
Err(e) => {
// Fail open: if we can't check assignees, allow dispatch
warn!(
agent = %agent_name,
issue = issue_number,
error = %e,
"failed to fetch assignees, allowing dispatch (fail-open)"
);
}
}
// Assign the issue to the agent
if let Err(e) = tracker.assign_issue(issue_number, &[agent_name]).await {
warn!(
agent = %agent_name,
issue = issue_number,
error = %e,
"failed to assign issue to agent"
);
} else {
info!(
agent = %agent_name,
issue = issue_number,
"assigned issue to agent"
);
}
false
}
/// Resolve mention chain metadata from the comment author.
///
/// If the comment was posted by a known agent, this is a nested mention:
/// inherit the chain_id from the agent's current run and increment depth.
/// If posted by a human, start a fresh chain with depth 0.
fn resolve_mention_chain(
&self,
comment_author: &str,
agent_names: &[String],
_max_depth: u32,
) -> (String, u32, String) {
if agent_names.iter().any(|n| n == comment_author) {
if let Some(active) = self.active_agents.get(comment_author) {
let parent_chain_id = active
.mention_chain_id
.clone()
.unwrap_or_else(|| ulid::Ulid::new().to_string());
let parent_depth = active.mention_depth.unwrap_or(0).saturating_add(1);
(parent_chain_id, parent_depth, comment_author.to_string())
} else {
let chain_id = ulid::Ulid::new().to_string();
(chain_id, 1, comment_author.to_string())
}
} else {
let chain_id = ulid::Ulid::new().to_string();
(chain_id, 0, String::new())
}
}
/// Sanitise finding text for use in issue title.
/// Strips JSON syntax characters that break title parsing.
fn sanitise_for_title(input: &str) -> String {
let mut result = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'{' | '}' | '[' | ']' | '"' => result.push(' '),
'\n' | '\r' => result.push(' '),
_ => result.push(ch),
}
}
let trimmed = result.split_whitespace().collect::<Vec<_>>().join(" ");
if trimmed.len() > 80 {
trimmed[..77].to_string() + "..."
} else {
trimmed
}
}
/// Sanitise finding text for use in issue body (markdown).
/// Escapes markdown special characters that could break rendering.
fn sanitise_for_body(input: &str) -> String {
let mut result = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'`' => result.push_str("``"),
'*' | '_' | '[' | ']' => result.push('\\'),
_ => result.push(ch),
}
}
result
}
/// File a Gitea issue for a compound review finding.
///
/// Deduplicates by searching for existing open issues with similar titles
/// before creating a new one.
async fn file_finding_issue(
&self,
poster: &OutputPoster,
result: &CompoundReviewResult,
finding: &ReviewFinding,
) -> Result<(), String> {
use terraphim_types::FindingSeverity;
let sev_str = match finding.severity {
FindingSeverity::Critical => "CRITICAL",
FindingSeverity::High => "HIGH",
FindingSeverity::Medium => "MEDIUM",
FindingSeverity::Low => "LOW",
FindingSeverity::Info => "INFO",
};
// Build a short keyword from the finding for dedup search
let dedup_keyword = if finding.finding.len() > 40 {
&finding.finding[..40]
} else {
&finding.finding
};
// Dedup: check if an open issue with similar title already exists
match poster.tracker().search_issues_by_title(dedup_keyword).await {
Ok(existing) if !existing.is_empty() => {
info!(
severity = %sev_str,
existing_issues = existing.len(),
keyword = %dedup_keyword,
"skipping finding issue (already filed)"
);
return Ok(());
}
Err(e) => {
// Dedup search failed — proceed with filing (fail-open)
warn!(error = %e, "dedup search failed, proceeding to file issue");
}
_ => {}
}
let title = format!(
"[Compound Review] {}: {}",
sev_str,
Self::sanitise_for_title(&finding.finding)
);
let mut body = "## Automated Finding from Compound Review\n\n".to_string();
body.push_str(&format!("- **Severity**: {}\n", sev_str));
if !finding.file.is_empty() {
body.push_str(&format!(
"- **File**: {}{}\n",
finding.file,
if finding.line > 0 {
format!(":{}", finding.line)
} else {
String::new()
}
));
}
body.push_str(&format!(
"- **Confidence**: {:.0}%\n",
finding.confidence * 100.0
));
body.push_str(&format!("- **Review ID**: {}\n\n", result.correlation_id));
body.push_str(&format!(
"### Finding\n\n{}\n\n",
Self::sanitise_for_body(&finding.finding)
));
if let Some(ref suggestion) = finding.suggestion {
if !suggestion.is_empty() {
body.push_str(&format!(
"### Suggested Fix\n\n{}\n",
Self::sanitise_for_body(suggestion)
));
}
}
// Skip labels for now - Gitea API has issues with label format
// TODO: Fix labels format for Gitea API
match poster.tracker().create_issue(&title, &body, &[]).await {
Ok(issue) => {
info!(
issue_number = issue.number,
severity = %sev_str,
title = %title,
"filed finding issue"
);
// Trigger implementation-swarm via mention comment so
// mention polling dispatches the agent automatically.
let trigger = format!(
"@adf:implementation-swarm please implement this finding for issue #{}",
issue.number
);
if let Err(e) = poster.tracker().post_comment(issue.number, &trigger).await {
warn!(
issue_number = issue.number,
error = %e,
"failed to post implementation trigger comment"
);
}
Ok(())
}
Err(e) => Err(format!("failed to create issue '{}': {}", title, e)),
}
}
/// Spawn a remediation agent for a CRITICAL finding.
///
/// Looks up the finding's category in `compound_review.remediation_agents`
/// to determine which agent to spawn. If no mapping exists, logs and skips.
async fn spawn_remediation_agent(&mut self, finding: &ReviewFinding) -> Result<(), String> {
let category_key = format!("{:?}", finding.category).to_lowercase();
let agent_name = self
.config
.compound_review
.remediation_agents
.get(&category_key)
.cloned();
let agent_name = match agent_name {
Some(name) => name,
None => {
debug!(
category = %category_key,
"no remediation agent mapped for category, skipping"
);
return Ok(());
}
};
// Build a targeted fix prompt
let mut prompt = "Fix this CRITICAL finding from compound review:\n\n".to_string();
if !finding.file.is_empty() {
prompt.push_str(&format!(
"File: {}{}\n",
finding.file,
if finding.line > 0 {
format!(":{}", finding.line)
} else {
String::new()
}
));
}
prompt.push_str(&format!(
"Severity: CRITICAL\nFinding: {}\n",
finding.finding
));
if let Some(ref suggestion) = finding.suggestion {
if !suggestion.is_empty() {
prompt.push_str(&format!("Suggested approach: {}\n", suggestion));
}
}
prompt.push_str(
"\nInstructions:\n\
1. Read the relevant file(s)\n\
2. Implement the fix\n\
3. Run cargo build && cargo test to verify\n\
4. Commit your changes\n",
);
// Look up the agent definition
let agent_def = self
.config
.agents
.iter()
.find(|a| a.name == agent_name)
.cloned();
let agent_def = match agent_def {
Some(def) => def,
None => {
warn!(
agent = %agent_name,
"remediation agent not found in fleet config, skipping"
);
return Ok(());
}
};
// Spawn using the existing agent infrastructure
// Build a modified agent def with our custom task prompt
let mut fix_def = agent_def;
fix_def.task = prompt;
fix_def.pre_check = None; // Skip pre-check for remediation
let spawned = self.spawn_agent(&fix_def).await;
match spawned {
Ok(_) => {
info!(
agent = %agent_name,
file = %finding.file,
"spawned remediation agent for CRITICAL finding"
);
Ok(())
}
Err(e) => Err(format!(
"failed to spawn remediation agent '{}': {}",
agent_name, e
)),
}
}
/// Create a git worktree for an agent to work in isolation.
///
/// `repo_dir` is the git repository root where `git worktree add` runs.
/// For project-bound agents this is the project's working_dir; otherwise
/// it is the orchestrator's top-level working_dir.
///
/// Returns the worktree path if successful, None if worktree creation fails
/// (fail-open: agent uses shared working_dir instead).
async fn create_agent_worktree(&self, agent_name: &str, repo_dir: &Path) -> Option<PathBuf> {
let worktree_root = PathBuf::from("/tmp/adf-worktrees");
if let Err(e) = tokio::fs::create_dir_all(&worktree_root).await {
warn!(agent = %agent_name, error = %e, "failed to create worktree root");
return None;
}
let id = uuid::Uuid::new_v4().to_string()[..8].to_string();
let worktree_path = worktree_root.join(format!("{agent_name}-{id}"));
let output = tokio::process::Command::new("git")
.args([
"worktree",
"add",
"--detach",
&worktree_path.to_string_lossy(),
"HEAD",
])
.current_dir(repo_dir)
.output()
.await;
match output {
Ok(o) if o.status.success() => {
info!(
agent = %agent_name,
path = %worktree_path.display(),
repo = %repo_dir.display(),
"created isolated git worktree"
);
Some(worktree_path)
}
Ok(o) => {
let stderr = String::from_utf8_lossy(&o.stderr);
warn!(
agent = %agent_name,
error = %stderr.chars().take(200).collect::<String>(),
"git worktree add failed, using shared working_dir"
);
None
}
Err(e) => {
warn!(agent = %agent_name, error = %e, "git worktree command failed");
None
}
}
}
/// Remove a git worktree after an agent finishes.
async fn remove_agent_worktree(&self, agent_name: &str, worktree_path: &Path, repo_dir: &Path) {
// Force-remove even if there are uncommitted changes (they were already
// committed by try_commit_agent_work or are intentionally discarded).
let output = tokio::process::Command::new("git")
.args([
"worktree",
"remove",
"--force",
&worktree_path.to_string_lossy(),
])
.current_dir(repo_dir)
.output()
.await;
match output {
Ok(o) if o.status.success() => {
info!(
agent = %agent_name,
path = %worktree_path.display(),
"removed agent worktree"
);
}
Ok(o) => {
let stderr = String::from_utf8_lossy(&o.stderr);
warn!(
agent = %agent_name,
path = %worktree_path.display(),
error = %stderr.chars().take(200).collect::<String>(),
"git worktree remove failed"
);
}
Err(e) => {
warn!(agent = %agent_name, error = %e, "git worktree remove command failed");
}
}
}
/// Attempt to commit any uncommitted working tree changes made by an agent.
///
/// This runs `git add -A && git diff --cached --quiet` to check if there
/// are changes, then commits with a standard message. Failures are logged
/// but not propagated — agent work is best-effort.
async fn try_commit_agent_work(&self, agent_name: &str, working_dir: &Path) {
// Stage all changes
let add = tokio::process::Command::new("git")
.args(["add", "-A"])
.current_dir(working_dir)
.output()
.await;
if let Err(e) = add {
tracing::debug!(agent = %agent_name, error = %e, "git add failed, skipping commit");
return;
}
// Check if there are staged changes
let diff_check = tokio::process::Command::new("git")
.args(["diff", "--cached", "--quiet"])
.current_dir(working_dir)
.status()
.await;
match diff_check {
Ok(status) if status.success() => {
// No changes to commit
return;
}
Ok(_) => { /* changes exist */ }
Err(e) => {
tracing::debug!(agent = %agent_name, error = %e, "git diff failed, skipping commit");
return;
}
}
// Get current branch for commit message
let branch = tokio::process::Command::new("git")
.args(["branch", "--show-current"])
.current_dir(working_dir)
.output()
.await;
let branch_name = match branch {
Ok(output) => String::from_utf8_lossy(&output.stdout).trim().to_string(),
Err(_) => "unknown".to_string(),
};
let msg = format!("feat({agent_name}): agent work [auto-commit]");
let commit = tokio::process::Command::new("git")
.args(["commit", "-m", &msg])
.current_dir(working_dir)
.output()
.await;
match commit {
Ok(output) if output.status.success() => {
tracing::info!(
agent = %agent_name,
branch = %branch_name,
"auto-committed agent working tree changes"
);
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::debug!(
agent = %agent_name,
stderr = %stderr,
"git commit failed"
);
}
Err(e) => {
tracing::warn!(agent = %agent_name, error = %e, "failed to run git commit");
}
}
}
/// Periodic reconciliation: detect exits, check cron, evaluate drift, drain output.
async fn reconcile_tick(&mut self) {
let tick_start = Instant::now();
self.provider_rate_limits.clean_expired();
self.retry_counts
.retain(|_, (_, ts)| ts.elapsed() < Duration::from_secs(3600));
// Check wall-clock timeouts and respawn with fallback
self.poll_wall_timeouts().await;
// 1. Poll all active agents for exit and handle exits per layer
self.poll_agent_exits().await;
// 2. Restart pending Safety agents (cooldown-aware)
self.restart_pending_safety_agents().await;
// 3. Check cron schedules for Core agents
self.check_cron_schedules().await;
// 4. Drain output events to nightwatch and collect telemetry
let telemetry_events = self.drain_output_events();
if !telemetry_events.is_empty() {
self.record_telemetry(telemetry_events).await;
}
// 5. Evaluate nightwatch drift (only during active hours)
let nw_cfg = &self.config.nightwatch;
let current_hour = chrono::Local::now().hour() as u8;
let in_window = if nw_cfg.active_start_hour <= nw_cfg.active_end_hour {
current_hour >= nw_cfg.active_start_hour && current_hour < nw_cfg.active_end_hour
} else {
// Wraps past midnight, e.g. start=22 end=6
current_hour >= nw_cfg.active_start_hour || current_hour < nw_cfg.active_end_hour
};
if in_window {
self.nightwatch.evaluate();
}
// 6. Sweep expired handoff buffer entries
let swept = self.handoff_buffer.sweep_expired();
if swept > 0 {
info!(swept_count = swept, "swept expired handoff buffer entries");
}
// 7. Check monthly budget reset
self.cost_tracker.monthly_reset_if_due();
// 8. Enforce budget limits (pause exhausted agents)
self.enforce_budgets().await;
// 9. Poll active flows (non-blocking)
let completed_flows: Vec<String> = self
.active_flows
.iter()
.filter(|(_, handle)| handle.is_finished())
.map(|(name, _)| name.clone())
.collect();
for name in completed_flows {
if let Some(handle) = self.active_flows.remove(&name) {
match handle.await {
Ok(state) => {
tracing::info!(flow = %name, status = ?state.status, "flow completed");
if let Some(ref dir) = self.config.flow_state_dir {
let _ = state.save_to_file(dir);
}
// Feed cost data from step envelopes into nightwatch for drift detection
for envelope in &state.step_envelopes {
if let (Some(cost), Some(input), Some(output)) = (
envelope.cost_usd,
envelope.input_tokens,
envelope.output_tokens,
) {
self.nightwatch.observe_cost(
&format!("flow-{}", name),
cost,
input,
output,
None, // Flows don't have individual budgets yet
);
}
}
}
Err(e) => {
tracing::error!(flow = %name, error = %e, "flow task panicked");
}
}
}
}
// 10. Check flow schedules
self.check_flow_schedules().await;
// 11. Poll for @adf: mentions in watched issues
self.poll_mentions().await;
// 12. D-4: Hot-reload KG routing rules if markdown files changed
if let Some(ref mut router) = self.kg_router {
router.reload_if_changed();
}
// 13. D-2: Re-probe providers if cached results are stale
if self.provider_health.is_stale() {
if let Some(ref kg_router) = self.kg_router {
self.provider_health.probe_all(kg_router).await;
if let Some(ref dir) = self
.config
.routing
.as_ref()
.and_then(|r| r.probe_results_dir.clone())
{
let _ = self.provider_health.save_results(dir.as_path()).await;
}
// Send probe results to Quickwit for cost-aware routing
if let Some(ref sink) = self.quickwit_sink {
let project_id = self
.config
.projects
.first()
.map(|p| p.id.clone())
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string());
self.provider_health
.send_to_quickwit(sink, &project_id)
.await;
}
}
}
// 14. Update last_tick_time and increment tick counter
self.last_tick_time = chrono::Utc::now();
self.tick_count = self.tick_count.wrapping_add(1);
// 15. Periodic telemetry persistence (every 60 ticks = ~5 min at 5s interval)
if self.tick_count % 60 == 0 {
self.persist_telemetry();
}
// 16. Flush provider-budget snapshot. The tracker accumulates in
// memory via record_telemetry; persist here so hour/day counters
// carry across restarts (cf. with_persistence at construction).
// Skip when no tracker was configured.
if let Some(tracker) = self.provider_budget_tracker.as_ref() {
if let Err(e) = tracker.persist() {
warn!(error = %e, "failed to persist provider budget snapshot");
}
}
// Archive stale learnings periodically
if self.tick_count % self.learning_config.consolidation_ticks == 0 {
if let Some(ref store) = self.learning_store {
match tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(store.archive_stale(self.learning_config.archive_days))
}) {
Ok(archived) if archived > 0 => {
info!(archived, "archived stale learnings");
}
Err(e) => {
warn!(error = %e, "failed to archive stale learnings");
}
Ok(_) => {}
}
}
// Evolution memory consolidation (promotes high-importance short-term to long-term).
if self.evolution_manager.is_enabled() {
let consolidated = self.evolution_manager.consolidate_all();
if consolidated > 0 {
info!(consolidated, "evolution memory consolidation complete");
}
}
}
// 17. Drain the unified dispatch queue. Handlers for ReviewPr,
// AutoMerge, and PostMergeTestGate are stubs; wiring happens in
// Steps D, G, and H respectively.
while let Some(task) = self.dispatcher.dequeue() {
match task {
DispatchTask::TimeDriven { name, project, .. } => {
tracing::debug!(name, project, "TimeDriven task drained from dispatcher");
}
DispatchTask::IssueDriven {
identifier,
project,
..
} => {
tracing::debug!(
identifier,
project,
"IssueDriven task drained from dispatcher"
);
}
DispatchTask::MentionDriven {
agent_name,
project,
..
} => {
tracing::debug!(
agent_name,
project,
"MentionDriven task drained from dispatcher"
);
}
task @ DispatchTask::ReviewPr { .. } => {
if let Err(e) = self.handle_review_pr(task).await {
warn!(error = %e, "handle_review_pr failed");
}
}
task @ DispatchTask::AutoMerge { .. } => {
if let Err(e) = self.handle_auto_merge(task).await {
warn!(error = %e, "handle_auto_merge failed");
}
}
task @ DispatchTask::PostMergeTestGate { .. } => {
if let Err(e) = self.handle_post_merge_test_gate(task).await {
tracing::error!(error = ?e, "handle_post_merge_test_gate failed");
}
}
task @ DispatchTask::Push { .. } => {
if let Err(e) = self.handle_push(task).await {
warn!(error = %e, "handle_push failed");
}
}
}
}
// 17.5. PR gate reconciliation: read actual commit statuses and
// branch protection, classify each open PR head, and take action
// (enqueue missing agents, open remediation issues, or clear for
// auto-merge). Runs every N ticks to avoid excessive API load.
if self.tick_count % self.config.gate_reconcile_interval_ticks as u64 == 0 {
if let Err(e) = self.reconcile_pr_gates().await {
warn!(error = %e, "reconcile_pr_gates failed");
}
}
// 18. ROC v1 Step F: poll open PRs for reviewer verdicts and enqueue
// AutoMerge for any PR that clears every gate. Runs AFTER the
// dispatch drain so the newly enqueued AutoMerge tasks are serviced
// on the NEXT tick (deterministic ordering).
if let Err(e) = self.poll_pending_reviews().await {
warn!(error = %e, "poll_pending_reviews failed");
}
info!(
tick = self.tick_count,
elapsed_ms = tick_start.elapsed().as_millis() as u64,
"reconcile_tick complete"
);
}
/// PR gate reconciliation: for every project with Gitea config, read
/// actual commit statuses and branch protection rules, classify each
/// open PR head via [`pr_gate::reconcile_pr_gate`], and take action.
///
/// Actions:
/// - `ReadyForPolicy`: no action (Step 18 will handle it).
/// - `EnqueueMissingChecks`: log which agents need dispatching.
/// - `AwaitingChecks`: log and skip (rechecked next interval).
/// - `BlockedByFailedChecks`: open deduplicated remediation issue.
/// - `FactoryFault`: open deduplicated remediation issue with error.
///
/// Remediation issues are deduplicated using [`pr_gate::remediation_key`]
/// by searching for existing open issues containing the key.
async fn reconcile_pr_gates(&mut self) -> Result<(), OrchestratorError> {
let targets: Vec<(String, config::GiteaOutputConfig)> = if self.config.projects.is_empty() {
match self.config.gitea.clone() {
Some(g) => vec![(dispatcher::LEGACY_PROJECT_ID.to_string(), g)],
None => return Ok(()),
}
} else {
self.config
.projects
.iter()
.filter_map(|p| p.gitea.clone().map(|g| (p.id.clone(), g)))
.collect()
};
if targets.is_empty() {
return Ok(());
}
for (project_id, gitea_cfg) in &targets {
if let Err(e) = self
.reconcile_pr_gates_for_project(project_id, gitea_cfg)
.await
{
warn!(
project = %project_id,
error = %e,
"reconcile_pr_gates_for_project failed"
);
}
}
Ok(())
}
/// Inner per-project PR gate reconciliation.
async fn reconcile_pr_gates_for_project(
&mut self,
project_id: &str,
gitea_cfg: &config::GiteaOutputConfig,
) -> Result<(), OrchestratorError> {
let tracker_cfg = terraphim_tracker::GiteaConfig {
base_url: gitea_cfg.base_url.clone(),
token: gitea_cfg.token.clone(),
owner: gitea_cfg.owner.clone(),
repo: gitea_cfg.repo.clone(),
active_states: vec!["open".to_string()],
terminal_states: vec!["closed".to_string()],
use_robot_api: false,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
let tracker = match terraphim_tracker::GiteaTracker::new(tracker_cfg) {
Ok(t) => t,
Err(e) => {
warn!(project = %project_id, error = %e, "failed to create GiteaTracker for PR gate reconciliation");
return Ok(());
}
};
let protection = match tracker
.get_branch_protection(&gitea_cfg.owner, &gitea_cfg.repo, "main")
.await
{
Ok(p) => p,
Err(e) => {
warn!(
project = %project_id,
error = %e,
"failed to get branch protection; skipping PR gate reconciliation"
);
return Ok(());
}
};
if !protection.enable_status_check || protection.status_check_contexts.is_empty() {
tracing::debug!(
project = %project_id,
"branch protection has no required status checks; skipping"
);
return Ok(());
}
let required_contexts = protection.status_check_contexts.clone();
let prs = match tracker.list_open_prs().await {
Ok(prs) => prs,
Err(e) => {
warn!(project = %project_id, error = %e, "failed to list open PRs for gate reconciliation");
return Ok(());
}
};
for pr in prs {
if pr.head_sha.is_empty() {
continue;
}
let statuses = match tracker
.list_commit_statuses(&gitea_cfg.owner, &gitea_cfg.repo, &pr.head_sha)
.await
{
Ok(s) => s,
Err(e) => {
warn!(
project = %project_id,
pr = pr.number,
sha = %pr.head_sha,
error = %e,
"failed to list commit statuses"
);
continue;
}
};
let head_statuses: Vec<pr_gate::CommitStatusSummary> = statuses
.into_iter()
.map(|s| pr_gate::CommitStatusSummary {
context: s.context,
state: pr_gate::CommitStatusState::from_api_str(&s.state),
created_at_unix: s.created_at.and_then(|ts| ts.parse::<i64>().ok()),
})
.collect();
let snapshot = pr_gate::PrGateSnapshot {
pr_number: pr.number,
head_sha: pr.head_sha.clone(),
base_branch: pr.base_ref.clone(),
required_contexts: required_contexts.clone(),
head_statuses,
now_unix: chrono::Utc::now().timestamp(),
};
let decision = pr_gate::reconcile_pr_gate(&snapshot);
match &decision {
pr_gate::PrGateDecision::ReadyForPolicy => {
tracing::debug!(
project = %project_id,
pr = pr.number,
"PR gate: all required contexts green"
);
}
pr_gate::PrGateDecision::EnqueueMissingChecks { missing } => {
tracing::info!(
project = %project_id,
pr = pr.number,
missing = ?missing,
"PR gate: missing required contexts"
);
}
pr_gate::PrGateDecision::AwaitingChecks { pending } => {
tracing::debug!(
project = %project_id,
pr = pr.number,
pending = ?pending,
"PR gate: awaiting pending checks"
);
}
pr_gate::PrGateDecision::BlockedByFailedChecks { failed } => {
let key =
pr_gate::remediation_key(project_id, pr.number, &pr.head_sha, &decision);
tracing::warn!(
project = %project_id,
pr = pr.number,
failed = ?failed,
key = %key,
"PR gate: blocked by failed checks"
);
if let Err(e) = self
.open_remediation_issue_if_needed(
&tracker,
project_id,
pr.number,
&pr.head_sha,
&key,
&format!(
"PR #{} blocked by failed required contexts: {}",
pr.number,
failed
.iter()
.map(|(ctx, state)| format!("{ctx}={state}"))
.collect::<Vec<_>>()
.join(", ")
),
)
.await
{
warn!(error = %e, "failed to open remediation issue");
}
}
pr_gate::PrGateDecision::FactoryFault { error } => {
let key =
pr_gate::remediation_key(project_id, pr.number, &pr.head_sha, &decision);
tracing::error!(
project = %project_id,
pr = pr.number,
error = %error,
key = %key,
"PR gate: factory fault"
);
if let Err(e) = self
.open_remediation_issue_if_needed(
&tracker,
project_id,
pr.number,
&pr.head_sha,
&key,
&format!("PR #{} factory fault: {error}", pr.number),
)
.await
{
warn!(error = %e, "failed to open remediation issue");
}
}
}
}
Ok(())
}
/// Open a deduplicated remediation issue. Searches for existing open issues
/// containing the remediation key before creating a new one.
async fn open_remediation_issue_if_needed(
&self,
tracker: &terraphim_tracker::GiteaTracker,
project_id: &str,
pr_number: u64,
head_sha: &str,
dedup_key: &str,
body: &str,
) -> Result<(), OrchestratorError> {
let existing = tracker.search_issues_by_title(dedup_key).await;
match existing {
Ok(ids) if !ids.is_empty() => {
tracing::debug!(
project = %project_id,
key = %dedup_key,
existing_count = ids.len(),
"remediation issue already exists; skipping"
);
return Ok(());
}
Err(e) => {
tracing::warn!(
project = %project_id,
error = %e,
"failed to search for existing remediation issues; creating anyway"
);
}
Ok(_) => {}
}
let title = format!("[ADF] PR gate remediation: {dedup_key}");
let full_body = format!(
"{body}\n\n\
Project: `{project_id}`\n\
PR: #{pr_number}\n\
Head SHA: `{head_sha}`\n\
Dedup key: `{dedup_key}`\n\n\
This issue was auto-created by the PR gate reconciler.\
It will be auto-closed when the gate clears."
);
let labels = ["adf", "pr-gate", "status/needs-triage"];
tracker
.create_issue(&title, &full_body, &labels)
.await
.map_err(|e| {
OrchestratorError::Config(format!("failed to create remediation issue: {e}"))
})?;
tracing::info!(
project = %project_id,
pr = pr_number,
key = %dedup_key,
"opened PR gate remediation issue"
);
Ok(())
}
/// Check all agent budgets and pause any that have exceeded their limits.
async fn enforce_budgets(&mut self) {
let actionable = self.cost_tracker.check_all();
for (agent_name, verdict) in actionable {
match verdict {
BudgetVerdict::NearExhaustion {
spent_cents,
budget_cents,
} => {
warn!(
agent = %agent_name,
spent_usd = spent_cents as f64 / 100.0,
budget_usd = budget_cents as f64 / 100.0,
pct = (spent_cents * 100 / budget_cents),
"budget warning: agent approaching monthly limit"
);
}
BudgetVerdict::Exhausted {
spent_cents,
budget_cents,
} => {
error!(
agent = %agent_name,
spent_usd = spent_cents as f64 / 100.0,
budget_usd = budget_cents as f64 / 100.0,
"budget exhausted: pausing agent"
);
self.stop_agent(&agent_name).await;
}
_ => {}
}
}
}
/// Kill agents that have exceeded their wall-clock timeout and respawn with fallback.
async fn poll_wall_timeouts(&mut self) {
let mut timed_out: Vec<String> = Vec::new();
for (name, managed) in &self.active_agents {
if let Some(max_secs) = managed.definition.max_cpu_seconds {
let elapsed = managed.started_at.elapsed();
if elapsed > Duration::from_secs(max_secs) {
warn!(
agent = %name,
elapsed_secs = elapsed.as_secs(),
max_wall_secs = max_secs,
"agent exceeded wall-clock timeout, killing for fallback respawn"
);
timed_out.push(name.clone());
}
}
}
for name in timed_out {
if let Some(managed) = self.active_agents.remove(&name) {
let def = managed.definition.clone();
// Kill the process
if let Err(e) = managed.handle.kill().await {
error!(agent = %name, error = %e, "failed to kill timed-out agent");
}
// Try respawn with fallback if configured
if def.fallback_provider.is_some() {
info!(
agent = %name,
fallback_model = ?def.fallback_model,
"respawning timed-out agent with fallback provider"
);
let mut fallback_def = def.clone();
// Swap provider to fallback (fallback_provider is a CLI tool path)
if let Some(ref fb_provider) = def.fallback_provider {
fallback_def.cli_tool = fb_provider.clone();
}
if let Some(ref fb_model) = def.fallback_model {
fallback_def.model = Some(fb_model.clone());
}
// Clear provider field so model composition uses the new cli_tool
fallback_def.provider = None;
// Clear fallback to prevent infinite loops
fallback_def.fallback_provider = None;
fallback_def.fallback_model = None;
// Honour the chosen cli_tool/model verbatim: skip KG re-routing
// which would otherwise re-pick the primary provider that just
// timed out.
fallback_def.bypass_kg_routing = true;
if let Err(e) = self.spawn_agent(&fallback_def).await {
error!(agent = %name, error = %e, "failed to respawn with fallback");
}
} else {
info!(agent = %name, "no fallback configured, agent timed out permanently");
}
}
}
}
/// Poll all active agents for exit and handle exits per layer.
async fn poll_agent_exits(&mut self) {
// Collect exited agents first to avoid borrow conflict
let mut exited: Vec<(String, AgentDefinition, std::process::ExitStatus)> = Vec::new();
// Collect agents that exceeded their wall-clock timeout
let mut timed_out: Vec<String> = Vec::new();
for (name, managed) in &mut self.active_agents {
match managed.handle.try_wait() {
Ok(Some(status)) => {
exited.push((name.clone(), managed.definition.clone(), status));
}
Ok(None) => {
// Still running -- check wall-clock timeout
if let Some(max_secs) = managed.definition.max_cpu_seconds {
let elapsed = managed.started_at.elapsed();
if elapsed > Duration::from_secs(max_secs) {
warn!(
agent = %name,
elapsed_secs = elapsed.as_secs(),
max_secs = max_secs,
"agent exceeded wall-clock timeout, killing"
);
timed_out.push(name.clone());
}
}
}
Err(e) => {
warn!(agent = %name, error = %e, "try_wait failed");
}
}
}
// Kill timed-out agents
for name in timed_out {
if let Some(mut managed) = self.active_agents.remove(&name) {
let grace = Duration::from_secs(managed.definition.grace_period_secs.unwrap_or(5));
match managed.handle.shutdown(grace).await {
Ok(graceful) => {
info!(
agent = %name,
graceful = graceful,
"timed-out agent terminated"
);
}
Err(e) => {
warn!(agent = %name, error = %e, "failed to kill timed-out agent");
}
}
// Handle exit based on layer (similar to handle_agent_exit but for timeout)
if managed.definition.layer == AgentLayer::Safety {
let key = agent_key(&managed.definition);
let restart_count = self.increment_restart_count(&key);
self.restart_cooldowns.insert(key, Instant::now());
info!(
agent = %name,
restart_count,
"safety agent timed out, will restart after cooldown"
);
} else {
info!(agent = %name, layer = ?managed.definition.layer, "agent timed out");
}
}
}
// Drain output from exiting agents BEFORE removing them
let mut quota_exits: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut exit_telemetry: Vec<(String, control_plane::telemetry::CompletionEvent)> =
Vec::new();
for (name, def, status) in &exited {
let mut stdout_lines: Vec<String> = Vec::new();
let mut stderr_lines: Vec<String> = Vec::new();
let mut output_lines: Vec<String> = Vec::new();
let mut agent_tmp_path: Option<PathBuf> = None;
if let Some(managed) = self.active_agents.get_mut(name) {
let cli_tool = managed.definition.cli_tool.clone();
let session_id = managed.session_id.clone();
let model = managed
.routed_model
.clone()
.or_else(|| managed.definition.model.clone())
.unwrap_or_default();
agent_tmp_path = managed.output_tmp_path.take();
while let Ok(event) = managed.output_rx.try_recv() {
self.nightwatch.observe(name, &event);
match &event {
crate::OutputEvent::Stdout { line, .. } => {
stdout_lines.push(line.clone());
output_lines.push(line.clone());
if let Some(ce) = Self::parse_stdout_for_telemetry(
&cli_tool,
line,
&session_id,
&model,
) {
exit_telemetry.push((name.clone(), ce));
}
}
crate::OutputEvent::Stderr { line, .. } => {
stderr_lines.push(line.clone());
output_lines.push(format!("[stderr] {}", line));
if let Some(ce) =
Self::parse_stderr_for_telemetry(line, &session_id, &model)
{
exit_telemetry.push((name.clone(), ce));
}
}
_ => {}
}
}
}
// Classify the exit using KG-boosted pattern matching
let classification =
self.exit_classifier
.classify(status.code(), &stdout_lines, &stderr_lines);
let wall_time_secs = self
.active_agents
.get(name)
.map(|m| m.started_at.elapsed().as_secs_f64())
.unwrap_or(0.0);
let routed_model = self
.active_agents
.get(name)
.and_then(|m| m.routed_model.clone());
let (mention_chain_id, mention_depth, mention_parent_agent) = self
.active_agents
.get(name)
.map(|m| {
(
m.mention_chain_id.clone(),
m.mention_depth,
m.mention_parent_agent.clone(),
)
})
.unwrap_or((None, None, None));
let trigger = if self
.active_agents
.get(name)
.is_some_and(|m| m.spawned_by_mention)
{
RunTrigger::Mention
} else {
RunTrigger::Cron
};
let record = AgentRunRecord {
run_id: uuid::Uuid::new_v4(),
agent_name: name.clone(),
started_at: chrono::Utc::now()
- chrono::Duration::milliseconds((wall_time_secs * 1000.0) as i64),
ended_at: chrono::Utc::now(),
exit_code: status.code(),
exit_class: classification.exit_class,
model_used: routed_model.clone().or_else(|| def.model.clone()),
was_fallback: false,
wall_time_secs,
output_summary: AgentRunRecord::summarise_output(&stdout_lines),
error_summary: AgentRunRecord::summarise_errors(&stderr_lines),
trigger,
matched_patterns: classification.matched_patterns.clone(),
confidence: classification.confidence,
mention_chain_id,
mention_depth,
mention_parent_agent,
consecutive_config_errors: 0,
};
// Config-error circuit-breaker: quarantine after 3 consecutive failures.
let record = if record.exit_class == ExitClass::ConfigError {
let count = self
.config_error_counters
.entry(name.clone())
.and_modify(|c| *c += 1)
.or_insert(1);
let new_count = *count;
if new_count >= 3 && !self.quarantined_agents.contains(name.as_str()) {
self.quarantined_agents.insert(name.clone());
warn!(
target: "adf.agent.quarantined",
agent = %name,
consecutive_config_errors = new_count,
"agent quarantined after consecutive ConfigError exits"
);
if std::env::var("ADF_QUARANTINE_PERSIST").as_deref() == Ok("1") {
// TODO: persist enabled=false to conf.d TOML (issue #1817).
}
}
AgentRunRecord {
consecutive_config_errors: new_count,
..record
}
} else {
self.config_error_counters.remove(name.as_str());
record
};
if record.exit_class == ExitClass::RateLimit {
quota_exits.insert(name.clone());
}
info!(
agent = %name,
exit_code = ?status.code(),
exit_class = %record.exit_class,
confidence = record.confidence,
matched_patterns = ?record.matched_patterns,
wall_time_secs = record.wall_time_secs,
"agent exit classified"
);
// Record learning outcome for injected lessons
if let Some(ref store) = self.learning_store {
if let Some(ids) = self.injected_learning_ids.get(name) {
for id in ids {
let result = match record.exit_class {
ExitClass::Success | ExitClass::EmptySuccess => {
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(store.record_effective(id, name))
})
}
ExitClass::Timeout
| ExitClass::RateLimit
| ExitClass::ModelError
| ExitClass::CompilationError
| ExitClass::TestFailure
| ExitClass::NetworkError
| ExitClass::ResourceExhaustion
| ExitClass::Crash => tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(store.record_applied(id, name))
}),
_ => continue,
};
if let Err(e) = result {
debug!(agent = %name, learning_id = %id, error = %e, "failed to record learning outcome");
}
}
}
self.injected_learning_ids.remove(name);
}
let mut quota_provider_recorded: Option<String> = None;
if record.exit_class == ExitClass::RateLimit {
let stderr_text = stderr_lines.join("\n");
let output_text = output_lines.join("\n");
let _secondary_confirms =
control_plane::output_parser::parse_stderr_for_limit_errors(&stderr_text)
.is_some()
|| control_plane::telemetry::is_subscription_limit_error(&output_text);
// Attribution: prefer routed model -> canonical key, fallback to config provider
let effective_provider = routed_model
.as_deref()
.map(provider_budget::canonical_key_for_model_or_provider)
.or_else(|| {
def.provider
.as_deref()
.map(provider_budget::canonical_quota_key)
});
if let Some(provider_key) = effective_provider {
warn!(
agent = %name,
provider = %provider_key,
model = ?routed_model,
"quota exit detected; recording provider failure and blocking"
);
self.provider_health.record_failure(provider_key);
if let Some(tracker) = self.provider_budget_tracker.as_ref() {
tracker.force_exhaust(provider_key);
}
let quota_line = stderr_lines
.iter()
.chain(stdout_lines.iter())
.find(|l| l.to_lowercase().contains("resets "))
.map(|s| s.as_str())
.unwrap_or("");
if let Some(reset_time) = parse_reset_time(quota_line) {
info!(
provider = %provider_key,
"blocking provider until rate-limit window expires"
);
self.provider_rate_limits
.block_until(provider_key, reset_time);
} else {
// Safety floor: classifier says RateLimit but no parseable
// reset window in stderr. Apply a conservative block so the
// next cron firing skips this provider while we iterate on
// the parser. The warn-log carries a representative stderr
// tail so future format drift is discoverable.
let stderr_sample: String = stderr_lines
.iter()
.rev()
.take(3)
.rev()
.cloned()
.collect::<Vec<_>>()
.join(" | ");
warn!(
provider = %provider_key,
block_secs = DEFAULT_RATE_LIMIT_BLOCK.as_secs(),
stderr_tail = %stderr_sample,
"rate-limit detected but reset window unparseable; applying conservative safety-floor block"
);
self.provider_rate_limits
.block_until(provider_key, Instant::now() + DEFAULT_RATE_LIMIT_BLOCK);
}
quota_provider_recorded = Some(provider_key.to_string());
}
}
// D-3: Feed exit classification into provider health circuit breaker
if let Some(ref provider) = def.provider {
let canonical = provider_budget::canonical_quota_key(provider);
let already_recorded_by_quota =
quota_provider_recorded.as_deref() == Some(canonical);
match record.exit_class {
ExitClass::ModelError | ExitClass::RateLimit =>
{
#[allow(clippy::collapsible_match)]
if !already_recorded_by_quota {
self.provider_health.record_failure(canonical);
}
}
ExitClass::Success | ExitClass::EmptySuccess => {
self.provider_health.record_success(canonical);
}
_ => {} // Other exit classes don't affect provider health
}
// issue #7: per-provider stderr-signature classification. This
// runs on top of the KG-driven ExitClass match above so that
// providers whose CLI exits 0 on quota hits ("returning partial
// output") still trip the breaker and force budget exhaustion
// when their stderr matches a configured throttle pattern.
let sigs = self.provider_error_signatures.get(provider);
let sig_kind = error_signatures::classify_lines(&stderr_lines, sigs);
match sig_kind {
error_signatures::ErrorKind::Throttle => {
warn!(
agent = %name,
provider = %canonical,
model = ?record.model_used,
"stderr classified as throttle; tripping breaker + exhausting budget"
);
self.provider_health.record_failure(canonical);
if let Some(tracker) = self.provider_budget_tracker.as_ref() {
tracker.force_exhaust(canonical);
}
}
error_signatures::ErrorKind::Flake => {
info!(
agent = %name,
provider = %provider,
"stderr classified as flake; routing will retry next pool entry"
);
}
error_signatures::ErrorKind::Unknown => {
// Only escalate when there *is* stderr text to classify
// AND the run itself looks like a real failure. A clean
// exit with empty stderr must never page fleet-meta.
let looked_like_failure = !matches!(
record.exit_class,
ExitClass::Success | ExitClass::EmptySuccess
);
if looked_like_failure && !stderr_lines.is_empty() {
// Soft-failure accounting so a pathological provider
// that spews unclassified errors still eventually
// opens the breaker.
self.provider_health.record_failure(provider);
self.escalate_unknown_error(
provider,
record.model_used.as_deref(),
&stderr_lines,
)
.await;
}
}
}
}
// Post output to Gitea if configured, routed by the agent's
// owning project so multi-project fleets land comments in the
// correct owner/repo.
if let (Some(poster), Some(issue)) = (&self.output_poster, def.gitea_issue) {
if def.event_only {
// Defence-in-depth: the dispatch gate at handle_webhook_dispatch
// should have prevented an event-only agent from acquiring a
// gitea_issue. If we reach here the gate has a hole; treat as a
// should-never-happen alert and skip the post.
error!(
agent = %name,
issue = issue,
"skipping output post: agent is event-only but gitea_issue is set; this indicates a missed dispatch gate"
);
} else {
let exit_code = status.code();
let project = def
.project
.clone()
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string());
if let Err(e) = poster
.post_agent_output_for_project(
&project,
name,
issue,
&output_lines,
exit_code,
)
.await
{
warn!(
agent = %name,
project = %project,
issue = issue,
error = %e,
"failed to post output to Gitea"
);
}
}
}
// Finalise the agent output log: prepend header to the temp file
// written by the background drain task, then rename to final path.
{
let _ = std::fs::create_dir_all(&self.agent_log_dir);
let ts = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
let filename = format!("{}-{}.log", name, ts);
let final_path = self.agent_log_dir.join(&filename);
if let Some(ref tmp_path) = agent_tmp_path {
// The drain task wrote raw output lines. Read them back,
// prepend the header, and write the final file.
let body = std::fs::read_to_string(tmp_path).unwrap_or_default();
let header = format!(
"# agent: {}\n# exit_code: {:?}\n# exit_class: {}\n# wall_time: {:.1}s\n# model: {}\n\n",
name,
status.code(),
record.exit_class,
record.wall_time_secs,
record.model_used.as_deref().unwrap_or("n/a"),
);
let final_content = format!("{}{}", header, body);
if let Err(e) = std::fs::write(&final_path, &final_content) {
warn!(agent = %name, path = %final_path.display(), error = %e, "failed to write agent output log");
} else {
debug!(agent = %name, path = %final_path.display(), "wrote agent output log");
}
let _ = std::fs::remove_file(tmp_path);
} else {
// Fallback: no drain task (shouldn't happen), write from
// the in-memory output_lines instead.
let mut content = String::with_capacity(output_lines.len() * 120);
content.push_str(&format!(
"# agent: {}\n# exit_code: {:?}\n# exit_class: {}\n# wall_time: {:.1}s\n# model: {}\n\n",
name,
status.code(),
record.exit_class,
record.wall_time_secs,
record.model_used.as_deref().unwrap_or("n/a"),
));
for line in &output_lines {
content.push_str(line);
content.push('\n');
}
if let Err(e) = std::fs::write(&final_path, &content) {
warn!(agent = %name, path = %final_path.display(), error = %e, "failed to write agent output log (fallback)");
}
}
}
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let exit_code = status.code();
let level = if exit_code.unwrap_or(1) == 0 {
"INFO"
} else {
"WARN"
};
let doc = quickwit::LogDocument {
timestamp: chrono::Utc::now().to_rfc3339(),
project_id: def
.project
.clone()
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string()),
level: level.into(),
agent_name: name.clone(),
layer: format!("{:?}", def.layer),
source: "orchestrator".into(),
message: format!("agent exited: {}", record.exit_class),
model: routed_model.clone().or_else(|| def.model.clone()),
exit_code,
wall_time_secs: Some(record.wall_time_secs),
extra: Some(serde_json::json!({
"exit_class": record.exit_class.to_string(),
"confidence": record.confidence,
"matched_patterns": record.matched_patterns,
})),
..Default::default()
};
let _ = sink.send(doc).await;
}
}
// Record telemetry from exiting agent output
if !exit_telemetry.is_empty() {
self.record_telemetry(exit_telemetry).await;
}
// Process natural exits
// NOW remove from active_agents and handle exits.
// Capture worktree_path before removing so we can commit + clean up.
for (name, def, status) in exited {
let (worktree_path, commit_status_post) = {
let agent = self.active_agents.get(&name);
(
agent.and_then(|m| m.worktree_path.clone()),
agent.and_then(|m| m.commit_status_post.clone()),
)
};
// Post terminal commit status if this agent was dispatched with one.
if let Some((ref head_sha, ref context)) = commit_status_post {
let exit_success = status.success();
let state = if exit_success {
terraphim_tracker::StatusState::Success
} else {
terraphim_tracker::StatusState::Failure
};
let description = if exit_success {
format!("{} passed", def.name)
} else {
format!("{} failed (exit {})", def.name, status.code().unwrap_or(-1))
};
self.post_terminal_commit_status(head_sha, context, state, &description)
.await;
}
// Disarm worktree guard on success so it doesn't conflict with
// the explicit cleanup below.
if status.success() {
if let Some(agent) = self.active_agents.get_mut(&name) {
if let Some(guard) = agent.worktree_guard.take() {
guard.keep();
}
}
}
self.active_agents.remove(&name);
if quota_exits.contains(&name) {
let mut local_unhealthy = self.provider_health.unhealthy_providers();
local_unhealthy.extend(self.provider_rate_limits.blocked_providers());
let respawned = if let Some(ref kg_router) = self.kg_router {
if let Some(decision) = kg_router.route_agent(&def.task) {
if let Some(healthy_route) = decision.first_healthy_route(&local_unhealthy)
{
let retry_count = self
.retry_counts
.entry(name.clone())
.or_insert((0, Instant::now()));
if retry_count.0 < 3 {
retry_count.0 += 1;
retry_count.1 = Instant::now();
let retry_name = format!("{}-retry-{}", name, retry_count.0);
let mut fallback_def = def.clone();
fallback_def.name = retry_name;
fallback_def.model = Some(healthy_route.model.clone());
fallback_def.provider = Some(healthy_route.provider.clone());
// Extract CLI tool from the action template so the retry uses
// the correct CLI for the fallback provider (e.g. opencode for kimi).
if let Some(ref action) = healthy_route.action {
if let Some(cli) = action.split_whitespace().next() {
fallback_def.cli_tool = cli.to_string();
}
}
fallback_def.fallback_provider = None;
fallback_def.fallback_model = None;
// KG router already filtered for healthy routes;
// re-running KG selection inside spawn_agent could
// drift if breaker state has changed (e.g. a probe
// succeeded). Lock the chosen route in.
fallback_def.bypass_kg_routing = true;
info!(
agent = %name,
retry_name = %fallback_def.name,
fallback_model = %healthy_route.model,
fallback_provider = %healthy_route.provider,
"respawning quota-exited agent via KG fallback route"
);
if let Err(e) = self.spawn_agent(&fallback_def).await {
error!(agent = %fallback_def.name, error = %e, "failed to spawn KG fallback agent");
}
true
} else {
warn!(agent = %name, retries = retry_count.0, "max retries reached, agent exits permanently");
self.retry_counts.remove(&name);
false
}
} else {
info!(agent = %name, "no healthy KG route available, agent exits permanently");
false
}
} else {
false
}
} else {
false
};
if !respawned {
// KG routing failed or no healthy route - try configured fallback before giving up
if def.fallback_provider.is_some() {
info!(
agent = %name,
fallback_provider = ?def.fallback_provider,
fallback_model = ?def.fallback_model,
"KG routing failed, respawning with configured fallback provider"
);
let mut fallback_def = def.clone();
if let Some(ref fb_provider) = def.fallback_provider {
fallback_def.cli_tool = fb_provider.clone();
}
if let Some(ref fb_model) = def.fallback_model {
fallback_def.model = Some(fb_model.clone());
}
fallback_def.provider = None;
fallback_def.fallback_provider = None;
fallback_def.fallback_model = None;
// The whole point of this branch is to escape KG routing
// (it just told us "no healthy route"). Honour the
// operator-chosen cli_tool/model verbatim instead of
// letting spawn_agent re-evaluate KG and re-pick the
// primary that drove us here.
fallback_def.bypass_kg_routing = true;
if let Err(e) = self.spawn_agent(&fallback_def).await {
error!(agent = %name, error = %e, "failed to respawn with fallback");
self.handle_agent_exit(&name, &def, status);
}
} else {
self.handle_agent_exit(&name, &def, status);
}
}
} else {
self.handle_agent_exit(&name, &def, status);
}
self.record_project_meta_exit(&def, status).await;
// Evolution: record lesson and snapshot on agent exit.
if def.evolution_enabled && self.evolution_manager.is_enabled() {
#[cfg(feature = "evolution")]
{
let exit_desc = format!("Agent {} exited with status: {}", name, status);
let exit_code = status.code().unwrap_or(-1);
let category = if status.success() {
terraphim_agent_evolution::LessonCategory::SuccessPattern
} else {
terraphim_agent_evolution::LessonCategory::Failure
};
let _ = self.evolution_manager.record_lesson(
&name,
&format!("{} run completed", name),
&exit_desc,
&format!("Exit code: {}", exit_code),
category,
);
}
if let Some(snapshot_key) = self.evolution_manager.snapshot_on_exit(&name) {
info!(agent = %name, key = %snapshot_key, "evolution snapshot created");
}
}
// Auto-commit in the agent's working directory (worktree or shared)
let project_repo: &Path = def
.project
.as_deref()
.and_then(|pid| self.config.project_by_id(pid))
.map(|p| p.working_dir.as_path())
.unwrap_or(&self.config.working_dir);
let commit_dir = worktree_path.as_deref().unwrap_or(project_repo);
if status.success() {
self.try_commit_agent_work(&name, commit_dir).await;
}
// Clean up the worktree after committing
if let Some(ref wt) = worktree_path {
self.remove_agent_worktree(&name, wt, project_repo).await;
}
}
}
/// Feed a `project-meta` exit into the per-project circuit breaker. On
/// the trip transition (Nth consecutive failure) this touches the pause
/// flag and opens an `[ADF]` escalation issue on the configured
/// fleet-escalation repository.
async fn record_project_meta_exit(
&mut self,
def: &AgentDefinition,
status: std::process::ExitStatus,
) {
if !project_control::is_project_meta_agent(def) {
return;
}
let Some(project_id) = def.project.clone() else {
return;
};
let success = status.success();
let verdict = self
.project_failure_counter
.record_project_meta_result(&project_id, success);
let count = self.project_failure_counter.count(&project_id);
let threshold = self.project_failure_counter.threshold();
info!(
project = %project_id,
agent = %def.name,
success,
consecutive_failures = count,
threshold,
"project-meta exit recorded"
);
if verdict != project_control::ShouldPause::Yes {
return;
}
self.trip_project_circuit_breaker(&project_id, &def.name, count, threshold)
.await;
}
/// Touch the pause flag and open an `[ADF]` escalation issue for a
/// project that has exceeded the `project-meta` failure threshold.
async fn trip_project_circuit_breaker(
&self,
project_id: &str,
agent_name: &str,
consecutive_failures: u32,
threshold: u32,
) {
match project_control::touch_pause_flag(&self.pause_dir, project_id) {
Ok(path) => {
warn!(
project = %project_id,
pause_flag = %path.display(),
consecutive_failures,
threshold,
"project circuit breaker tripped; pause flag created"
);
}
Err(e) => {
error!(
project = %project_id,
pause_dir = %self.pause_dir.display(),
error = %e,
"failed to create project pause flag"
);
}
}
let (Some(owner), Some(repo)) = self.fleet_escalation_target() else {
warn!(
project = %project_id,
"no fleet-escalation owner/repo configured; skipping issue creation"
);
return;
};
let Some(gitea_cfg) = self.config.gitea.as_ref() else {
warn!(
project = %project_id,
"no top-level gitea config; cannot open escalation issue"
);
return;
};
let tracker_cfg = terraphim_tracker::GiteaConfig {
base_url: gitea_cfg.base_url.clone(),
token: gitea_cfg.token.clone(),
owner: owner.clone(),
repo: repo.clone(),
active_states: vec!["open".to_string()],
terminal_states: vec!["closed".to_string()],
use_robot_api: false,
robot_path: std::path::PathBuf::from("/home/alex/go/bin/gitea-robot"),
claim_strategy: terraphim_tracker::gitea::ClaimStrategy::PreferRobot,
};
let tracker = match terraphim_tracker::GiteaTracker::new(tracker_cfg) {
Ok(t) => t,
Err(e) => {
error!(
project = %project_id,
owner = %owner,
repo = %repo,
error = %e,
"failed to construct escalation GiteaTracker"
);
return;
}
};
let title = format!(
"[ADF] project-meta on {project_id} failed {consecutive_failures} consecutively"
);
let body = format!(
"Project `{project_id}` has been paused by the circuit breaker after \
{consecutive_failures} consecutive `project-meta` failures (threshold: {threshold}).\n\n\
Agent: `{agent_name}`\n\n\
Pause flag: `{pause}`\n\n\
Remove the pause flag once the underlying failure is resolved:\n\n\
```\nrm {pause}\n```\n",
pause = self.pause_dir.join(project_id).display()
);
let labels = ["adf", "circuit-breaker", "priority/high"];
match tracker.create_issue(&title, &body, &labels).await {
Ok(issue) => info!(
project = %project_id,
owner = %owner,
repo = %repo,
issue = issue.number,
"opened [ADF] escalation issue"
),
Err(e) => error!(
project = %project_id,
owner = %owner,
repo = %repo,
error = %e,
"failed to open [ADF] escalation issue"
),
}
}
/// Resolve the `(owner, repo)` pair for fleet-level escalation issues.
/// Falls back to the configured Gitea output target when the dedicated
/// `fleet_escalation_*` fields are unset.
fn fleet_escalation_target(&self) -> (Option<String>, Option<String>) {
let owner = self
.config
.fleet_escalation_owner
.clone()
.or_else(|| self.config.gitea.as_ref().map(|g| g.owner.clone()));
let repo = self
.config
.fleet_escalation_repo
.clone()
.or_else(|| self.config.gitea.as_ref().map(|g| g.repo.clone()));
(owner, repo)
}
/// Handle an agent exit based on its layer.
fn handle_agent_exit(
&mut self,
name: &str,
def: &AgentDefinition,
status: std::process::ExitStatus,
) {
let key = agent_key(def);
match def.layer {
AgentLayer::Safety => {
// Only count non-zero exits toward restart limit.
// A successful exit (code 0) means the agent completed its task;
// punishing it for succeeding makes no sense.
if !status.success() {
let restart_count = self.increment_restart_count(&key);
self.restart_cooldowns.insert(key, Instant::now());
if restart_count <= self.config.max_restart_count {
info!(
agent = %name,
exit_status = %status,
restart_count,
cooldown_secs = self.config.restart_cooldown_secs,
window_secs = self.config.restart_budget_window_secs,
"safety agent failed, will restart after cooldown"
);
} else {
error!(
agent = %name,
exit_status = %status,
restart_count,
max = self.config.max_restart_count,
"safety agent exceeded max restarts, permanently stopped"
);
}
} else {
self.restart_cooldowns.insert(key, Instant::now());
info!(
agent = %name,
exit_status = %status,
cooldown_secs = self.config.restart_cooldown_secs,
"safety agent completed successfully, will restart after cooldown"
);
}
}
AgentLayer::Core => {
info!(agent = %name, exit_status = %status, "core agent completed");
}
AgentLayer::Growth => {
info!(agent = %name, exit_status = %status, "growth agent completed");
}
}
}
/// Restart Safety agents that have exited and passed their cooldown.
async fn restart_pending_safety_agents(&mut self) {
let cooldown = Duration::from_secs(self.config.restart_cooldown_secs);
let max_restarts = self.config.max_restart_count;
// Age out stale restart counters before restart eligibility checks.
let safety_keys: Vec<(String, String)> = self
.config
.agents
.iter()
.filter(|def| def.layer == AgentLayer::Safety)
.map(agent_key)
.collect();
for key in &safety_keys {
let _ = self.current_restart_count(key);
}
// Find Safety agents that need restarting
let to_restart: Vec<AgentDefinition> = self
.config
.agents
.iter()
.filter(|def| {
// Must be Safety layer
if def.layer != AgentLayer::Safety {
return false;
}
// Must not be currently active
if self.active_agents.contains_key(&def.name) {
return false;
}
let key = agent_key(def);
// Must have a restart cooldown entry (meaning it exited)
let last_exit = match self.restart_cooldowns.get(&key) {
Some(t) => t,
None => return false,
};
// Must have passed the cooldown
if last_exit.elapsed() < cooldown {
return false;
}
// Must be under max restart count
let count = self.restart_counts.get(&key).copied().unwrap_or(0);
count <= max_restarts
})
.cloned()
.collect();
for def in to_restart {
let key = agent_key(&def);
info!(
agent = %def.name,
restart_count = self.restart_counts.get(&key).copied().unwrap_or(0),
"restarting safety agent after cooldown"
);
if let Err(e) = self.spawn_agent(&def).await {
error!(agent = %def.name, error = %e, "failed to restart safety agent");
}
}
}
/// Check cron schedules and spawn due Core agents.
async fn check_cron_schedules(&mut self) {
let now = chrono::Utc::now();
let scheduled = self.scheduler.scheduled_agents();
// Collect agents that should fire
let to_spawn: Vec<(AgentDefinition, chrono::DateTime<chrono::Utc>)> = scheduled
.into_iter()
.filter(|(def, _schedule)| {
// Skip quarantined agents
!self.quarantined_agents.contains(&def.name)
})
.filter(|(def, _schedule)| {
// Skip if already active
!self.active_agents.contains_key(&def.name)
})
.filter_map(|(def, schedule)| {
// Get the next fire time after last_tick_time
let next_fire = schedule.after(&self.last_tick_time).next()?;
// Check if fire time is within window
if next_fire > now {
return None;
}
// Skip if agent already fired at this schedule occurrence
if let Some(last_fire) = self.last_cron_fire.get(&def.name) {
if next_fire <= *last_fire {
return None;
}
}
Some((def.clone(), next_fire))
})
.collect();
for (def, fire_time) in to_spawn {
info!(agent = %def.name, fire_time = %fire_time, "cron schedule fired");
// Record fire time before spawning to prevent rapid re-trigger
self.last_cron_fire.insert(def.name.clone(), fire_time);
if let Err(e) = self.spawn_agent(&def).await {
error!(agent = %def.name, error = %e, "cron spawn failed");
}
}
// Also check compound review schedule
if let Some(compound_sched) = self.scheduler.compound_review_schedule() {
debug!(
last_tick = %self.last_tick_time,
last_fired = ?self.last_compound_review_fired_at,
now = %now,
"checking compound review schedule"
);
// Compute the earliest occurrence strictly after
// `last_tick_time` that is also <= now. This is the same
// occurrence the buggy code would have refired forever when
// the reconcile-tick future was cancelled mid-await by the
// 90 s `tokio::time::timeout` safety wrapper (#1562).
let next_fire = compound_sched
.after(&self.last_tick_time)
.take_while(|t| *t <= now)
.next();
debug!(next_fire = ?next_fire, "compound schedule next fire");
if let Some(fire_time) = next_fire {
// Gate against re-firing the same occurrence. The
// cursor `last_compound_review_fired_at` is the per-
// occurrence dedup key, mirroring `last_cron_fire` for
// per-agent crons. It is updated *before* the `.await`
// below so a cancelled future cannot lose the update.
let already_fired = self
.last_compound_review_fired_at
.map(|prev| fire_time <= prev)
.unwrap_or(false);
if !already_fired {
// Record fire time BEFORE awaiting
// `handle_schedule_event` so that future
// cancellation cannot lose the update and
// re-trigger the same occurrence on the next tick.
self.last_compound_review_fired_at = Some(fire_time);
info!(
fire_time = %fire_time,
"compound review schedule fired, starting review"
);
self.handle_schedule_event(ScheduleEvent::CompoundReview)
.await;
}
}
}
}
/// Drain broadcast output events from all active agents into nightwatch.
/// Also parses CLI output for telemetry completion events.
fn drain_output_events(&mut self) -> Vec<(String, control_plane::telemetry::CompletionEvent)> {
let mut events: Vec<(String, OutputEvent)> = Vec::new();
for (name, managed) in &mut self.active_agents {
loop {
match managed.output_rx.try_recv() {
Ok(event) => events.push((name.clone(), event)),
Err(broadcast::error::TryRecvError::Empty) => break,
Err(broadcast::error::TryRecvError::Lagged(n)) => {
warn!(agent = %name, skipped = n, "output events lagged");
break;
}
Err(broadcast::error::TryRecvError::Closed) => break,
}
}
}
let mut completion_events: Vec<(String, control_plane::telemetry::CompletionEvent)> =
Vec::new();
for (name, event) in &events {
self.nightwatch.observe(name, event);
// Feed output to evolution system if enabled.
if self.evolution_manager.is_enabled() {
let is_evo = self
.active_agents
.get(name)
.map(|m| m.definition.evolution_enabled)
.unwrap_or(false);
if is_evo {
let (line_content, event_type) = match event {
crate::OutputEvent::Stdout { line, .. } => (line.clone(), "stdout"),
crate::OutputEvent::Stderr { line, .. } => (line.clone(), "stderr"),
_ => continue,
};
let _ = self
.evolution_manager
.record_output(evolution::EvolutionOutput {
agent_id: name.clone(),
content: line_content,
event_type: event_type.to_string(),
importance: "medium".to_string(),
});
}
}
match event {
OutputEvent::Stdout { line, .. } => {
let (cli_tool, session_id, model) = self
.active_agents
.get(name)
.map(|m| {
(
m.definition.cli_tool.clone(),
m.session_id.clone(),
m.routed_model
.clone()
.or_else(|| m.definition.model.clone())
.unwrap_or_default(),
)
})
.unwrap_or_default();
if let Some(ce) =
Self::parse_stdout_for_telemetry(&cli_tool, line, &session_id, &model)
{
completion_events.push((name.clone(), ce));
}
}
OutputEvent::Stderr { line, .. } => {
let (session_id, model) = self
.active_agents
.get(name)
.map(|m| {
(
m.session_id.clone(),
m.routed_model
.clone()
.or_else(|| m.definition.model.clone())
.unwrap_or_default(),
)
})
.unwrap_or_default();
if let Some(ce) = Self::parse_stderr_for_telemetry(line, &session_id, &model) {
completion_events.push((name.clone(), ce));
}
}
_ => {}
}
#[cfg(feature = "quickwit")]
if let Some(ref sink) = self.quickwit_sink {
let (level, source, line) = match event {
crate::OutputEvent::Stdout { line, .. } => ("INFO", "stdout", line.as_str()),
crate::OutputEvent::Stderr { line, .. } => ("WARN", "stderr", line.as_str()),
_ => continue,
};
let layer = self
.active_agents
.get(name)
.map(|m| format!("{:?}", m.definition.layer))
.unwrap_or_default();
let project_id = self
.active_agents
.get(name)
.and_then(|m| m.definition.project.clone())
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string());
let model = self.active_agents.get(name).and_then(|m| {
m.routed_model
.clone()
.or_else(|| m.definition.model.clone())
});
let doc = quickwit::LogDocument {
timestamp: chrono::Utc::now().to_rfc3339(),
project_id,
level: level.into(),
agent_name: name.clone(),
layer,
source: source.into(),
message: line.to_owned(),
model,
..Default::default()
};
let _ = sink.try_send(doc);
}
}
completion_events
}
/// Record parsed telemetry events into the telemetry store, per-agent
/// cost tracker, and (when configured) the provider-level hour/day
/// budget tracker.
///
/// Cost accounting is performed per-agent before the batch write so that
/// agent-level spend is still tracked individually. The telemetry store
/// write uses a single lock acquisition via `record_batch`. Provider
/// budget spend is folded in during the same iteration so Layer 3 of
/// the subscription gate actually sees real dispatch cost.
async fn record_telemetry(
&self,
events: Vec<(String, control_plane::telemetry::CompletionEvent)>,
) {
for (agent_name, event) in &events {
if event.cost_usd > 0.0 {
self.cost_tracker.record_cost(agent_name, event.cost_usd);
if let Some(tracker) = self.provider_budget_tracker.as_ref() {
if let Some(provider_key) =
provider_budget::provider_key_for_model(&event.model)
{
let verdict = tracker.record_cost(provider_key, event.cost_usd);
if matches!(
verdict,
cost_tracker::BudgetVerdict::Exhausted { .. }
| cost_tracker::BudgetVerdict::NearExhaustion { .. }
) {
warn!(
provider = provider_key,
agent = agent_name.as_str(),
cost_usd = event.cost_usd,
verdict = ?verdict,
"provider budget pressure recorded"
);
}
}
}
}
// Send to Quickwit for cost-aware routing analytics
if let Some(ref sink) = self.quickwit_sink {
let doc = quickwit::LogDocument {
timestamp: event.completed_at.to_rfc3339(),
project_id: self
.config
.projects
.first()
.map(|p| p.id.clone())
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string()),
level: if event.success {
"INFO".to_string()
} else {
"WARN".to_string()
},
agent_name: agent_name.clone(),
layer: "Core".to_string(),
source: "telemetry".to_string(),
message: event
.error
.clone()
.unwrap_or_else(|| "completion recorded".to_string()),
model: Some(event.model.clone()),
cost_usd: Some(event.cost_usd),
latency_ms: Some(event.latency_ms),
tokens_input: Some(event.tokens.input),
tokens_output: Some(event.tokens.output),
exit_class: if event.success {
Some("success".to_string())
} else {
Some("error".to_string())
},
is_free: event.cost_usd == 0.0,
..Default::default()
};
if let Err(e) = sink.send(doc).await {
warn!(error = %e, "failed to send telemetry to Quickwit");
}
}
}
// Write all events in one lock acquisition.
let completion_events: Vec<control_plane::telemetry::CompletionEvent> =
events.into_iter().map(|(_, e)| e).collect();
self.telemetry_store.record_batch(completion_events).await;
}
/// Attempt to restore persisted telemetry summary from durable storage.
///
/// Best-effort: if no summary exists or loading fails, logs and continues
/// with an empty telemetry store. Called once at the start of `run()`.
async fn restore_telemetry(&self) {
use terraphim_persistence::Persistable;
let mut summary = control_plane::TelemetrySummary::new("telemetry_summary".to_string());
match summary.load().await {
Ok(loaded) => {
self.telemetry_store.import_summary(loaded).await;
info!("restored persisted telemetry summary");
}
Err(_) => {
info!("no persisted telemetry summary found, starting fresh");
}
}
}
/// Persist telemetry summary to durable storage via fire-and-forget spawn.
///
/// Clones the Arc-backed store and moves both export and save into the
/// spawned task so the reconcile loop is not blocked by the read lock.
fn persist_telemetry(&self) {
let store = self.telemetry_store.clone();
tokio::spawn(async move {
use terraphim_persistence::Persistable;
let summary = store.export_summary().await;
if let Err(e) = summary.save().await {
tracing::warn!(error = %e, "failed to persist telemetry summary");
}
});
}
/// Parse a stdout line from a CLI tool into a CompletionEvent, if the line
/// represents a completed agent session.
///
/// Returns `None` for lines that do not carry completion telemetry (tool
/// calls, status updates, ignored formats, or unrecognised cli_tool).
fn parse_stdout_for_telemetry(
cli_tool: &str,
line: &str,
session_id: &str,
model: &str,
) -> Option<control_plane::telemetry::CompletionEvent> {
let parsed = match cli_tool {
"opencode" => {
control_plane::output_parser::parse_opencode_line(line, session_id, model, None)
}
"claude" => control_plane::output_parser::parse_claude_line(line, session_id, model),
_ => control_plane::output_parser::ParsedOutput::Ignored,
};
match parsed {
control_plane::output_parser::ParsedOutput::Completion(ce) => Some(ce),
_ => None,
}
}
/// Parse a stderr line into a CompletionEvent representing a subscription
/// limit error.
///
/// Returns `None` when the line does not match any known limit-error
/// pattern.
fn parse_stderr_for_telemetry(
line: &str,
session_id: &str,
model: &str,
) -> Option<control_plane::telemetry::CompletionEvent> {
control_plane::output_parser::parse_stderr_for_limit_errors(line)?;
Some(control_plane::telemetry::CompletionEvent {
model: model.to_string(),
session_id: session_id.to_string(),
completed_at: chrono::Utc::now(),
latency_ms: 0,
success: false,
tokens: control_plane::telemetry::TokenBreakdown::default(),
cost_usd: 0.0,
error: Some(line.to_string()),
})
}
/// Check flow schedules and trigger due flows.
async fn check_flow_schedules(&mut self) {
let now = chrono::Utc::now();
let mut to_trigger: Vec<flow::config::FlowDefinition> = Vec::new();
for flow_def in &self.config.flows {
let Some(ref schedule_str) = flow_def.schedule else {
continue;
};
let Ok(schedule) = cron::Schedule::from_str(schedule_str) else {
continue;
};
// Overlap prevention: skip if this flow is already active
if self.active_flows.contains_key(&flow_def.name) {
tracing::info!(
flow = %flow_def.name,
"skipping cron trigger: flow already active"
);
continue;
}
let should_fire: bool = schedule
.after(&self.last_tick_time)
.take_while(|t| *t <= now)
.next()
.is_some();
if should_fire {
to_trigger.push(flow_def.clone());
}
}
for flow_def in to_trigger {
self.handle_schedule_event(ScheduleEvent::Flow(Box::new(flow_def)))
.await;
}
}
/// Handle a schedule event from the TimeScheduler.
async fn handle_schedule_event(&mut self, event: ScheduleEvent) {
match event {
ScheduleEvent::Spawn(def) => {
info!(agent = %def.name, "scheduled spawn");
if let Err(e) = self.spawn_agent(&def).await {
error!(agent = %def.name, error = %e, "scheduled spawn failed");
}
}
ScheduleEvent::Stop { agent_name } => {
info!(agent = %agent_name, "scheduled stop");
self.stop_agent(&agent_name).await;
}
ScheduleEvent::CompoundReview => {
info!("scheduled compound review starting");
// For scheduled reviews, use HEAD against base_branch from config
let git_ref = "HEAD";
let base_ref = &self.config.compound_review.base_branch;
match self.compound_workflow.run(git_ref, base_ref).await {
Ok(result) => {
info!(
findings = result.findings.len(),
pass = %result.pass,
duration = ?result.duration,
"compound review completed"
);
// 1. Post structured summary to Gitea
if let (Some(ref poster), Some(issue)) =
(&self.output_poster, self.config.compound_review.gitea_issue)
{
let report = result.format_report();
if let Err(e) = poster.post_raw(issue, &report).await {
warn!(error = %e, "failed to post compound review summary");
}
// 2. Auto-file issues for CRITICAL/HIGH findings
if self.config.compound_review.auto_file_issues {
let actionable = result.actionable_findings();
for finding in actionable {
if let Err(e) =
self.file_finding_issue(poster, &result, finding).await
{
warn!(error = %e, "failed to file finding issue");
}
}
}
// 3. Trigger remediation agents for CRITICAL findings
if self.config.compound_review.auto_remediate {
let critical: Vec<_> = result
.findings
.iter()
.filter(|f| f.severity == FindingSeverity::Critical)
.collect();
for finding in critical {
if let Err(e) = self.spawn_remediation_agent(finding).await {
warn!(error = %e, "failed to spawn remediation agent");
}
}
}
}
}
Err(e) => {
error!(error = %e, "compound review failed");
}
}
}
ScheduleEvent::Flow(flow_def) => {
let flow_name = flow_def.name.clone();
let flow_state_dir = self
.config
.flow_state_dir
.clone()
.unwrap_or_else(|| PathBuf::from("/tmp/flow-states"));
let working_dir = self.config.compound_review.repo_path.clone();
let project_runtimes = build_flow_project_runtimes(&self.config);
let flow_def = *flow_def;
let flow_name_for_closure = flow_name.clone();
// FlowExecutor contains non-Send types (Regex via AgentSpawner),
// so we use spawn_blocking + Handle::block_on as a Send-safe bridge.
let rt_handle = tokio::runtime::Handle::current();
let handle = tokio::task::spawn_blocking(move || {
let executor = flow::executor::FlowExecutor::new(working_dir, flow_state_dir)
.with_projects(project_runtimes);
rt_handle.block_on(async {
executor.run(&flow_def, None).await
.unwrap_or_else(|e| {
tracing::error!(flow = %flow_name_for_closure, error = %e, "flow execution failed");
flow::state::FlowRunState::failed(&flow_name_for_closure, &e.to_string())
})
})
});
self.active_flows.insert(flow_name.clone(), handle);
tracing::info!(flow = %flow_name, "flow spawned as background task");
}
}
}
/// Handle a drift alert from the NightwatchMonitor.
async fn handle_drift_alert(&mut self, alert: DriftAlert) {
warn!(
agent = %alert.agent_name,
score = alert.drift_score.score,
level = ?alert.drift_score.level,
"drift alert"
);
match alert.recommended_action {
CorrectionAction::LogWarning(msg) => {
warn!(agent = %alert.agent_name, message = %msg, "drift warning");
}
CorrectionAction::RestartAgent => {
info!(agent = %alert.agent_name, "restarting agent due to drift");
self.stop_agent(&alert.agent_name).await;
self.nightwatch.reset(&alert.agent_name);
// Find definition and respawn
if let Some(def) = self
.config
.agents
.iter()
.find(|a| a.name == alert.agent_name)
.cloned()
{
if let Err(e) = self.spawn_agent(&def).await {
error!(
agent = %alert.agent_name,
error = %e,
"failed to restart agent after drift correction"
);
}
}
}
CorrectionAction::PauseAndEscalate(msg) => {
error!(
agent = %alert.agent_name,
message = %msg,
"CRITICAL: pausing agent and escalating to human"
);
self.stop_agent(&alert.agent_name).await;
self.nightwatch.reset(&alert.agent_name);
}
}
}
/// Stop a specific agent by name.
async fn stop_agent(&mut self, name: &str) {
if let Some(managed) = self.active_agents.remove(name) {
info!(agent = %name, "stopping agent");
let grace = Duration::from_secs(5);
let mut handle = managed.handle;
match handle.shutdown(grace).await {
Ok(_) => info!(agent = %name, "agent stopped gracefully"),
Err(e) => warn!(agent = %name, error = %e, "agent stop had issues"),
}
}
}
/// Shutdown all active agents.
async fn shutdown_all_agents(&mut self) {
let names: Vec<String> = self.active_agents.keys().cloned().collect();
for name in names {
self.stop_agent(&name).await;
}
}
/// Spawn a specific agent by name (test helper).
#[doc(hidden)]
pub async fn spawn_agent_for_test(&mut self, name: &str) -> Result<(), OrchestratorError> {
let def = self
.config
.agents
.iter()
.find(|a| a.name == name)
.ok_or_else(|| OrchestratorError::AgentNotFound(name.to_string()))?
.clone();
self.spawn_agent(&def).await
}
/// Check if an agent is in the active_agents map (test helper).
#[doc(hidden)]
pub fn is_agent_active(&self, name: &str) -> bool {
self.active_agents.contains_key(name)
}
/// Test helper: remove an agent from active_agents so it can be re-spawned.
#[doc(hidden)]
pub fn remove_agent_for_test(&mut self, name: &str) {
self.active_agents.remove(name);
}
/// Test helper: set last_run_commits for a given agent.
#[doc(hidden)]
pub fn set_last_run_commit(&mut self, agent_name: &str, commit: &str) {
self.last_run_commits
.insert(agent_name.to_string(), commit.to_string());
}
/// Test helper: set last_cron_fire for a given agent.
#[doc(hidden)]
pub fn set_last_cron_fire(
&mut self,
agent_name: &str,
fire_time: chrono::DateTime<chrono::Utc>,
) {
self.last_cron_fire
.insert(agent_name.to_string(), fire_time);
}
/// Test helper: set last_tick_time for synthetic time testing.
#[doc(hidden)]
pub fn set_last_tick_time(&mut self, time: chrono::DateTime<chrono::Utc>) {
self.last_tick_time = time;
}
/// Test helper: read the compound-review fire cursor.
#[doc(hidden)]
pub fn last_compound_review_fired_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
self.last_compound_review_fired_at
}
/// Test helper: clear the compound-review fire cursor for synthetic
/// testing of the cancellation property.
#[doc(hidden)]
pub fn clear_last_compound_review_fired_at(&mut self) {
self.last_compound_review_fired_at = None;
}
/// Test helper: access the telemetry store for assertions.
#[doc(hidden)]
pub fn telemetry_store(&self) -> &control_plane::TelemetryStore {
&self.telemetry_store
}
/// Test helper: access the provider budget tracker (if any).
#[doc(hidden)]
pub fn provider_budget_tracker(&self) -> Option<&Arc<provider_budget::ProviderBudgetTracker>> {
self.provider_budget_tracker.as_ref()
}
/// Test helper: inspect the unknown-error dedupe set (lock + clone).
#[doc(hidden)]
pub fn unknown_error_dedupe_snapshot(&self) -> std::collections::HashSet<String> {
self.unknown_error_dedupe
.lock()
.map(|g| g.clone())
.unwrap_or_default()
}
/// Open a `[ADF] unknown error signature on <provider>/<model>` Gitea
/// issue so fleet-meta can classify the pattern. Deduped by
/// [`error_signatures::unknown_dedupe_key`] within the process lifetime
/// so retries of the same stderr shape don't spam the tracker.
///
/// The target tracker is the orchestrator's default [`GiteaTracker`]
/// from [`OutputPoster::tracker`], which points at the fleet-meta repo
/// configured in `orchestrator.toml`. If no `OutputPoster` is wired
/// (tests, legacy configs), this is a no-op.
async fn escalate_unknown_error(
&self,
provider: &str,
model: Option<&str>,
stderr_lines: &[String],
) {
let joined = stderr_lines.join("\n");
let dedupe_key = error_signatures::unknown_dedupe_key(provider, &joined);
{
let mut set = match self.unknown_error_dedupe.lock() {
Ok(g) => g,
Err(_) => {
warn!(
provider = %provider,
"unknown_error_dedupe lock poisoned; skipping escalation"
);
return;
}
};
if !set.insert(dedupe_key.clone()) {
// Already escalated this shape in this process. Skip quietly.
return;
}
}
let Some(poster) = self.output_poster.as_ref() else {
info!(
provider = %provider,
dedupe_key = %dedupe_key,
"no output_poster configured; unknown stderr logged only"
);
return;
};
// Cap stderr in the body so a runaway CLI never posts megabytes.
const MAX_STDERR_CHARS: usize = 4000;
let truncated: String = if joined.len() > MAX_STDERR_CHARS {
format!(
"{}\n...[truncated, original {} chars]",
joined.chars().take(MAX_STDERR_CHARS).collect::<String>(),
joined.len()
)
} else {
joined
};
let model_slug = model.unwrap_or("<unknown-model>");
let title = format!(
"[ADF] unknown error signature on {}/{}",
provider, model_slug
);
let body = format!(
"A spawned agent produced stderr that matched neither the \
throttle nor the flake regex lists for provider `{}` \
(model `{}`). Please review and extend the provider's \
`error_signatures` config so future occurrences classify \
correctly.\n\n\
**Dedupe key:** `{}`\n\n\
## Captured stderr\n\n```\n{}\n```\n",
provider, model_slug, dedupe_key, truncated
);
let labels = ["adf", "error-signature", "triage"];
let tracker = poster.tracker();
if let Err(e) = tracker.create_issue(&title, &body, &labels).await {
warn!(
provider = %provider,
model = %model_slug,
error = %e,
"failed to escalate unknown-error signature to Gitea"
);
} else {
info!(
provider = %provider,
model = %model_slug,
dedupe_key = %dedupe_key,
"escalated unknown error signature to fleet-meta"
);
}
}
/// Test helper: drive `record_telemetry` from outside the crate so
/// integration tests can verify the cost-tracker / provider-budget
/// wiring without starting the full reconcile loop.
#[doc(hidden)]
pub async fn record_telemetry_for_test(
&self,
events: Vec<(String, control_plane::telemetry::CompletionEvent)>,
) {
self.record_telemetry(events).await
}
/// Test helper: return the pause directory the orchestrator is using.
#[doc(hidden)]
pub fn pause_dir_for_test(&self) -> &std::path::Path {
&self.pause_dir
}
/// Test helper: drive the project circuit breaker from outside the crate
/// so integration tests can verify the trip → pause-flag path without
/// spawning real agent processes.
///
/// Simulates recording `failure_count` consecutive `project-meta` failures
/// against `project_id`; on the Nth failure (where N == threshold) the
/// underlying counter trips and this function touches the pause flag.
/// Returns `true` iff the pause flag was (re)created by this call.
#[doc(hidden)]
pub async fn simulate_project_meta_failures_for_test(
&mut self,
project_id: &str,
failure_count: u32,
) -> bool {
let mut tripped = false;
for _ in 0..failure_count {
let verdict = self
.project_failure_counter
.record_project_meta_result(project_id, false);
if verdict == project_control::ShouldPause::Yes {
let _ = project_control::touch_pause_flag(&self.pause_dir, project_id);
tripped = true;
}
}
tripped
}
/// Test helper: record a successful project-meta run, resetting the
/// per-project consecutive-failure counter.
#[doc(hidden)]
pub fn reset_project_meta_counter_for_test(&mut self, project_id: &str) {
let _ = self
.project_failure_counter
.record_project_meta_result(project_id, true);
}
}
/// Check whether any changed file matches any of the watch path prefixes.
fn has_matching_changes(changed_files: &[String], watch_paths: &[String]) -> bool {
for file in changed_files {
for prefix in watch_paths {
if scope::is_path_prefix(prefix, file) {
return true;
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn legacy_key(name: &str) -> (String, String) {
(
crate::dispatcher::LEGACY_PROJECT_ID.to_string(),
name.to_string(),
)
}
fn test_config() -> OrchestratorConfig {
OrchestratorConfig {
working_dir: std::path::PathBuf::from("/tmp/test-orchestrator"),
nightwatch: NightwatchConfig::default(),
compound_review: CompoundReviewConfig {
cli_tool: None,
provider: None,
model: None,
schedule: "0 2 * * *".to_string(),
max_duration_secs: 60,
repo_path: std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."),
create_prs: false,
worktree_root: std::path::PathBuf::from("/tmp/test-orchestrator/.worktrees"),
base_branch: "main".to_string(),
max_concurrent_agents: 3,
..Default::default()
},
workflow: None,
agents: vec![
AgentDefinition {
name: "sentinel".to_string(),
layer: AgentLayer::Safety,
cli_tool: "echo".to_string(),
task: "safety watch".to_string(),
model: None,
schedule: None,
capabilities: vec!["security".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
},
AgentDefinition {
name: "sync".to_string(),
layer: AgentLayer::Core,
cli_tool: "echo".to_string(),
task: "sync upstream".to_string(),
model: None,
schedule: Some("0 3 * * *".to_string()),
capabilities: vec!["sync".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
},
],
restart_cooldown_secs: 60,
max_restart_count: 10,
restart_budget_window_secs: 43_200,
disk_usage_threshold: 100, // disable disk guard in tests
tick_interval_secs: 30,
gate_reconcile_interval_ticks: 20,
handoff_buffer_ttl_secs: None,
persona_data_dir: None,
skill_data_dir: None,
gitea_skill_repo: None,
flows: vec![],
flow_state_dir: None,
gitea: None,
mentions: None,
webhook: None,
role_config_path: None,
routing: None,
#[cfg(feature = "quickwit")]
quickwit: None,
projects: vec![],
include: vec![],
providers: vec![],
provider_budget_state_file: None,
pause_dir: None,
project_circuit_breaker_threshold: 3,
fleet_escalation_owner: None,
fleet_escalation_repo: None,
post_merge_gate: None,
learning: config::LearningConfig::default(),
evolution: config::EvolutionConfig::default(),
pr_dispatch: None,
pr_dispatch_per_project: Default::default(),
}
}
#[test]
fn test_orchestrator_creates_from_config() {
let config = test_config();
let orch = AgentOrchestrator::new(config);
assert!(orch.is_ok());
}
#[test]
fn test_orchestrator_initial_state() {
let config = test_config();
let orch = AgentOrchestrator::new(config).unwrap();
assert!(orch.active_agents.is_empty());
assert!(!orch.shutdown_requested);
let statuses = orch.agent_statuses();
assert!(statuses.is_empty());
}
#[test]
fn test_orchestrator_shutdown_flag() {
let config = test_config();
let mut orch = AgentOrchestrator::new(config).unwrap();
assert!(!orch.shutdown_requested);
orch.shutdown();
assert!(orch.shutdown_requested);
}
#[tokio::test]
async fn test_orchestrator_compound_review_manual() {
// Use empty groups to avoid git worktree operations during test.
// Worktree creation fails when git index is locked (e.g. pre-commit hooks).
let repo_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
// In shallow clones (e.g. CI with fetch-depth: 1) HEAD~1 does not exist.
// Fall back to diffing against the empty tree so the test works everywhere.
let base_ref = {
let check = std::process::Command::new("git")
.args([
"-C",
repo_path.to_str().unwrap(),
"rev-parse",
"--verify",
"HEAD~1",
])
.output();
match check {
Ok(o) if o.status.success() => "HEAD~1".to_string(),
_ => {
// 4b825dc: the well-known empty tree hash in git
let empty = std::process::Command::new("git")
.args([
"-C",
repo_path.to_str().unwrap(),
"hash-object",
"-t",
"tree",
"/dev/null",
])
.output()
.expect("git hash-object failed");
String::from_utf8_lossy(&empty.stdout).trim().to_string()
}
}
};
let swarm_config = SwarmConfig {
groups: vec![],
timeout: Duration::from_secs(60),
worktree_root: std::path::PathBuf::from("/tmp/test-orchestrator/.worktrees"),
repo_path,
base_branch: "main".to_string(),
max_concurrent_agents: 3,
create_prs: false,
};
let workflow = CompoundReviewWorkflow::new(swarm_config);
let result = workflow.run("HEAD", &base_ref).await.unwrap();
assert!(
!result.correlation_id.is_nil(),
"correlation_id should be set"
);
assert_eq!(result.agents_run, 0, "no agents with empty groups");
assert_eq!(result.agents_failed, 0);
}
/// Regression test for #1562.
///
/// Property: when `check_cron_schedules` fires the compound review,
/// `last_compound_review_fired_at` advances **before** the `await`
/// on `handle_schedule_event`. Calling `check_cron_schedules` a
/// second time without advancing wall-clock time must NOT re-fire
/// the same occurrence; the cursor stays put.
///
/// This is the property that breaks if the cursor is dropped: the
/// 90 s `tokio::time::timeout` wrapping `reconcile_tick` cancels
/// the future mid-await, `last_tick_time` is never updated, and
/// the next tick re-evaluates the same cron occurrence as "should
/// fire", spawning a new worktree every tick (the bigbox storm).
#[tokio::test]
async fn test_compound_review_cursor_advances_on_cancellation() {
// Build a test config and override compound_review so that the
// workflow has no review groups -- it still creates a worktree
// on the workspace git repo, but no agent subprocesses are
// launched. This mirrors `test_orchestrator_compound_review_manual`.
let mut config = test_config();
let tmp_worktree = TempDir::new().expect("tempdir");
config.compound_review.worktree_root = tmp_worktree.path().to_path_buf();
// Schedule fires hourly so we can use a recent `last_tick_time`.
// 5-field cron: minute 0 of every hour.
config.compound_review.schedule = "0 * * * *".to_string();
let mut orch = AgentOrchestrator::new(config).expect("orchestrator");
// Replace the compound workflow with one that uses an empty
// group list so the cron-fire path is a no-op apart from the
// worktree creation/removal. The orchestrator's
// `repo_path`/`base_branch` are inherited from the test config.
let repo_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
let swarm_config = crate::compound::SwarmConfig {
groups: vec![],
timeout: Duration::from_secs(60),
worktree_root: tmp_worktree.path().to_path_buf(),
repo_path,
base_branch: "main".to_string(),
max_concurrent_agents: 1,
create_prs: false,
};
orch.compound_workflow = crate::compound::CompoundReviewWorkflow::new(swarm_config);
// Plant `last_tick_time` 2 hours ago so at least one occurrence
// of `0 * * * *` lies in [last_tick_time, now]. Clear the new
// cursor so the first call has nothing to compare against.
let two_hours_ago = chrono::Utc::now() - chrono::Duration::hours(2);
orch.set_last_tick_time(two_hours_ago);
orch.clear_last_compound_review_fired_at();
assert!(
orch.last_compound_review_fired_at().is_none(),
"cursor should start empty",
);
// First call: should advance the cursor to a past fire time.
orch.check_cron_schedules().await;
let cursor_after_first = orch
.last_compound_review_fired_at()
.expect("cursor should be Some after first fire");
assert!(
cursor_after_first <= chrono::Utc::now(),
"cursor should be in the past, got {}",
cursor_after_first
);
// Second call without advancing wall-clock or `last_tick_time`:
// the cursor must NOT advance (the same occurrence is gated).
orch.check_cron_schedules().await;
let cursor_after_second = orch
.last_compound_review_fired_at()
.expect("cursor should still be Some");
assert_eq!(
cursor_after_first, cursor_after_second,
"cursor must not re-advance on a re-check without new occurrences \
(#1562 storm regression)",
);
}
#[test]
fn test_orchestrator_from_toml() {
let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp"
[[agents]]
name = "test"
layer = "Safety"
cli_tool = "echo"
task = "test"
"#;
let config = OrchestratorConfig::from_toml(toml_str).unwrap();
let orch = AgentOrchestrator::new(config);
assert!(orch.is_ok());
}
#[test]
fn test_agent_status_fields() {
let status = AgentStatus {
name: "test".to_string(),
layer: AgentLayer::Safety,
running: true,
health: HealthStatus::Healthy,
drift_score: Some(0.05),
uptime: Duration::from_secs(3600),
restart_count: 0,
api_calls_remaining: HashMap::new(),
};
assert_eq!(status.name, "test");
assert!(status.running);
assert_eq!(status.drift_score, Some(0.05));
}
#[test]
fn test_load_skill_chain_content_supports_lowercase_skill_md() {
let skill_root = TempDir::new().unwrap();
let skill_dir = skill_root.path().join("business-scenario-design");
std::fs::create_dir_all(&skill_dir).unwrap();
std::fs::write(skill_dir.join("skill.md"), "Lowercase skill content").unwrap();
let mut config = test_config();
config.skill_data_dir = Some(skill_root.path().to_path_buf());
let orch = AgentOrchestrator::new(config).unwrap();
let mut def = orch.config.agents[0].clone();
def.skill_chain = vec!["business-scenario-design".to_string()];
let loaded = orch.load_skill_chain_content(&def);
assert!(loaded.contains("### Skill: business-scenario-design"));
assert!(loaded.contains("Lowercase skill content"));
}
#[test]
fn test_load_skill_chain_content_falls_back_to_home_skill_roots() {
let home_dir = TempDir::new().unwrap();
let configured_skill_root = TempDir::new().unwrap();
let roots = AgentOrchestrator::skill_roots(
Some(configured_skill_root.path()),
Some(home_dir.path()),
None,
);
assert_eq!(roots[0], configured_skill_root.path());
assert!(roots.iter().any(|path| path.ends_with(".opencode/skills")));
assert!(roots.iter().any(|path| path.ends_with(".claude/skills")));
}
/// Helper: create a config with a single Safety echo agent and short cooldown.
fn test_config_fast_lifecycle() -> OrchestratorConfig {
OrchestratorConfig {
working_dir: std::path::PathBuf::from("/tmp"),
nightwatch: NightwatchConfig::default(),
compound_review: CompoundReviewConfig {
cli_tool: None,
provider: None,
model: None,
schedule: "0 2 * * *".to_string(),
max_duration_secs: 60,
repo_path: std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."),
create_prs: false,
worktree_root: std::path::PathBuf::from("/tmp/.worktrees"),
base_branch: "main".to_string(),
max_concurrent_agents: 3,
..Default::default()
},
workflow: None,
agents: vec![AgentDefinition {
name: "echo-safety".to_string(),
layer: AgentLayer::Safety,
cli_tool: "echo".to_string(),
task: "safety watch".to_string(),
model: None,
schedule: None,
capabilities: vec![],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}],
restart_cooldown_secs: 0, // instant restart for testing
max_restart_count: 3,
restart_budget_window_secs: 43_200,
disk_usage_threshold: 100, // disable disk guard in tests
tick_interval_secs: 1,
gate_reconcile_interval_ticks: 20,
handoff_buffer_ttl_secs: None,
persona_data_dir: None,
skill_data_dir: None,
gitea_skill_repo: None,
flows: vec![],
flow_state_dir: None,
gitea: None,
mentions: None,
webhook: None,
role_config_path: None,
routing: None,
#[cfg(feature = "quickwit")]
quickwit: None,
projects: vec![],
include: vec![],
providers: vec![],
provider_budget_state_file: None,
pause_dir: None,
project_circuit_breaker_threshold: 3,
fleet_escalation_owner: None,
fleet_escalation_repo: None,
post_merge_gate: None,
learning: config::LearningConfig::default(),
evolution: config::EvolutionConfig::default(),
pr_dispatch: None,
pr_dispatch_per_project: Default::default(),
}
}
#[tokio::test]
async fn test_reconcile_detects_agent_exit() {
let config = test_config_fast_lifecycle();
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn the echo agent (exits immediately)
let def = orch.config.agents[0].clone();
orch.spawn_agent(&def).await.unwrap();
assert!(orch.active_agents.contains_key("echo-safety"));
// Give echo time to exit
tokio::time::sleep(Duration::from_millis(100)).await;
// Poll for exits
orch.poll_agent_exits().await;
// Agent should be removed from active_agents
assert!(
!orch.active_agents.contains_key("echo-safety"),
"exited agent should be removed from active_agents"
);
// Successful exit (code 0) should NOT increment restart count
assert_eq!(
orch.restart_counts
.get(&legacy_key("echo-safety"))
.copied()
.unwrap_or(0),
0,
"successful exit should not increment restart count"
);
}
#[tokio::test]
async fn test_safety_agent_restarts_after_cooldown() {
let config = test_config_fast_lifecycle();
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn and let it exit
let def = orch.config.agents[0].clone();
orch.spawn_agent(&def).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
orch.poll_agent_exits().await;
assert!(!orch.active_agents.contains_key("echo-safety"));
// Restart pending (cooldown is 0, so immediate)
orch.restart_pending_safety_agents().await;
assert!(
orch.active_agents.contains_key("echo-safety"),
"safety agent should be restarted after cooldown"
);
}
#[tokio::test]
async fn test_core_agent_no_auto_restart() {
let mut config = test_config_fast_lifecycle();
config.agents = vec![AgentDefinition {
name: "echo-core".to_string(),
layer: AgentLayer::Core,
cli_tool: "echo".to_string(),
task: "core task".to_string(),
model: None,
schedule: Some("0 3 * * *".to_string()),
capabilities: vec![],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn core agent and let it exit
let def = orch.config.agents[0].clone();
orch.spawn_agent(&def).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
orch.poll_agent_exits().await;
assert!(!orch.active_agents.contains_key("echo-core"));
// Restart pending should NOT restart a Core agent
orch.restart_pending_safety_agents().await;
assert!(
!orch.active_agents.contains_key("echo-core"),
"core agent should not auto-restart"
);
}
#[tokio::test]
async fn test_max_restart_count_respected() {
let mut config = test_config_fast_lifecycle();
config.max_restart_count = 2;
// Use a command that exits non-zero so restart_count increments
config.agents[0].cli_tool = "false".to_string();
config.agents[0].task = String::new();
let mut orch = AgentOrchestrator::new(config).unwrap();
let def = orch.config.agents[0].clone();
// Cycle through max_restart_count + 1 exits (all non-zero)
for i in 0..3 {
orch.spawn_agent(&def).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
orch.poll_agent_exits().await;
assert!(
!orch.active_agents.contains_key("echo-safety"),
"agent should have exited on cycle {}",
i
);
}
// After 3 non-zero exits, restart count = 3, max = 2
// restart_pending should NOT restart (count > max)
orch.restart_pending_safety_agents().await;
assert!(
!orch.active_agents.contains_key("echo-safety"),
"agent should not restart after exceeding max_restart_count"
);
assert_eq!(
orch.restart_counts.get(&legacy_key("echo-safety")).copied(),
Some(3)
);
}
#[test]
fn test_restart_count_ages_out_after_budget_window() {
let mut config = test_config_fast_lifecycle();
config.restart_budget_window_secs = 1;
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.restart_counts.insert(legacy_key("echo-safety"), 3);
orch.restart_last_failure_unix_secs.insert(
legacy_key("echo-safety"),
chrono::Utc::now().timestamp() - 5,
);
let count = orch.current_restart_count(&legacy_key("echo-safety"));
assert_eq!(count, 0);
assert!(!orch.restart_counts.contains_key(&legacy_key("echo-safety")));
assert!(!orch
.restart_last_failure_unix_secs
.contains_key(&legacy_key("echo-safety")));
}
#[tokio::test]
async fn test_successful_exit_does_not_increment_restart_count() {
let config = test_config_fast_lifecycle();
let mut orch = AgentOrchestrator::new(config).unwrap();
let def = orch.config.agents[0].clone(); // echo "safety watch" -> exit 0
// Spawn and let it exit successfully multiple times
for _ in 0..5 {
orch.spawn_agent(&def).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
orch.poll_agent_exits().await;
}
// Exit code 0 should never increment restart_count
assert_eq!(
orch.restart_counts
.get(&legacy_key("echo-safety"))
.copied()
.unwrap_or(0),
0,
"successful exits (code 0) must not increment restart_count"
);
// Agent should still be eligible for restart
orch.restart_cooldowns.insert(
legacy_key("echo-safety"),
Instant::now() - Duration::from_secs(999),
);
orch.restart_pending_safety_agents().await;
assert!(
orch.active_agents.contains_key("echo-safety"),
"agent with only successful exits should always be restartable"
);
}
#[tokio::test]
async fn test_output_events_fed_to_nightwatch() {
let config = test_config_fast_lifecycle();
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn echo agent (writes "safety watch" to stdout)
let def = orch.config.agents[0].clone();
orch.spawn_agent(&def).await.unwrap();
// Give the output capture time to process
tokio::time::sleep(Duration::from_millis(200)).await;
// Drain events
orch.drain_output_events();
// Nightwatch should have observations for the agent
let drift = orch.nightwatch.drift_score("echo-safety");
assert!(
drift.is_some(),
"nightwatch should have drift data after draining output events"
);
let drift = drift.unwrap();
assert!(
drift.metrics.sample_count > 0,
"nightwatch should have at least one sample from drained output"
);
}
#[tokio::test]
async fn test_reconcile_tick_full_cycle() {
let config = test_config_fast_lifecycle();
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn echo agent
let def = orch.config.agents[0].clone();
orch.spawn_agent(&def).await.unwrap();
// Give echo time to exit and produce output
tokio::time::sleep(Duration::from_millis(200)).await;
// Run a full reconciliation tick
orch.reconcile_tick().await;
// After tick: echo exited, so it was detected and marked for restart.
// With 0 cooldown, it should have been restarted in the same tick.
assert!(
orch.active_agents.contains_key("echo-safety"),
"safety agent should be restarted by reconcile_tick"
);
// echo exits with code 0, so restart_count stays at 0
assert_eq!(
orch.restart_counts
.get(&legacy_key("echo-safety"))
.copied()
.unwrap_or(0),
0,
"successful exit should not increment restart count"
);
}
// =========================================================================
// Persona Injection Tests (Gitea #73)
// =========================================================================
/// Test that spawn_agent composes persona-enriched prompt when persona exists
#[tokio::test]
async fn test_spawn_agent_with_persona_composes_prompt() {
let mut config = test_config_fast_lifecycle();
// Add an agent with a persona
// Use cat (not echo) because persona_found=true triggers stdin delivery.
// cat reads stdin before exiting, avoiding broken pipe under parallel load.
config.agents = vec![AgentDefinition {
name: "persona-agent".to_string(),
layer: AgentLayer::Safety,
cli_tool: "cat".to_string(),
task: "test task".to_string(),
model: None,
schedule: None,
capabilities: vec![],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: Some("TestAgent".to_string()), // Persona that exists in default test_persona
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
// Set up persona data dir with a test persona
let temp_dir =
std::env::temp_dir().join(format!("terraphim-test-persona-{}", std::process::id()));
std::fs::create_dir_all(&temp_dir).unwrap();
let persona_toml = r#"
agent_name = "TestAgent"
role_name = "Test Engineer"
name_origin = "From testing"
vibe = "Thorough, methodical"
symbol = "Checkmark"
core_characteristics = [{ name = "Thorough", description = "checks everything twice" }]
speech_style = "Precise and factual."
terraphim_nature = "Adapted to testing environments."
sfia_title = "Test Engineer"
primary_level = 4
guiding_phrase = "Enable"
level_essence = "Works autonomously under general direction."
sfia_skills = [{ code = "TEST", name = "Testing", level = 4, description = "Designs and executes test plans." }]
"#;
std::fs::write(temp_dir.join("testagent.toml"), persona_toml).unwrap();
config.persona_data_dir = Some(temp_dir.clone());
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn the agent - it should use the persona-enriched prompt
let def = orch.config.agents[0].clone();
let result = orch.spawn_agent(&def).await;
// Cleanup
let _ = std::fs::remove_dir_all(&temp_dir);
// Spawn should succeed
assert!(result.is_ok());
// The agent should be active
assert!(orch.active_agents.contains_key("persona-agent"));
}
/// Test that spawn_agent uses bare task when persona is None
#[tokio::test]
async fn test_spawn_agent_without_persona_uses_bare_task() {
let config = test_config_fast_lifecycle();
let mut orch = AgentOrchestrator::new(config).unwrap();
// Agent without persona should use bare task
let def = orch.config.agents[0].clone();
assert!(def.persona.is_none());
let result = orch.spawn_agent(&def).await;
assert!(result.is_ok());
assert!(orch.active_agents.contains_key("echo-safety"));
}
/// Test graceful degradation when persona not found in registry
#[tokio::test]
async fn test_spawn_agent_persona_not_found_graceful() {
let mut config = test_config_fast_lifecycle();
// Add an agent with a non-existent persona
config.agents = vec![AgentDefinition {
name: "unknown-persona-agent".to_string(),
layer: AgentLayer::Safety,
cli_tool: "echo".to_string(),
task: "test task".to_string(),
model: None,
schedule: None,
capabilities: vec![],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: Some("NonExistentPersona".to_string()), // This persona doesn't exist
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
// No persona_data_dir, so registry will be empty
config.persona_data_dir = None;
let mut orch = AgentOrchestrator::new(config).unwrap();
// Spawn should still succeed even though persona doesn't exist
let def = orch.config.agents[0].clone();
let result = orch.spawn_agent(&def).await;
assert!(
result.is_ok(),
"spawn should succeed with fallback to bare task"
);
assert!(orch.active_agents.contains_key("unknown-persona-agent"));
}
// ==================== Agent Name Validation Tests ====================
#[test]
fn test_validate_agent_name_accepts_valid() {
assert!(validate_agent_name("my-agent_1").is_ok());
assert!(validate_agent_name("sentinel").is_ok());
assert!(validate_agent_name("Agent-42").is_ok());
}
#[test]
fn test_validate_agent_name_rejects_traversal() {
assert!(validate_agent_name("../etc/passwd").is_err());
assert!(validate_agent_name("..").is_err());
assert!(validate_agent_name("foo/../bar").is_err());
}
#[test]
fn test_validate_agent_name_rejects_slash() {
assert!(validate_agent_name("foo/bar").is_err());
assert!(validate_agent_name("foo\\bar").is_err());
}
#[test]
fn test_validate_agent_name_rejects_empty() {
assert!(validate_agent_name("").is_err());
}
#[test]
fn test_validate_agent_name_rejects_special_chars() {
assert!(validate_agent_name("agent name").is_err()); // spaces
assert!(validate_agent_name("agent@host").is_err()); // @
assert!(validate_agent_name("agent.name").is_err()); // dots
}
// ==================== has_matching_changes Tests ====================
#[test]
fn test_has_matching_changes_prefix_match() {
let changed = vec!["crates/orchestrator/src/lib.rs".to_string()];
let watch = vec!["crates/orchestrator/".to_string()];
assert!(has_matching_changes(&changed, &watch));
}
#[test]
fn test_has_matching_changes_exact_match() {
let changed = vec!["Cargo.toml".to_string()];
let watch = vec!["Cargo.toml".to_string()];
assert!(has_matching_changes(&changed, &watch));
}
#[test]
fn test_has_matching_changes_no_match() {
let changed = vec!["docs/README.md".to_string()];
let watch = vec!["crates/orchestrator/".to_string()];
assert!(!has_matching_changes(&changed, &watch));
}
#[test]
fn test_has_matching_changes_multiple_files_one_matches() {
let changed = vec![
"docs/README.md".to_string(),
"crates/orchestrator/src/config.rs".to_string(),
];
let watch = vec!["crates/orchestrator/".to_string()];
assert!(has_matching_changes(&changed, &watch));
}
#[test]
fn test_has_matching_changes_multiple_watch_paths() {
let changed = vec!["tests/integration.rs".to_string()];
let watch = vec!["crates/orchestrator/".to_string(), "tests/".to_string()];
assert!(has_matching_changes(&changed, &watch));
}
#[test]
fn test_has_matching_changes_empty_watch_paths() {
let changed = vec!["crates/orchestrator/src/lib.rs".to_string()];
let watch: Vec<String> = vec![];
assert!(!has_matching_changes(&changed, &watch));
}
// =========================================================================
// ADF Remediation Tests (Gitea #117)
// =========================================================================
#[test]
fn test_provider_model_composition_opencode() {
// Simulate what spawn_agent does for opencode with provider + model
let provider = Some("kimi-for-coding".to_string());
let model = Some("k2p5".to_string());
let cli_name = "opencode";
let composed = if cli_name == "opencode" {
match (&provider, &model) {
(Some(p), Some(m)) => Some(format!("{}/{}", p, m)),
_ => model,
}
} else {
model
};
assert_eq!(composed, Some("kimi-for-coding/k2p5".to_string()));
}
#[test]
fn test_provider_model_composition_claude_unchanged() {
// Claude should not have provider/model composed
let provider = Some("anthropic".to_string());
let model = Some("claude-opus-4-6".to_string());
let cli_name = "claude";
let composed = if cli_name == "opencode" {
match (&provider, &model) {
(Some(p), Some(m)) => Some(format!("{}/{}", p, m)),
_ => model.clone(),
}
} else {
model.clone()
};
assert_eq!(composed, Some("claude-opus-4-6".to_string()));
}
#[test]
fn parse_reset_time_relative_hours() {
let result = parse_reset_time("resets in 2 hours");
assert!(result.is_some());
}
#[test]
fn parse_reset_time_relative_minutes() {
let result = parse_reset_time("resets in 30 minutes");
assert!(result.is_some());
}
#[test]
fn parse_reset_time_utc_format() {
let result = parse_reset_time("resets at 14:00 UTC");
assert!(result.is_some());
}
#[test]
fn parse_reset_time_fallback_generic() {
let result = parse_reset_time("resets 2am Europe/Berlin");
assert!(result.is_some());
}
#[test]
fn parse_reset_time_no_match() {
let result = parse_reset_time("something unrelated");
assert!(result.is_none());
}
#[test]
fn parse_reset_time_short_hours_abbreviation() {
// "resets in 4h" -- Claude Code's compact format
let before = std::time::Instant::now();
let result = parse_reset_time("5-hour limit reached, resets in 4h").unwrap();
let delta = result.duration_since(before);
// 4 hours, allowing a small wall-clock slack between `before` and `Instant::now()`
// inside the parser.
assert!(delta >= std::time::Duration::from_secs(4 * 3600 - 1));
assert!(delta <= std::time::Duration::from_secs(4 * 3600 + 5));
}
#[test]
fn parse_reset_time_short_minutes_abbreviation() {
// "resets in 30m"
let before = std::time::Instant::now();
let result = parse_reset_time("resets in 30m").unwrap();
let delta = result.duration_since(before);
assert!(delta >= std::time::Duration::from_secs(30 * 60 - 1));
assert!(delta <= std::time::Duration::from_secs(30 * 60 + 5));
}
#[test]
fn parse_reset_time_pm_suffix() {
// "resets 11pm" -- amount depends on wall-clock; just assert non-zero & bounded
let result = parse_reset_time("you've hit your session limit, resets 11pm");
assert!(result.is_some(), "11pm must parse to a future instant");
// The pm path computes a delta < 24h.
let delta = result.unwrap().duration_since(std::time::Instant::now());
assert!(delta <= std::time::Duration::from_secs(24 * 3600));
}
#[test]
fn parse_reset_time_am_suffix() {
let result = parse_reset_time("session limit reached, resets 7am");
assert!(result.is_some());
let delta = result.unwrap().duration_since(std::time::Instant::now());
assert!(delta <= std::time::Duration::from_secs(24 * 3600));
}
#[test]
fn parse_reset_time_unknown_without_resets_returns_none() {
// No "resets" token at all -> caller applies safety floor.
assert!(parse_reset_time("you've hit your session limit").is_none());
assert!(parse_reset_time("rate limit exceeded, try later").is_none());
}
#[test]
fn default_rate_limit_block_is_fifteen_minutes() {
assert_eq!(
DEFAULT_RATE_LIMIT_BLOCK,
std::time::Duration::from_secs(900)
);
}
#[test]
fn agent_def_bypass_kg_routing_defaults_false() {
// TOML without the field deserialises to `false` via #[serde(default)].
let toml_src = r#"
name = "test-agent"
layer = "Core"
cli_tool = "/bin/echo"
task = "ping"
"#;
let def: AgentDefinition = toml::from_str(toml_src).expect("parse default");
assert!(!def.bypass_kg_routing);
}
#[test]
fn agent_def_bypass_kg_routing_explicit_true() {
let toml_src = r#"
name = "test-agent"
layer = "Core"
cli_tool = "/bin/echo"
task = "ping"
bypass_kg_routing = true
"#;
let def: AgentDefinition = toml::from_str(toml_src).expect("parse explicit");
assert!(def.bypass_kg_routing);
}
#[test]
fn rate_limit_window_block_and_check() {
let mut window = ProviderRateLimitWindow::new();
assert!(!window.is_blocked("claude-code"));
window.block_until(
"claude-code",
std::time::Instant::now() + std::time::Duration::from_secs(3600),
);
assert!(window.is_blocked("claude-code"));
assert!(!window.is_blocked("kimi"));
}
#[test]
fn rate_limit_window_expired_unblocks() {
let mut window = ProviderRateLimitWindow::new();
window.block_until(
"claude-code",
std::time::Instant::now() + std::time::Duration::from_millis(1),
);
std::thread::sleep(std::time::Duration::from_millis(5));
assert!(!window.is_blocked("claude-code"));
}
#[test]
fn rate_limit_window_blocked_providers_list() {
let mut window = ProviderRateLimitWindow::new();
window.block_until(
"claude-code",
std::time::Instant::now() + std::time::Duration::from_secs(3600),
);
window.block_until(
"anthropic",
std::time::Instant::now() + std::time::Duration::from_secs(3600),
);
let blocked = window.blocked_providers();
assert_eq!(blocked.len(), 2);
assert!(blocked.contains(&"claude-code".to_string()));
assert!(blocked.contains(&"anthropic".to_string()));
}
#[test]
fn rate_limit_window_clean_expired() {
let mut window = ProviderRateLimitWindow::new();
window.block_until(
"expired",
std::time::Instant::now() + std::time::Duration::from_millis(1),
);
window.block_until(
"active",
std::time::Instant::now() + std::time::Duration::from_secs(3600),
);
std::thread::sleep(std::time::Duration::from_millis(5));
window.clean_expired();
assert!(!window.is_blocked("expired"));
assert!(window.is_blocked("active"));
}
#[tokio::test]
async fn test_wall_clock_timeout_kills_agent() {
let mut config = test_config_fast_lifecycle();
// Use sleep agent with 1-second timeout
config.agents = vec![AgentDefinition {
name: "timeout-test".to_string(),
layer: AgentLayer::Core,
cli_tool: "sleep".to_string(),
task: "60".to_string(),
model: None,
schedule: None,
capabilities: vec![],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: Some(2),
max_cpu_seconds: Some(1), // 1 second timeout
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
let mut orch = AgentOrchestrator::new(config).unwrap();
let def = orch.config.agents[0].clone();
orch.spawn_agent(&def).await.unwrap();
assert!(orch.active_agents.contains_key("timeout-test"));
// Wait for the timeout to elapse
tokio::time::sleep(Duration::from_secs(2)).await;
// Poll should detect timeout and kill
orch.poll_agent_exits().await;
assert!(!orch.active_agents.contains_key("timeout-test"));
}
// =========================================================================
// Flow DAG Orchestrator Integration Tests (Gitea #163)
// =========================================================================
#[test]
fn test_orchestrator_with_empty_flows() {
let mut config = test_config();
config.flows = vec![];
config.flow_state_dir = None;
let orch = AgentOrchestrator::new(config);
assert!(
orch.is_ok(),
"orchestrator should initialize with empty flows"
);
let orch = orch.unwrap();
assert!(
orch.active_flows.is_empty(),
"active_flows should be empty initially"
);
}
/// Test that flow scheduling overlap prevention works
#[tokio::test]
async fn test_flow_overlap_prevention() {
use crate::flow::config::{FlowDefinition, FlowStepDef, StepKind};
let mut config = test_config_fast_lifecycle();
// Add a test flow with a schedule
config.flows = vec![FlowDefinition {
name: "test-flow".to_string(),
project: "test".to_string(),
schedule: Some("0 2 * * *".to_string()), // 2 AM daily
repo_path: "/tmp/test-repo".to_string(),
base_branch: "main".to_string(),
timeout_secs: 3600,
steps: vec![FlowStepDef {
name: "test-step".to_string(),
kind: StepKind::Action,
command: Some("echo test".to_string()),
cli_tool: None,
model: None,
task: None,
task_file: None,
condition: None,
timeout_secs: 60,
on_fail: crate::flow::config::FailStrategy::Abort,
provider: None,
persona: None,
matrix: None,
}],
}];
config.flow_state_dir = Some(PathBuf::from("/tmp/test-flow-states"));
let orch = AgentOrchestrator::new(config);
assert!(orch.is_ok(), "orchestrator should initialize with flows");
let orch = orch.unwrap();
assert!(
orch.active_flows.is_empty(),
"active_flows should be empty initially"
);
}
// ==================== Sanitisation Tests ====================
#[test]
fn test_sanitise_for_title_strips_json_braces() {
let input = r#"{"type":"tool_use","timestamp":1775313676859}"#;
let result = AgentOrchestrator::sanitise_for_title(input);
assert!(!result.contains('{'), "title should not contain open brace");
assert!(
!result.contains('}'),
"title should not contain close brace"
);
assert!(
!result.contains('['),
"title should not contain open bracket"
);
assert!(
!result.contains(']'),
"title should not contain close bracket"
);
}
#[test]
fn test_sanitise_for_title_strips_quotes() {
let input = r#"JSON "quoted" text"#;
let result = AgentOrchestrator::sanitise_for_title(input);
assert!(!result.contains('"'), "title should not contain quotes");
}
#[test]
fn test_sanitise_for_title_truncates_long_input() {
let input = "This is a very long finding text that should be truncated because it exceeds eighty characters limit";
let result = AgentOrchestrator::sanitise_for_title(input);
assert!(
result.len() <= 80,
"title should be at most 80 chars, got {}",
result.len()
);
}
#[test]
fn test_sanitise_for_body_escapes_backticks() {
let input = "Use `code` here";
let result = AgentOrchestrator::sanitise_for_body(input);
assert!(result.contains("``"), "body should escape backticks");
}
#[test]
fn test_sanitise_for_body_escapes_markdown_chars() {
let input = "Text with *asterisks* and [brackets]";
let result = AgentOrchestrator::sanitise_for_body(input);
assert!(
result.contains('\\'),
"body should contain backslash, got: {}",
result
);
}
/// An agent whose monthly budget is exhausted must skip spawn entirely.
/// `CostTracker::check()` returning `Exhausted` short-circuits
/// dispatch before pre-check or routing runs.
#[tokio::test]
async fn test_spawn_agent_skips_when_budget_exhausted() {
let mut config = test_config_fast_lifecycle();
config.agents = vec![AgentDefinition {
name: "broke-agent".to_string(),
layer: AgentLayer::Safety,
cli_tool: "echo".to_string(),
task: "should not run".to_string(),
model: None,
schedule: None,
capabilities: vec![],
max_memory_bytes: None,
// $1 monthly budget.
budget_monthly_cents: Some(100),
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
let mut orch = AgentOrchestrator::new(config).unwrap();
// Blow through the budget before attempting to spawn.
let verdict = orch.cost_tracker.record_cost("broke-agent", 2.00);
assert!(
verdict.should_pause(),
"budget must be exhausted: {verdict}"
);
let def = orch.config.agents[0].clone();
let result = orch.spawn_agent(&def).await;
// Spawn should succeed-with-no-op rather than error.
assert!(result.is_ok(), "spawn returned error: {:?}", result);
// Agent must NOT have been added to active_agents.
assert!(
!orch.active_agents.contains_key("broke-agent"),
"exhausted agent should not have been spawned"
);
}
/// An agent with no budget cap (subscription) must spawn normally
/// even after recording cost -- `record_cost` returns `Uncapped`.
#[tokio::test]
async fn test_spawn_agent_runs_when_budget_uncapped() {
let mut config = test_config_fast_lifecycle();
// Ensure the only agent is uncapped.
config.agents[0].budget_monthly_cents = None;
config.agents[0].name = "subscription-agent".to_string();
let mut orch = AgentOrchestrator::new(config).unwrap();
// Even a large recorded spend must not pause an uncapped agent.
let _ = orch
.cost_tracker
.record_cost("subscription-agent", 9_999.00);
let verdict = orch.cost_tracker.check("subscription-agent");
assert!(!verdict.should_pause(), "uncapped must never pause");
let def = orch.config.agents[0].clone();
let result = orch.spawn_agent(&def).await;
assert!(result.is_ok(), "spawn errored: {:?}", result);
assert!(orch.active_agents.contains_key("subscription-agent"));
}
/// Helper: build a minimal config with a project-scoped `pr-reviewer`
/// agent suitable for driving `handle_review_pr` through the full
/// routing and spawn pipeline. Returns the config plus the tempdir that
/// owns the working directory so the caller keeps it alive.
fn review_pr_config(cli_tool: &str) -> (OrchestratorConfig, TempDir) {
let tmp = TempDir::new().unwrap();
let working_dir = tmp.path().to_path_buf();
let config = OrchestratorConfig {
working_dir: working_dir.clone(),
nightwatch: NightwatchConfig::default(),
compound_review: CompoundReviewConfig {
cli_tool: None,
provider: None,
model: None,
schedule: "0 2 * * *".to_string(),
max_duration_secs: 60,
repo_path: working_dir.clone(),
create_prs: false,
worktree_root: working_dir.join(".worktrees"),
base_branch: "main".to_string(),
max_concurrent_agents: 3,
..Default::default()
},
workflow: None,
agents: vec![AgentDefinition {
name: "pr-reviewer".to_string(),
layer: AgentLayer::Safety,
cli_tool: cli_tool.to_string(),
task: "review".to_string(),
model: None,
schedule: None,
capabilities: vec!["review".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: Some("alpha".to_string()),
}],
restart_cooldown_secs: 0,
max_restart_count: 3,
restart_budget_window_secs: 43_200,
disk_usage_threshold: 100,
tick_interval_secs: 1,
gate_reconcile_interval_ticks: 20,
handoff_buffer_ttl_secs: None,
persona_data_dir: None,
skill_data_dir: None,
flows: vec![],
flow_state_dir: None,
gitea: None,
mentions: None,
webhook: None,
role_config_path: None,
routing: None,
#[cfg(feature = "quickwit")]
quickwit: None,
projects: vec![crate::config::Project {
id: "alpha".to_string(),
working_dir: working_dir.clone(),
schedule_offset_minutes: 0,
gitea: None,
mentions: None,
workflow: None,
#[cfg(feature = "quickwit")]
quickwit: None,
max_concurrent_agents: None,
max_concurrent_mention_agents: None,
}],
include: vec![],
providers: vec![],
provider_budget_state_file: None,
gitea_skill_repo: None,
pause_dir: None,
project_circuit_breaker_threshold: 3,
fleet_escalation_owner: None,
fleet_escalation_repo: None,
post_merge_gate: None,
learning: config::LearningConfig::default(),
evolution: config::EvolutionConfig::default(),
pr_dispatch: None,
pr_dispatch_per_project: Default::default(),
};
(config, tmp)
}
fn review_pr_task() -> dispatcher::DispatchTask {
dispatcher::DispatchTask::ReviewPr {
pr_number: 641,
project: "alpha".to_string(),
head_sha: "deadbeef1234".to_string(),
author_login: "claude-code".to_string(),
title: "fix(kg): short synonyms".to_string(),
diff_loc: 42,
}
}
/// `handle_review_pr` must drive the routing engine and spawn the
/// pr-reviewer agent it selected, registering it in `active_agents`.
#[tokio::test]
async fn reviewpr_dispatch_routes_via_routing_engine() {
let (config, _tmp) = review_pr_config("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
let managed = orch
.active_agents
.get("pr-reviewer")
.expect("pr-reviewer must be registered in active_agents after routing");
assert!(
!managed.session_id.is_empty(),
"routing must tag the spawned agent with a session_id"
);
assert!(
managed.session_id.starts_with("pr-reviewer-"),
"session id should be scoped to the agent, got: {}",
managed.session_id
);
}
/// When a workflow tracker is configured, `handle_review_pr` must POST
/// a `pending` commit status with context `adf/pr-reviewer` for the
/// PR head SHA after spawning. Verifies issue #928 (ADF Phase 1).
#[tokio::test]
async fn reviewpr_dispatch_posts_pending_status_when_tracker_configured() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
last_path: std::sync::Mutex<Option<String>>,
last_body: std::sync::Mutex<Option<serde_json::Value>>,
}
async fn capture(
Path((owner, repo, sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
*captured.last_path.lock().unwrap() =
Some(format!("/api/v1/repos/{}/{}/statuses/{}", owner, repo, sha));
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
*captured.last_body.lock().unwrap() = Some(parsed);
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
// Build the standard review-pr config and bolt on a workflow that
// points at the loopback Gitea endpoint above. Tests with no
// workflow already cover the silent skip-path (other reviewpr_*).
let (mut config, _tmp) = review_pr_config("echo");
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Allow the loopback server to receive the POST.
for _ in 0..50 {
if captured.calls.load(AOrdering::SeqCst) > 0 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(
captured.calls.load(AOrdering::SeqCst),
1,
"exactly one pending status post expected"
);
assert_eq!(
captured.last_path.lock().unwrap().as_deref(),
Some("/api/v1/repos/fakeowner/fakerepo/statuses/deadbeef1234")
);
let body = captured.last_body.lock().unwrap().clone().unwrap();
assert_eq!(body["state"], "pending");
assert_eq!(body["context"], "adf/pr-reviewer");
}
/// A banned provider configured on the pr-reviewer agent must be
/// short-circuited by the C1/C3 allow-list gate; no spawn happens.
#[tokio::test]
async fn reviewpr_dispatch_rejects_banned_provider() {
let (config, _tmp) = review_pr_config("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
// Bypass load-time validation by mutating after construction to
// simulate a stale/poisoned config entry reaching the dispatcher.
orch.config.agents[0].model = Some("google/gemini-2".to_string());
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
!orch.active_agents.contains_key("pr-reviewer"),
"banned provider must short-circuit before spawn"
);
}
/// The per-PR `ADF_PR_*` env overrides must reach the spawned process so
/// downstream review skills can read them without parsing the task string.
#[tokio::test]
async fn reviewpr_dispatch_sets_env_vars() {
let tmp = TempDir::new().unwrap();
let script_path = tmp.path().join("dump-env.sh");
let dump_path = tmp.path().join("env.dump");
let script_body = format!(
"#!/bin/sh\nenv | grep '^ADF_PR_' > {}\n",
dump_path.display()
);
std::fs::write(&script_path, script_body).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&script_path).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&script_path, perms).unwrap();
}
let (config, _cfg_tmp) = review_pr_config(script_path.to_str().unwrap());
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(orch.active_agents.contains_key("pr-reviewer"));
// Poll for the script to exit and for the child process reaper to
// drop it out of active_agents, then read the env dump it wrote.
for _ in 0..40 {
tokio::time::sleep(Duration::from_millis(50)).await;
orch.poll_agent_exits().await;
if dump_path.exists() {
break;
}
}
let dump = std::fs::read_to_string(&dump_path)
.unwrap_or_else(|e| panic!("env dump not written to {}: {e}", dump_path.display()));
assert!(
dump.contains("ADF_PR_NUMBER=641"),
"ADF_PR_NUMBER missing from dump:\n{dump}"
);
assert!(
dump.contains("ADF_PR_HEAD_SHA=deadbeef1234"),
"ADF_PR_HEAD_SHA missing from dump:\n{dump}"
);
assert!(
dump.contains("ADF_PR_PROJECT=alpha"),
"ADF_PR_PROJECT missing from dump:\n{dump}"
);
assert!(
dump.contains("ADF_PR_AUTHOR=claude-code"),
"ADF_PR_AUTHOR missing from dump:\n{dump}"
);
assert!(
dump.contains("ADF_PR_DIFF_LOC=42"),
"ADF_PR_DIFF_LOC missing from dump:\n{dump}"
);
assert!(
dump.contains("ADF_PR_TITLE=fix(kg): short synonyms"),
"ADF_PR_TITLE missing from dump:\n{dump}"
);
}
/// Helper: extend a `review_pr_config` setup with a project-scoped
/// `build-runner` agent and a Phase 2 D2 fan-out list. After issue
/// #962 the dispatch table lives in `pr_dispatch_per_project`, keyed
/// by the project id ("alpha" in these fixtures); the top-level
/// `pr_dispatch` field is left as `None` to exercise the new
/// per-project lookup branch end-to-end. Sibling tests
/// (`handle_review_pr_skips_missing_agents`,
/// `handle_review_pr_pending_status_posted_per_agent`,
/// `handle_review_pr_skipped_agent_does_not_post_pending`) keep
/// populating the top-level `pr_dispatch` field directly to
/// exercise the backward-compat fallback path.
fn review_pr_config_with_fanout(cli_tool: &str) -> (OrchestratorConfig, TempDir) {
let (mut config, tmp) = review_pr_config(cli_tool);
config.agents.push(AgentDefinition {
name: "build-runner".to_string(),
layer: AgentLayer::Growth,
cli_tool: cli_tool.to_string(),
task: "build".to_string(),
model: None,
schedule: None,
capabilities: vec!["build".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: Some("alpha".to_string()),
});
config.pr_dispatch_per_project.insert(
"alpha".to_string(),
crate::config::PrDispatchConfig {
agents_on_pr_open: vec![
crate::config::PrDispatchEntry {
name: "build-runner".to_string(),
context: "adf/build".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-reviewer".to_string(),
context: "adf/pr-reviewer".to_string(),
},
],
},
);
(config, tmp)
}
/// ADF Phase 2 (issue #944): a `pull_request.opened` event with both
/// `build-runner` and `pr-reviewer` in `agents_on_pr_open` must spawn
/// both agents. Each receives the appropriate env injection: build-runner
/// gets `ADF_PUSH_*` (mirroring `handle_push`); pr-reviewer keeps the
/// existing `ADF_PR_*` keys.
#[tokio::test]
async fn handle_review_pr_spawns_both_build_runner_and_pr_reviewer() {
let (config, _tmp) = review_pr_config_with_fanout("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
orch.active_agents.contains_key("pr-reviewer"),
"pr-reviewer must be spawned; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
assert!(
orch.active_agents.contains_key("build-runner"),
"build-runner must be spawned; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
}
/// The per-agent env injection must distinguish the two agents:
/// build-runner sees `ADF_PUSH_*` (with `ref_name = refs/pull/<n>/head`),
/// pr-reviewer sees `ADF_PR_*`. Verified by writing a tiny script that
/// dumps env to a file and reading the artefacts back.
#[tokio::test]
async fn handle_review_pr_injects_per_agent_env_correctly() {
let tmp = TempDir::new().unwrap();
let pr_dump = tmp.path().join("pr.env");
let push_dump = tmp.path().join("push.env");
// Single shell script that picks which dump to write based on which
// env vars are present. Avoids needing two separate cliTools.
// NOTE: Check for ADF_PR_NUMBER first because child processes inherit
// the parent environment (cargo test inherits from build-runner which
// has ADF_PUSH_SHA set), so absence of ADF_PUSH_SHA is not reliable.
let script_path = tmp.path().join("dump-env.sh");
let all_dump = tmp.path().join("all.env");
let script_body = format!(
"#!/bin/sh\nenv > {}\nif [ -n \"$ADF_PR_NUMBER\" ]; then env | grep '^ADF_PR_' > {}\nelse env | grep '^ADF_PUSH_' > {}\nfi\n",
all_dump.display(),
pr_dump.display(),
push_dump.display(),
);
std::fs::write(&script_path, script_body).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&script_path).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&script_path, perms).unwrap();
}
let (config, _cfg_tmp) = review_pr_config_with_fanout(script_path.to_str().unwrap());
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Allow agents time to spawn before polling
tokio::time::sleep(Duration::from_secs(2)).await;
for i in 0..600 {
tokio::time::sleep(Duration::from_millis(50)).await;
orch.poll_agent_exits().await;
if pr_dump.exists() && push_dump.exists() {
break;
}
if i == 100 {
eprintln!(
"Still waiting after 5s. Active agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
}
}
let pr = std::fs::read_to_string(&pr_dump).unwrap_or_default();
let push = std::fs::read_to_string(&push_dump).unwrap_or_default();
let all_env = std::fs::read_to_string(&all_dump).unwrap_or_default();
if !pr.contains("ADF_PR_NUMBER=641") || !push.contains("ADF_PUSH_SHA=deadbeef1234") {
eprintln!(
"active_agents after poll loop: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
eprintln!("pr_dump path: {}", pr_dump.display());
eprintln!("push_dump path: {}", push_dump.display());
eprintln!("pr_dump exists: {}", pr_dump.exists());
eprintln!("push_dump exists: {}", push_dump.exists());
eprintln!("pr_dump contents:\n{pr}");
eprintln!("push_dump contents:\n{push}");
eprintln!("all env dump:\n{all_env}");
}
assert!(
pr.contains("ADF_PR_NUMBER=641"),
"pr-reviewer env missing ADF_PR_NUMBER:\n{pr}"
);
assert!(
push.contains("ADF_PUSH_SHA=deadbeef1234"),
"build-runner env missing ADF_PUSH_SHA=deadbeef1234:\n{push}"
);
assert!(
push.contains("ADF_PUSH_REF=refs/pull/641/head"),
"build-runner env missing ADF_PUSH_REF=refs/pull/641/head:\n{push}"
);
assert!(
push.contains("ADF_PUSH_PROJECT=alpha"),
"build-runner env missing ADF_PUSH_PROJECT=alpha:\n{push}"
);
}
/// When `agents_on_pr_open` references an agent that isn't configured
/// for the project, the orchestrator must skip it gracefully without
/// panicking and without posting a `pending` status that would never
/// resolve. The other entries still spawn.
#[tokio::test]
async fn handle_review_pr_skips_missing_agents() {
// Standard config has only pr-reviewer; bolt on a pr_dispatch list
// that ALSO references build-runner (which is absent).
let (mut config, _tmp) = review_pr_config("echo");
config.pr_dispatch = Some(crate::config::PrDispatchConfig {
agents_on_pr_open: vec![
crate::config::PrDispatchEntry {
name: "build-runner".to_string(),
context: "adf/build".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-reviewer".to_string(),
context: "adf/pr-reviewer".to_string(),
},
],
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
orch.active_agents.contains_key("pr-reviewer"),
"pr-reviewer must still spawn even when build-runner is missing"
);
assert!(
!orch.active_agents.contains_key("build-runner"),
"build-runner must not be spawned when not configured"
);
}
/// When a workflow tracker is configured, each fan-out agent that spawns
/// must POST exactly one `pending` commit status with its configured
/// context. With both build-runner and pr-reviewer in the dispatch list,
/// the orchestrator must POST two distinct statuses.
#[tokio::test]
async fn handle_review_pr_pending_status_posted_per_agent() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
states: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
if let Some(st) = parsed.get("state").and_then(|v| v.as_str()) {
captured.states.lock().unwrap().push(st.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_fanout("echo");
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Wait for both POSTs.
for _ in 0..100 {
if captured.calls.load(AOrdering::SeqCst) >= 2 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(
captured.calls.load(AOrdering::SeqCst),
2,
"exactly two pending status posts expected (one per fan-out agent)"
);
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/build"),
"adf/build pending status missing; got: {contexts:?}"
);
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"adf/pr-reviewer pending status missing; got: {contexts:?}"
);
let states = captured.states.lock().unwrap().clone();
assert!(
states.iter().all(|s| s == "pending"),
"all initial statuses must be pending; got: {states:?}"
);
}
/// When a fan-out agent is gated out (in this test: build-runner has a
/// banned static model so the C1/C3 subscription gate short-circuits its
/// spawn), the orchestrator must NOT post a `pending` status for that
/// agent. A `pending` that never resolves would block the PR forever.
/// The other agent still spawns and posts its own pending.
#[tokio::test]
async fn handle_review_pr_skipped_agent_does_not_post_pending() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_fanout("echo");
// Stamp a banned model on build-runner AFTER load-time validation
// so the runtime allow-list gate is the one rejecting the spawn.
let br = config
.agents
.iter_mut()
.find(|a| a.name == "build-runner")
.unwrap();
br.model = Some("google/gemini-2".to_string());
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Allow time for the (single expected) POST to land — and any
// erroneous extra POST to also land if the bug is present.
for _ in 0..100 {
if captured.calls.load(AOrdering::SeqCst) >= 1 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
// Give a small grace window for an erroneous adf/build POST to surface.
tokio::time::sleep(Duration::from_millis(100)).await;
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"pr-reviewer must still post its pending status; got: {contexts:?}"
);
assert!(
!contexts.iter().any(|c| c == "adf/build"),
"skipped build-runner must NOT post adf/build pending; got: {contexts:?}"
);
assert!(
!orch.active_agents.contains_key("build-runner"),
"build-runner must not be in active_agents when subscription gate rejects"
);
}
/// Phase 2b helper: extend `review_pr_config_with_fanout` with a third
/// project-scoped `pr-spec-validator` agent and a three-entry
/// `[pr_dispatch]` block (build-runner, pr-reviewer, pr-spec-validator).
fn review_pr_config_with_spec_fanout(cli_tool: &str) -> (OrchestratorConfig, TempDir) {
let (mut config, tmp) = review_pr_config_with_fanout(cli_tool);
config.agents.push(AgentDefinition {
name: "pr-spec-validator".to_string(),
layer: AgentLayer::Safety,
cli_tool: cli_tool.to_string(),
task: "spec".to_string(),
model: None,
schedule: None,
capabilities: vec!["review".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec!["requirements-traceability".to_string()],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: Some("alpha".to_string()),
});
// The per-project block takes precedence over the top-level block,
// so we must update both to keep them in sync.
config
.pr_dispatch_per_project
.get_mut("alpha")
.unwrap()
.agents_on_pr_open
.push(crate::config::PrDispatchEntry {
name: "pr-spec-validator".to_string(),
context: "adf/spec".to_string(),
});
config.pr_dispatch = Some(crate::config::PrDispatchConfig {
agents_on_pr_open: vec![
crate::config::PrDispatchEntry {
name: "build-runner".to_string(),
context: "adf/build".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-reviewer".to_string(),
context: "adf/pr-reviewer".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-spec-validator".to_string(),
context: "adf/spec".to_string(),
},
],
});
(config, tmp)
}
/// ADF Phase 2b (Refs #950): a `pull_request.opened` event with
/// `pr-spec-validator` in `agents_on_pr_open` must spawn the agent.
/// Verifies the existing fan-out loop's generic `_` arm (which routes
/// any non-`build-runner` entry through `dispatch_pr_reviewer_for_pr`
/// by name) handles the new context cleanly without code change.
#[tokio::test]
async fn handle_review_pr_spawns_pr_spec_validator_when_configured() {
let (config, _tmp) = review_pr_config_with_spec_fanout("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
orch.active_agents.contains_key("pr-spec-validator"),
"pr-spec-validator must be spawned; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
// Spec-validator is a PR-event agent, so it must receive the
// `ADF_PR_*` env (not `ADF_PUSH_*`). Verified via session_id
// scoping; the env wiring itself is exercised by the existing
// `reviewpr_dispatch_sets_env_vars` test through the same
// dispatch helper.
let managed = orch.active_agents.get("pr-spec-validator").unwrap();
assert!(
managed.session_id.starts_with("pr-spec-validator-"),
"session id should be scoped to the agent, got: {}",
managed.session_id
);
}
/// ADF Phase 2b (Refs #950): when a workflow tracker is configured,
/// `pr-spec-validator`'s spawn must POST a `pending` commit status
/// with context `adf/spec` against the PR head SHA.
#[tokio::test]
async fn handle_review_pr_pending_status_posted_for_spec_context() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
states: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
if let Some(st) = parsed.get("state").and_then(|v| v.as_str()) {
captured.states.lock().unwrap().push(st.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_spec_fanout("echo");
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Expect three POSTs (one per fan-out agent).
for _ in 0..150 {
if captured.calls.load(AOrdering::SeqCst) >= 3 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/spec"),
"adf/spec pending status missing; got: {contexts:?}"
);
let states = captured.states.lock().unwrap().clone();
assert!(
states.iter().all(|s| s == "pending"),
"all initial statuses must be pending; got: {states:?}"
);
}
/// ADF Phase 2b (Refs #950): when `pr-spec-validator` is gated out by
/// the runtime subscription allow-list, its `pending` must NOT be
/// posted -- otherwise `adf/spec` (a required check on `main`) would
/// hang indefinitely. Other fan-out entries still post their pendings.
#[tokio::test]
async fn handle_review_pr_spec_validator_skipped_does_not_post_pending() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_spec_fanout("echo");
// Stamp a banned model on pr-spec-validator AFTER load-time
// validation so the runtime allow-list gate is the one that
// short-circuits the spawn. The other agents stay clean.
let svc = config
.agents
.iter_mut()
.find(|a| a.name == "pr-spec-validator")
.unwrap();
svc.model = Some("google/gemini-2".to_string());
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Wait for the two non-skipped POSTs, then a small grace window
// for any erroneous adf/spec POST to surface.
for _ in 0..150 {
if captured.calls.load(AOrdering::SeqCst) >= 2 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
tokio::time::sleep(Duration::from_millis(150)).await;
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
!contexts.iter().any(|c| c == "adf/spec"),
"skipped pr-spec-validator must NOT post adf/spec pending; got: {contexts:?}"
);
assert!(
!orch.active_agents.contains_key("pr-spec-validator"),
"pr-spec-validator must not be in active_agents when subscription gate rejects"
);
// Sanity: the other two agents still spawned + posted.
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"pr-reviewer must still post its pending; got: {contexts:?}"
);
assert!(
contexts.iter().any(|c| c == "adf/build"),
"build-runner must still post its pending; got: {contexts:?}"
);
}
#[test]
fn test_learning_config_default_disabled() {
let cfg = config::LearningConfig::default();
assert!(!cfg.enabled);
assert_eq!(cfg.min_trust, "L1");
assert_eq!(cfg.max_tokens, 1500);
assert_eq!(cfg.max_entries, 10);
assert_eq!(cfg.archive_days, 30);
assert_eq!(cfg.consolidation_ticks, 100);
}
#[test]
fn test_render_lessons_section_empty_store() {
let config = test_config();
let orch = AgentOrchestrator::new(config).unwrap();
let (section, ids) = orch.render_lessons_section("sentinel");
assert!(section.is_empty());
assert!(ids.is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn test_render_lessons_section_with_learnings() {
let config = test_config();
let mut orch = AgentOrchestrator::new(config).unwrap();
let persistence = learning::InMemoryLearningPersistence::new();
let store =
learning::SharedLearningStore::new(Box::new(persistence), learning::TrustLevel::L0);
store
.insert(learning::NewLearning {
source_agent: "other-agent".to_string(),
category: learning::LearningCategory::Tip,
summary: "Always run clippy before committing".to_string(),
details: Some("Prevents CI failures from lint warnings".to_string()),
applicable_agents: vec![],
verify_pattern: None,
})
.await
.unwrap();
orch.learning_store = Some(store);
let (section, ids) = orch.render_lessons_section("sentinel");
assert!(!section.is_empty(), "expected non-empty section, got empty");
assert!(section.contains("Prior Lessons"));
assert!(section.contains("Always run clippy before committing"));
assert_eq!(ids.len(), 1);
}
/// Phase 2e helper (Refs #954): extend `review_pr_config_with_fanout`
/// with a third project-scoped `pr-test-guardian` agent and a
/// three-entry `[pr_dispatch]` block (build-runner, pr-reviewer,
/// pr-test-guardian). Distinct name from Phase 2b's `…_with_spec_fanout`
/// and Phase 2c's `…_with_security_fanout` helpers so all three Phase 2
/// branches can coexist on the same `review_pr_config_with_fanout`
/// baseline once they merge.
fn review_pr_config_with_test_fanout(cli_tool: &str) -> (OrchestratorConfig, TempDir) {
let (mut config, tmp) = review_pr_config_with_fanout(cli_tool);
config.agents.push(AgentDefinition {
name: "pr-test-guardian".to_string(),
layer: AgentLayer::Growth,
cli_tool: cli_tool.to_string(),
task: "test".to_string(),
model: None,
schedule: None,
capabilities: vec!["review".to_string(), "test".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec!["testing".to_string()],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: Some("alpha".to_string()),
});
// The per-project block takes precedence over the top-level block,
// so we must update both to keep them in sync.
config
.pr_dispatch_per_project
.get_mut("alpha")
.unwrap()
.agents_on_pr_open
.push(crate::config::PrDispatchEntry {
name: "pr-test-guardian".to_string(),
context: "adf/test".to_string(),
});
config.pr_dispatch = Some(crate::config::PrDispatchConfig {
agents_on_pr_open: vec![
crate::config::PrDispatchEntry {
name: "build-runner".to_string(),
context: "adf/build".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-reviewer".to_string(),
context: "adf/pr-reviewer".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-test-guardian".to_string(),
context: "adf/test".to_string(),
},
],
});
(config, tmp)
}
/// ADF Phase 2e (Refs #954): a `pull_request.opened` event with
/// `pr-test-guardian` in `agents_on_pr_open` must spawn the agent.
/// Verifies the existing fan-out loop's generic `_` arm (which routes
/// any non-`build-runner` entry through `dispatch_pr_reviewer_for_pr`
/// by name) handles the new `adf/test` context cleanly without any
/// production code change.
#[tokio::test]
async fn handle_review_pr_spawns_pr_test_guardian_when_configured() {
let (config, _tmp) = review_pr_config_with_test_fanout("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
orch.active_agents.contains_key("pr-test-guardian"),
"pr-test-guardian must be spawned; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
// Test guardian is a PR-event agent, so it must receive the
// `ADF_PR_*` env (not `ADF_PUSH_*`). Verified via session_id
// scoping; the env wiring itself is exercised by the existing
// `reviewpr_dispatch_sets_env_vars` test through the same dispatch
// helper.
let managed = orch.active_agents.get("pr-test-guardian").unwrap();
assert!(
managed.session_id.starts_with("pr-test-guardian-"),
"session id should be scoped to the agent, got: {}",
managed.session_id
);
}
/// ADF Phase 2e (Refs #954): when a workflow tracker is configured,
/// `pr-test-guardian`'s spawn must POST a `pending` commit status with
/// context `adf/test` against the PR head SHA. Three fan-out agents are
/// configured, so three pending statuses are expected.
#[tokio::test]
async fn handle_review_pr_pending_status_posted_for_test_context() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
states: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
if let Some(st) = parsed.get("state").and_then(|v| v.as_str()) {
captured.states.lock().unwrap().push(st.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_test_fanout("echo");
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Expect three POSTs (one per fan-out agent).
for _ in 0..150 {
if captured.calls.load(AOrdering::SeqCst) >= 3 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/test"),
"adf/test pending status missing; got: {contexts:?}"
);
let states = captured.states.lock().unwrap().clone();
assert!(
states.iter().all(|s| s == "pending"),
"all initial statuses must be pending; got: {states:?}"
);
}
/// ADF Phase 2e (Refs #954): when `pr-test-guardian` is gated out by
/// the runtime subscription allow-list, its `pending` must NOT be
/// posted -- otherwise `adf/test` (a required check on `main`) would
/// hang indefinitely. Other fan-out entries still post their pendings.
#[tokio::test]
async fn handle_review_pr_test_guardian_skipped_does_not_post_pending() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_test_fanout("echo");
// Stamp a banned model on pr-test-guardian AFTER load-time
// validation so the runtime allow-list gate is the one that
// short-circuits the spawn. The other agents stay clean.
let tg = config
.agents
.iter_mut()
.find(|a| a.name == "pr-test-guardian")
.unwrap();
tg.model = Some("google/gemini-2".to_string());
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Wait for the two non-skipped POSTs, then a small grace window
// for any erroneous adf/test POST to surface.
for _ in 0..150 {
if captured.calls.load(AOrdering::SeqCst) >= 2 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
tokio::time::sleep(Duration::from_millis(150)).await;
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
!contexts.iter().any(|c| c == "adf/test"),
"skipped pr-test-guardian must NOT post adf/test pending; got: {contexts:?}"
);
assert!(
!orch.active_agents.contains_key("pr-test-guardian"),
"pr-test-guardian must not be in active_agents when subscription gate rejects"
);
// Sanity: the other two agents still spawned + posted.
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"pr-reviewer must still post its pending; got: {contexts:?}"
);
assert!(
contexts.iter().any(|c| c == "adf/build"),
"build-runner must still post its pending; got: {contexts:?}"
);
}
/// ADF Phase 2d (issue #955): helper that wires `pr-compliance-watchdog`
/// alongside the existing `pr-reviewer` agent and a `[pr_dispatch]` block
/// listing both agents on PR open. Standalone -- does not reuse the
/// Phase 2 `review_pr_config_with_fanout` helper -- so the assertion
/// surface stays tight (exactly two pending POSTs: `adf/pr-reviewer`
/// and `adf/compliance`).
fn review_pr_config_with_compliance_fanout(cli_tool: &str) -> (OrchestratorConfig, TempDir) {
let (mut config, tmp) = review_pr_config(cli_tool);
config.agents.push(AgentDefinition {
name: "pr-compliance-watchdog".to_string(),
layer: AgentLayer::Growth,
cli_tool: cli_tool.to_string(),
task: "compliance".to_string(),
model: None,
schedule: None,
capabilities: vec!["compliance".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec!["responsible-ai".to_string()],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: Some("alpha".to_string()),
});
config.pr_dispatch = Some(crate::config::PrDispatchConfig {
agents_on_pr_open: vec![
crate::config::PrDispatchEntry {
name: "pr-reviewer".to_string(),
context: "adf/pr-reviewer".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-compliance-watchdog".to_string(),
context: "adf/compliance".to_string(),
},
],
});
(config, tmp)
}
/// ADF Phase 2d (issue #955): when `pr-compliance-watchdog` is listed in
/// `agents_on_pr_open`, the generic `_` arm in `handle_review_pr` must
/// route through `dispatch_pr_reviewer_for_pr` and spawn the agent. No
/// new Rust dispatch code is needed -- this test asserts that property.
#[tokio::test]
async fn handle_review_pr_spawns_pr_compliance_watchdog_when_configured() {
let (config, _tmp) = review_pr_config_with_compliance_fanout("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
orch.active_agents.contains_key("pr-reviewer"),
"pr-reviewer must spawn alongside the new compliance agent; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
assert!(
orch.active_agents.contains_key("pr-compliance-watchdog"),
"pr-compliance-watchdog must be spawned by the generic fan-out arm; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
}
/// ADF Phase 2d: with the workflow tracker pointed at a loopback Gitea,
/// each fan-out agent that successfully spawns must POST exactly one
/// `pending` commit status. The compliance agent must use the
/// `adf/compliance` context (a hung pending under any other context
/// would block the PR forever once branch protection requires it).
#[tokio::test]
async fn handle_review_pr_pending_status_posted_for_compliance_context() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
states: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
if let Some(st) = parsed.get("state").and_then(|v| v.as_str()) {
captured.states.lock().unwrap().push(st.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_compliance_fanout("echo");
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
for _ in 0..100 {
if captured.calls.load(AOrdering::SeqCst) >= 2 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(
captured.calls.load(AOrdering::SeqCst),
2,
"exactly two pending status posts expected (pr-reviewer + compliance)"
);
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"adf/pr-reviewer pending status missing; got: {contexts:?}"
);
assert!(
contexts.iter().any(|c| c == "adf/compliance"),
"adf/compliance pending status missing; got: {contexts:?}"
);
let states = captured.states.lock().unwrap().clone();
assert!(
states.iter().all(|s| s == "pending"),
"all initial statuses must be pending; got: {states:?}"
);
}
/// ADF Phase 2d: when the compliance agent is gated out by the C1/C3
/// subscription allow-list (banned static model stamped post-validation),
/// the orchestrator must NOT post an `adf/compliance` pending status. A
/// hung pending under a required context would block the PR forever.
/// `pr-reviewer` (the un-gated peer) still spawns and posts its own
/// pending. Note: this test exercises the orchestrator-layer skip; the
/// TOML-level path-filter skip-with-success is a separate, shell-only
/// behaviour and is not asserted here.
#[tokio::test]
async fn handle_review_pr_compliance_watchdog_skipped_does_not_post_pending() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_compliance_fanout("echo");
// Stamp a banned static model on pr-compliance-watchdog AFTER load-time
// validation so the runtime subscription allow-list gate is the path
// that rejects the spawn.
let watchdog = config
.agents
.iter_mut()
.find(|a| a.name == "pr-compliance-watchdog")
.unwrap();
watchdog.model = Some("google/gemini-2".to_string());
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
for _ in 0..100 {
if captured.calls.load(AOrdering::SeqCst) >= 1 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
// Grace window so an erroneous adf/compliance POST has time to surface.
tokio::time::sleep(Duration::from_millis(100)).await;
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"pr-reviewer must still post its pending status; got: {contexts:?}"
);
assert!(
!contexts.iter().any(|c| c == "adf/compliance"),
"skipped pr-compliance-watchdog must NOT post adf/compliance pending; got: {contexts:?}"
);
assert!(
!orch.active_agents.contains_key("pr-compliance-watchdog"),
"pr-compliance-watchdog must not be in active_agents when subscription gate rejects"
);
}
/// Phase 2c helper: extend `review_pr_config_with_fanout` with a third
/// project-scoped `pr-security-sentinel` agent and a three-entry
/// `[pr_dispatch]` block (build-runner, pr-reviewer, pr-security-sentinel).
///
/// Distinct name from Phase 2b's `review_pr_config_with_spec_fanout`
/// helper (lives on the unmerged `task/950-pr-spec-validator-phase-2b`
/// branch -- see PR #952). Once Phase 2b lands the two helpers will
/// coexist; both build on the same `review_pr_config_with_fanout`
/// baseline.
fn review_pr_config_with_security_fanout(cli_tool: &str) -> (OrchestratorConfig, TempDir) {
let (mut config, tmp) = review_pr_config_with_fanout(cli_tool);
config.agents.push(AgentDefinition {
name: "pr-security-sentinel".to_string(),
layer: AgentLayer::Safety,
cli_tool: cli_tool.to_string(),
task: "security".to_string(),
model: None,
schedule: None,
capabilities: vec!["review".to_string(), "security".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec!["security-audit".to_string()],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: false,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: Some("alpha".to_string()),
});
// The per-project block takes precedence over the top-level block,
// so we must update both to keep them in sync.
config
.pr_dispatch_per_project
.get_mut("alpha")
.unwrap()
.agents_on_pr_open
.push(crate::config::PrDispatchEntry {
name: "pr-security-sentinel".to_string(),
context: "adf/security".to_string(),
});
config.pr_dispatch = Some(crate::config::PrDispatchConfig {
agents_on_pr_open: vec![
crate::config::PrDispatchEntry {
name: "build-runner".to_string(),
context: "adf/build".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-reviewer".to_string(),
context: "adf/pr-reviewer".to_string(),
},
crate::config::PrDispatchEntry {
name: "pr-security-sentinel".to_string(),
context: "adf/security".to_string(),
},
],
});
(config, tmp)
}
/// ADF Phase 2c (Refs #953): a `pull_request.opened` event with
/// `pr-security-sentinel` in `agents_on_pr_open` must spawn the agent.
/// Verifies the existing fan-out loop's generic `_` arm (which routes
/// any non-`build-runner` entry through `dispatch_pr_reviewer_for_pr`
/// by name) handles the new `adf/security` context cleanly without
/// any production code change.
#[tokio::test]
async fn handle_review_pr_spawns_pr_security_sentinel_when_configured() {
let (config, _tmp) = review_pr_config_with_security_fanout("echo");
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
assert!(
orch.active_agents.contains_key("pr-security-sentinel"),
"pr-security-sentinel must be spawned; active_agents: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
// Security sentinel is a PR-event agent, so it must receive the
// `ADF_PR_*` env (not `ADF_PUSH_*`). Verified via session_id
// scoping; the env wiring itself is exercised by the existing
// `reviewpr_dispatch_sets_env_vars` test through the same
// dispatch helper.
let managed = orch.active_agents.get("pr-security-sentinel").unwrap();
assert!(
managed.session_id.starts_with("pr-security-sentinel-"),
"session id should be scoped to the agent, got: {}",
managed.session_id
);
}
/// ADF Phase 2c (Refs #953): when a workflow tracker is configured,
/// `pr-security-sentinel`'s spawn must POST a `pending` commit status
/// with context `adf/security` against the PR head SHA.
#[tokio::test]
async fn handle_review_pr_pending_status_posted_for_security_context() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
states: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
if let Some(st) = parsed.get("state").and_then(|v| v.as_str()) {
captured.states.lock().unwrap().push(st.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_security_fanout("echo");
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Expect three POSTs (one per fan-out agent).
for _ in 0..150 {
if captured.calls.load(AOrdering::SeqCst) >= 3 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
contexts.iter().any(|c| c == "adf/security"),
"adf/security pending status missing; got: {contexts:?}"
);
let states = captured.states.lock().unwrap().clone();
assert!(
states.iter().all(|s| s == "pending"),
"all initial statuses must be pending; got: {states:?}"
);
}
/// ADF Phase 2c (Refs #953): when `pr-security-sentinel` is gated out
/// by the runtime subscription allow-list, its `pending` must NOT be
/// posted -- otherwise `adf/security` (a required check on `main`
/// post-deploy) would hang indefinitely. Other fan-out entries still
/// post their pendings.
#[tokio::test]
async fn handle_review_pr_security_sentinel_skipped_does_not_post_pending() {
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::post,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
use std::sync::Arc;
use tokio::net::TcpListener;
#[derive(Default)]
struct Captured {
calls: AtomicUsize,
contexts: std::sync::Mutex<Vec<String>>,
}
async fn capture(
Path((_owner, _repo, _sha)): Path<(String, String, String)>,
State(captured): State<Arc<Captured>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
captured.calls.fetch_add(1, AOrdering::SeqCst);
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) {
if let Some(ctx) = parsed.get("context").and_then(|v| v.as_str()) {
captured.contexts.lock().unwrap().push(ctx.to_string());
}
}
StatusCode::CREATED
}
let captured = Arc::new(Captured::default());
let app = Router::new()
.route("/api/v1/repos/{owner}/{repo}/statuses/{sha}", post(capture))
.with_state(captured.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
let base_url = format!("http://{}", addr);
let (mut config, _tmp) = review_pr_config_with_security_fanout("echo");
// Stamp a banned model on pr-security-sentinel AFTER load-time
// validation so the runtime allow-list gate is the one that
// short-circuits the spawn. The other agents stay clean.
let svc = config
.agents
.iter_mut()
.find(|a| a.name == "pr-security-sentinel")
.unwrap();
svc.model = Some("google/gemini-2".to_string());
config.workflow = Some(crate::config::WorkflowConfig {
enabled: true,
poll_interval_secs: 60,
workflow_file: std::path::PathBuf::from("/tmp/workflow.md"),
tracker: crate::config::TrackerConfig {
kind: "gitea".to_string(),
endpoint: base_url.clone(),
api_key: "test-token".to_string(),
owner: "fakeowner".to_string(),
repo: "fakerepo".to_string(),
project_slug: None,
use_robot_api: false,
states: crate::config::TrackerStates::default(),
},
concurrency: crate::config::ConcurrencyConfig::default(),
});
let mut orch = AgentOrchestrator::new(config).unwrap();
orch.handle_review_pr(review_pr_task()).await.unwrap();
// Wait for the two non-skipped POSTs, then a small grace window
// for any erroneous adf/security POST to surface.
for _ in 0..150 {
if captured.calls.load(AOrdering::SeqCst) >= 2 {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
tokio::time::sleep(Duration::from_millis(150)).await;
let contexts = captured.contexts.lock().unwrap().clone();
assert!(
!contexts.iter().any(|c| c == "adf/security"),
"skipped pr-security-sentinel must NOT post adf/security pending; got: {contexts:?}"
);
assert!(
!orch.active_agents.contains_key("pr-security-sentinel"),
"pr-security-sentinel must not be in active_agents when subscription gate rejects"
);
// Sanity: the other two agents still spawned + posted.
assert!(
contexts.iter().any(|c| c == "adf/pr-reviewer"),
"pr-reviewer must still post its pending; got: {contexts:?}"
);
assert!(
contexts.iter().any(|c| c == "adf/build"),
"build-runner must still post its pending; got: {contexts:?}"
);
}
/// T3: SpawnAgent dispatch must reject when the resolved agent is event_only.
/// No agent should be added to active_agents and no spawn attempted.
#[tokio::test]
async fn test_handle_webhook_dispatch_rejects_event_only_agent() {
let mut config = test_config();
// Replace the test fixture agents with a single event_only agent.
config.agents = vec![AgentDefinition {
name: "build-runner".to_string(),
layer: AgentLayer::Growth,
cli_tool: "/bin/bash".to_string(),
task: "echo would-build".to_string(),
schedule: None,
model: None,
capabilities: vec!["build".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: true,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
// mentions config required so handle_webhook_dispatch does not bail at the top.
config.mentions = Some(crate::config::MentionConfig::default());
let mut orch = AgentOrchestrator::new(config).unwrap();
let dispatch = webhook::WebhookDispatch::SpawnAgent {
agent_name: "build-runner".to_string(),
detected_project: None,
issue_number: 9999,
comment_id: 99999,
context: "@adf:build-runner please run".to_string(),
};
orch.handle_webhook_dispatch(dispatch).await;
assert!(
orch.active_agents.is_empty(),
"event_only agent must not be added to active_agents on mention dispatch; got: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
}
/// T4: SpawnPersona dispatch must reject when the resolved agent is event_only.
/// Uses resolve_persona_mention's "direct agent name match" branch by passing
/// the agent name as the persona name -- the resolver returns the agent, and our
/// gate must reject before spawn.
#[tokio::test]
async fn test_handle_webhook_dispatch_rejects_event_only_persona() {
let mut config = test_config();
config.agents = vec![AgentDefinition {
name: "build-runner".to_string(),
layer: AgentLayer::Growth,
cli_tool: "/bin/bash".to_string(),
task: "echo would-build".to_string(),
schedule: None,
model: None,
capabilities: vec!["build".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: None,
event_only: true,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
}];
config.mentions = Some(crate::config::MentionConfig::default());
let mut orch = AgentOrchestrator::new(config).unwrap();
let dispatch = webhook::WebhookDispatch::SpawnPersona {
persona_name: "build-runner".to_string(),
issue_number: 9999,
comment_id: 99999,
context: "@adf:build-runner please run via persona".to_string(),
};
orch.handle_webhook_dispatch(dispatch).await;
assert!(
orch.active_agents.is_empty(),
"event_only agent must not be added to active_agents on persona dispatch; got: {:?}",
orch.active_agents.keys().collect::<Vec<_>>()
);
}
/// T5: structural invariant for the post-exit defensive guard.
/// The guard at lib.rs's "Post output to Gitea if configured" block fires
/// `error!` and skips posting when an event-only agent reaches the hook with
/// gitea_issue set -- a "should never happen" path because the dispatch gate
/// in handle_webhook_dispatch should have already rejected the spawn.
/// Full runtime coverage would require integration infrastructure
/// (worktrees, real spawning, output capture) disproportionate to a single
/// boolean check. T3 and T4 cover the dispatch gate that prevents this
/// branch from being reached in production.
#[test]
fn test_post_exit_guard_invariant_event_only_with_gitea_issue() {
let def = AgentDefinition {
name: "build-runner".to_string(),
layer: AgentLayer::Growth,
cli_tool: "/bin/bash".to_string(),
task: "echo would-build".to_string(),
schedule: None,
model: None,
capabilities: vec!["build".to_string()],
max_memory_bytes: None,
budget_monthly_cents: None,
provider: None,
persona: None,
terraphim_role: None,
skill_chain: vec![],
sfia_skills: vec![],
fallback_provider: None,
fallback_model: None,
grace_period_secs: None,
max_cpu_seconds: None,
pre_check: None,
gitea_issue: Some(9999),
event_only: true,
evolution_enabled: false,
rlm_enabled: None,
bypass_kg_routing: false,
enabled: true,
project: None,
};
// The defensive guard reads exactly these two fields. Its branch fires
// when both are set on the same definition.
assert!(
def.event_only,
"event_only must be true to trigger the guard"
);
assert!(
def.gitea_issue.is_some(),
"gitea_issue must be Some(_) for the post-exit code to enter the outer if-let"
);
}
}