terraphim_orchestrator 1.20.2

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
//! Unit tests for terraphim_orchestrator (relocated from lib.rs as part of the
//! Gitea #1910 god-file decomposition; behaviour unchanged).

use super::*;
use tempfile::TempDir;

fn legacy_key(name: &str) -> (String, String) {
    (
        crate::dispatcher::LEGACY_PROJECT_ID.to_string(),
        name.to_string(),
    )
}

/// Build an `active_agents` key for a project-scoped test agent.
fn project_key(project: &str, name: &str) -> (String, String) {
    (project.to_string(), name.to_string())
}

fn test_config() -> OrchestratorConfig {
    OrchestratorConfig {
        project_sources: Vec::new(),
        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 {
                extra_projects: Vec::new(),
                name: "sentinel".to_string(),
                layer: AgentLayer::Safety,
                cli_tool: "echo".to_string(),
                task: "safety watch".to_string(),
                model: None,
                default_tier: 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 {
                extra_projects: Vec::new(),
                name: "sync".to_string(),
                layer: AgentLayer::Core,
                cli_tool: "echo".to_string(),
                task: "sync upstream".to_string(),
                model: None,
                default_tier: 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,
        auto_merge: None,
        learning: config::LearningConfig::default(),
        evolution: config::EvolutionConfig::default(),
        pr_dispatch: None,
        pr_dispatch_per_project: Default::default(),
        direct_dispatch: None,
    }
}

#[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);
}

#[cfg(unix)]
#[tokio::test]
async fn test_direct_dispatch_config_starts_socket_listener() {
    use std::os::unix::fs::FileTypeExt;

    let temp = TempDir::new().unwrap();
    let socket_path = temp.path().join("direct-dispatch.sock");
    let mut config = test_config();
    config.agents.clear();
    config.direct_dispatch = Some(crate::config::DirectDispatchConfig {
        socket_path: socket_path.clone(),
    });

    let mut orch = AgentOrchestrator::new(config).unwrap();
    orch.shutdown();
    orch.run().await.unwrap();

    let mut socket_created = false;
    for _ in 0..50 {
        if std::fs::symlink_metadata(&socket_path)
            .map(|metadata| metadata.file_type().is_socket())
            .unwrap_or(false)
        {
            socket_created = true;
            break;
        }
        tokio::task::yield_now().await;
    }

    assert!(
        socket_created,
        "direct dispatch listener did not create socket at {}",
        socket_path.display()
    );
}

#[tokio::test]
async fn test_handle_direct_dispatch_spawns_agent_without_mentions() {
    let mut config = test_config();
    config.agents = vec![AgentDefinition {
        extra_projects: Vec::new(),
        name: "echo-agent".to_string(),
        layer: AgentLayer::Core,
        cli_tool: "echo".to_string(),
        task: "echo hello".to_string(),
        schedule: None,
        model: None,
        default_tier: None,
        capabilities: vec!["echo".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,
    }];
    config.mentions = None;

    let mut orch = AgentOrchestrator::new(config).unwrap();

    let dispatch = webhook::WebhookDispatch::SpawnAgent {
        agent_name: "echo-agent".to_string(),
        detected_project: None,
        issue_number: 0,
        comment_id: 0,
        context: "test context".to_string(),
        synthetic_event: None,
    };

    orch.handle_direct_dispatch(dispatch).await;

    assert!(
        orch.active_agents.contains_key(&legacy_key("echo-agent")),
        "direct dispatch must spawn agent even without mentions config; active_agents: {:?}",
        orch.active_agents.keys().collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_handle_direct_dispatch_rejects_disabled_agent() {
    let mut config = test_config();
    config.agents = vec![AgentDefinition {
        extra_projects: Vec::new(),
        name: "disabled-agent".to_string(),
        layer: AgentLayer::Core,
        cli_tool: "echo".to_string(),
        task: "echo hello".to_string(),
        schedule: None,
        model: None,
        default_tier: None,
        capabilities: vec!["echo".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: false,
        project: None,
    }];
    config.mentions = None;

    let mut orch = AgentOrchestrator::new(config).unwrap();

    let dispatch = webhook::WebhookDispatch::SpawnAgent {
        agent_name: "disabled-agent".to_string(),
        detected_project: None,
        issue_number: 0,
        comment_id: 0,
        context: String::new(),
        synthetic_event: None,
    };

    orch.handle_direct_dispatch(dispatch).await;

    assert!(
        !orch
            .active_agents
            .contains_key(&legacy_key("disabled-agent")),
        "direct dispatch must not spawn disabled agent; active_agents: {:?}",
        orch.active_agents.keys().collect::<Vec<_>>()
    );
}

#[tokio::test]
#[ignore = "flaky: depends on live git repo state which may be shallow clone in CI/rch"]
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 {
        project_sources: Vec::new(),
        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 {
            extra_projects: Vec::new(),
            name: "echo-safety".to_string(),
            layer: AgentLayer::Safety,
            cli_tool: "echo".to_string(),
            task: "safety watch".to_string(),
            model: None,
            default_tier: 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,
        auto_merge: None,
        learning: config::LearningConfig::default(),
        evolution: config::EvolutionConfig::default(),
        pr_dispatch: None,
        pr_dispatch_per_project: Default::default(),
        direct_dispatch: None,
    }
}

#[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(&legacy_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(&legacy_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(&legacy_key("echo-safety")));

    // Restart pending (cooldown is 0, so immediate)
    orch.restart_pending_safety_agents().await;
    assert!(
        orch.active_agents.contains_key(&legacy_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 {
        extra_projects: Vec::new(),
        name: "echo-core".to_string(),
        layer: AgentLayer::Core,
        cli_tool: "echo".to_string(),
        task: "core task".to_string(),
        model: None,
        default_tier: 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(&legacy_key("echo-core")));

    // Restart pending should NOT restart a Core agent
    orch.restart_pending_safety_agents().await;
    assert!(
        !orch.active_agents.contains_key(&legacy_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(&legacy_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(&legacy_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(&legacy_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(&legacy_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 {
        extra_projects: Vec::new(),
        name: "persona-agent".to_string(),
        layer: AgentLayer::Safety,
        cli_tool: "cat".to_string(),
        task: "test task".to_string(),
        model: None,
        default_tier: 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(&legacy_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(&legacy_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 {
        extra_projects: Vec::new(),
        name: "unknown-persona-agent".to_string(),
        layer: AgentLayer::Safety,
        cli_tool: "echo".to_string(),
        task: "test task".to_string(),
        model: None,
        default_tier: 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(&legacy_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 {
        extra_projects: Vec::new(),
        name: "timeout-test".to_string(),
        layer: AgentLayer::Core,
        cli_tool: "sleep".to_string(),
        task: "60".to_string(),
        model: None,
        default_tier: 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(&legacy_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(&legacy_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,
            loop_target: 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 {
        extra_projects: Vec::new(),
        name: "broke-agent".to_string(),
        layer: AgentLayer::Safety,
        cli_tool: "echo".to_string(),
        task: "should not run".to_string(),
        model: None,
        default_tier: 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(&legacy_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(&legacy_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 {
        project_sources: Vec::new(),
        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 {
            extra_projects: Vec::new(),
            name: "pr-reviewer".to_string(),
            layer: AgentLayer::Safety,
            cli_tool: cli_tool.to_string(),
            task: "review".to_string(),
            model: None,
            default_tier: 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,
        auto_merge: None,
        learning: config::LearningConfig::default(),
        evolution: config::EvolutionConfig::default(),
        pr_dispatch: None,
        pr_dispatch_per_project: Default::default(),
        direct_dispatch: None,
    };
    (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(&project_key("alpha", "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
    );
}

/// #2175 multi-repo: a verdict agent whose home project is "alpha" but which
/// is registered for "beta" via `extra_projects` must, when dispatched for a
/// PR on "beta", be re-pointed at "beta" -- registered under the beta agent
/// key with `definition.project == "beta"` so its working-dir, GITEA_OWNER/
/// REPO env, and terminal commit-status all resolve to the PR's repo.
#[tokio::test]
async fn reviewpr_dispatch_repoints_shared_agent_at_pr_project() {
    let (mut config, tmp) = review_pr_config("echo");
    // pr-reviewer's home stays "alpha"; also register it for "beta".
    config.agents[0].extra_projects = vec!["beta".to_string()];

    let beta_dir = tmp.path().join("beta");
    std::fs::create_dir_all(&beta_dir).unwrap();
    config.projects.push(crate::config::Project {
        id: "beta".to_string(),
        working_dir: beta_dir,
        schedule_offset_minutes: 0,
        gitea: Some(crate::config::GiteaOutputConfig {
            base_url: "https://git.example.com".to_string(),
            token: "t".to_string(),
            owner: "terraphim".to_string(),
            repo: "beta-repo".to_string(),
            agent_tokens_path: None,
        }),
        mentions: None,
        workflow: None,
        #[cfg(feature = "quickwit")]
        quickwit: None,
        max_concurrent_agents: None,
        max_concurrent_mention_agents: None,
    });

    let mut orch = AgentOrchestrator::new(config).unwrap();
    orch.handle_review_pr(dispatcher::DispatchTask::ReviewPr {
        pr_number: 7,
        project: "beta".to_string(),
        head_sha: "cafef00d".to_string(),
        author_login: "claude-code".to_string(),
        title: "docs: tweak".to_string(),
        diff_loc: 3,
    })
    .await
    .unwrap();

    let managed = orch
        .active_agents
        .get(&project_key("beta", "pr-reviewer"))
        .expect("verdict agent must be keyed under the PR project 'beta', not its home 'alpha'");
    assert_eq!(
        managed.definition.project.as_deref(),
        Some("beta"),
        "spawned definition must be re-pointed at the PR project so repo/env resolve to beta"
    );
    assert!(
        !orch
            .active_agents
            .contains_key(&project_key("alpha", "pr-reviewer")),
        "agent must not be registered under its home project 'alpha' for a beta PR"
    );
}

/// #2175: `gitea_owner_repo_for_project` returns the project's gitea
/// owner/repo, and `None` for an unknown project or one without gitea config
/// (so commit-status posting falls back to the global tracker repo).
#[test]
fn gitea_owner_repo_for_project_resolves_or_none() {
    let (mut config, _tmp) = review_pr_config("echo");
    config.projects.push(crate::config::Project {
        id: "beta".to_string(),
        working_dir: _tmp.path().to_path_buf(),
        schedule_offset_minutes: 0,
        gitea: Some(crate::config::GiteaOutputConfig {
            base_url: "https://git.example.com".to_string(),
            token: "t".to_string(),
            owner: "terraphim".to_string(),
            repo: "beta-repo".to_string(),
            agent_tokens_path: None,
        }),
        mentions: None,
        workflow: None,
        #[cfg(feature = "quickwit")]
        quickwit: None,
        max_concurrent_agents: None,
        max_concurrent_mention_agents: None,
    });
    assert_eq!(
        config.gitea_owner_repo_for_project("beta"),
        Some(("terraphim".to_string(), "beta-repo".to_string()))
    );
    // "alpha" has no gitea block -> None (falls back to global tracker).
    assert_eq!(config.gitea_owner_repo_for_project("alpha"), None);
    // unknown project -> None.
    assert_eq!(config.gitea_owner_repo_for_project("nope"), None);
}

/// 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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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 (mut config, _tmp) = review_pr_config("echo");
    // Bypass load-time validation by mutating the test config before
    // construction to simulate a stale/poisoned config entry reaching the
    // dispatcher.
    config.agents[0].model = Some("google/gemini-2".to_string());
    let mut orch = AgentOrchestrator::new(config).unwrap();

    orch.handle_review_pr(review_pr_task()).await.unwrap();

    assert!(
        !orch
            .active_agents
            .contains_key(&project_key("alpha", "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(&project_key("alpha", "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 {
        extra_projects: Vec::new(),
        name: "build-runner".to_string(),
        layer: AgentLayer::Growth,
        cli_tool: cli_tool.to_string(),
        task: "build".to_string(),
        model: None,
        default_tier: 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(),
                },
            ],
            ..Default::default()
        },
    );
    (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(&project_key("alpha", "pr-reviewer")),
        "pr-reviewer must be spawned; active_agents: {:?}",
        orch.active_agents.keys().collect::<Vec<_>>()
    );
    assert!(
        orch.active_agents
            .contains_key(&project_key("alpha", "build-runner")),
        "build-runner must be spawned; active_agents: {:?}",
        orch.active_agents.keys().collect::<Vec<_>>()
    );
}

/// Regression for Gitea #2075: in a polyrepo fleet two projects can each
/// own an agent called `build-runner`. When pushes/PRs land on both
/// projects, the second `build-runner` dispatch was previously dropped
/// because `active_agents` was keyed by the bare agent name, so the
/// per-project dedup check (`contains_key("build-runner")`) collided.
///
/// With `active_agents` keyed by `(project, name)` both build-runners must
/// be active simultaneously. We drive the real handler path
/// (`handle_review_pr`) once per project and assert both
/// `("alpha", "build-runner")` and `("beta", "build-runner")` are present.
#[tokio::test]
async fn handle_review_pr_build_runner_does_not_collide_across_projects() {
    // Start from the alpha fanout config, then register a second project
    // `beta` with its own `build-runner` agent and dispatch entry.
    let (mut config, _tmp) = review_pr_config_with_fanout("echo");

    // Clone the alpha build-runner definition into project beta.
    let mut beta_build_runner = config
        .agents
        .iter()
        .find(|a| a.name == "build-runner" && a.project.as_deref() == Some("alpha"))
        .expect("alpha build-runner must exist in fanout config")
        .clone();
    beta_build_runner.project = Some("beta".to_string());
    config.agents.push(beta_build_runner);

    // Register the beta project so the dispatch path resolves it.
    let beta_working_dir = config.working_dir.clone();
    config.projects.push(crate::config::Project {
        id: "beta".to_string(),
        working_dir: beta_working_dir,
        schedule_offset_minutes: 0,
        gitea: None,
        mentions: None,
        workflow: None,
        #[cfg(feature = "quickwit")]
        quickwit: None,
        max_concurrent_agents: None,
        max_concurrent_mention_agents: None,
    });

    // beta dispatches a build-runner on PR open, mirroring alpha.
    config.pr_dispatch_per_project.insert(
        "beta".to_string(),
        crate::config::PrDispatchConfig {
            agents_on_pr_open: vec![crate::config::PrDispatchEntry {
                name: "build-runner".to_string(),
                context: "adf/build".to_string(),
            }],
            ..Default::default()
        },
    );

    let mut orch = AgentOrchestrator::new(config).unwrap();

    // Dispatch the alpha PR first, then the beta PR via the same handler.
    orch.handle_review_pr(review_pr_task()).await.unwrap();
    orch.handle_review_pr(dispatcher::DispatchTask::ReviewPr {
        pr_number: 642,
        project: "beta".to_string(),
        head_sha: "feedface5678".to_string(),
        author_login: "claude-code".to_string(),
        title: "fix(beta): concurrent build".to_string(),
        diff_loc: 17,
    })
    .await
    .unwrap();

    // The collision fix: both per-project build-runners are active at once.
    assert!(
        orch.active_agents
            .contains_key(&project_key("alpha", "build-runner")),
        "alpha build-runner must be active; active_agents: {:?}",
        orch.active_agents.keys().collect::<Vec<_>>()
    );
    assert!(
        orch.active_agents
            .contains_key(&project_key("beta", "build-runner")),
        "beta build-runner must NOT be dropped as a concurrent-dispatch \
         duplicate; 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(),
            },
        ],
        ..Default::default()
    });
    let mut orch = AgentOrchestrator::new(config).unwrap();

    orch.handle_review_pr(review_pr_task()).await.unwrap();

    assert!(
        orch.active_agents
            .contains_key(&project_key("alpha", "pr-reviewer")),
        "pr-reviewer must still spawn even when build-runner is missing"
    );
    assert!(
        !orch
            .active_agents
            .contains_key(&project_key("alpha", "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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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)
            && 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(&project_key("alpha", "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 {
        extra_projects: Vec::new(),
        name: "pr-spec-validator".to_string(),
        layer: AgentLayer::Safety,
        cli_tool: cli_tool.to_string(),
        task: "spec".to_string(),
        model: None,
        default_tier: 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(),
            },
        ],
        ..Default::default()
    });
    (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(&project_key("alpha", "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(&project_key("alpha", "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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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)
            && 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(&project_key("alpha", "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 {
        extra_projects: Vec::new(),
        name: "pr-test-guardian".to_string(),
        layer: AgentLayer::Growth,
        cli_tool: cli_tool.to_string(),
        task: "test".to_string(),
        model: None,
        default_tier: 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(),
            },
        ],
        ..Default::default()
    });
    (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(&project_key("alpha", "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(&project_key("alpha", "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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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)
            && 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(&project_key("alpha", "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 {
        extra_projects: Vec::new(),
        name: "pr-compliance-watchdog".to_string(),
        layer: AgentLayer::Growth,
        cli_tool: cli_tool.to_string(),
        task: "compliance".to_string(),
        model: None,
        default_tier: 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(),
            },
        ],
        ..Default::default()
    });
    (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(&project_key("alpha", "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(&project_key("alpha", "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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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)
            && 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(&project_key("alpha", "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 {
        extra_projects: Vec::new(),
        name: "pr-security-sentinel".to_string(),
        layer: AgentLayer::Safety,
        cli_tool: cli_tool.to_string(),
        task: "security".to_string(),
        model: None,
        default_tier: 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(),
            },
        ],
        ..Default::default()
    });
    (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(&project_key("alpha", "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(&project_key("alpha", "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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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::{
        Router,
        extract::{Path, State},
        http::StatusCode,
        response::IntoResponse,
        routing::post,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
    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)
            && 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(&project_key("alpha", "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 {
        extra_projects: Vec::new(),
        name: "build-runner".to_string(),
        layer: AgentLayer::Growth,
        cli_tool: "/bin/bash".to_string(),
        task: "echo would-build".to_string(),
        schedule: None,
        model: None,
        default_tier: 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(),
        synthetic_event: None,
    };

    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 {
        extra_projects: Vec::new(),
        name: "build-runner".to_string(),
        layer: AgentLayer::Growth,
        cli_tool: "/bin/bash".to_string(),
        task: "echo would-build".to_string(),
        schedule: None,
        model: None,
        default_tier: 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 {
        extra_projects: Vec::new(),
        name: "build-runner".to_string(),
        layer: AgentLayer::Growth,
        cli_tool: "/bin/bash".to_string(),
        task: "echo would-build".to_string(),
        schedule: None,
        model: None,
        default_tier: 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"
    );
}

#[test]
fn test_spawn_ctx_working_dir_set_to_agent_working_dir() {
    use std::path::PathBuf;

    // Simulate what build_spawn_context_for_agent returns for a project-bound agent:
    // working_dir is set to the project root.
    let project_root = PathBuf::from("/tmp/project-root");
    let worktree_path = PathBuf::from("/tmp/project-root/.worktrees/agent-abc123");

    let mut spawn_ctx = SpawnContext::with_working_dir(project_root.clone()).with_env(
        "ADF_WORKING_DIR",
        project_root.to_string_lossy().into_owned(),
    );

    // Apply the fix (the two new lines from the proposed change).
    let agent_working_dir = worktree_path.clone();
    spawn_ctx.working_dir = Some(agent_working_dir.clone());
    spawn_ctx = spawn_ctx.with_env(
        "ADF_WORKING_DIR",
        agent_working_dir.to_string_lossy().into_owned(),
    );

    assert_eq!(
        spawn_ctx.working_dir.as_deref(),
        Some(worktree_path.as_path()),
        "spawn_ctx.working_dir must be the worktree path, not the project root"
    );
    assert_eq!(
        spawn_ctx
            .env_overrides
            .get("ADF_WORKING_DIR")
            .map(String::as_str),
        Some(worktree_path.to_string_lossy().as_ref()),
        "ADF_WORKING_DIR env var must reflect the worktree path"
    );
}

#[test]
fn test_requires_isolated_worktree_for_mutating_ai_agents() {
    let mut def = test_config_fast_lifecycle().agents[0].clone();

    def.cli_tool = "echo".to_string();
    assert!(!requires_isolated_worktree(&def, None));

    assert!(requires_isolated_worktree(
        &def,
        Some("kimi-for-coding/k2p6")
    ));

    def.cli_tool = "/home/alex/.local/bin/claude".to_string();
    assert!(requires_isolated_worktree(&def, None));
    assert!(!requires_isolated_worktree(&def, Some("claude-3-haiku")));
}

#[tokio::test]
async fn test_mutating_agent_fails_closed_when_worktree_creation_fails() {
    let temp_repo = TempDir::new().unwrap();
    let mut config = test_config_fast_lifecycle();
    config.working_dir = temp_repo.path().to_path_buf();
    config.agents[0].cli_tool = "claude".to_string();

    let mut orch = AgentOrchestrator::new(config).unwrap();
    let def = orch.config.agents[0].clone();
    let result = orch.spawn_agent(&def).await;

    assert!(matches!(
        result,
        Err(OrchestratorError::WorktreeCreationFailed { .. })
    ));
    assert!(
        !orch.active_agents.contains_key(&legacy_key("echo-safety")),
        "agent must not spawn in the shared checkout after worktree failure"
    );
}

/// Repo-local agents: the same agent name in two projects (e.g. a per-repo
/// `implementation-swarm`) must fire and dedup INDEPENDENTLY, since
/// `last_cron_fire` is now keyed by `(project, name)`. Suppressing one
/// project's worker must not suppress the other's.
#[tokio::test]
async fn cron_dedup_and_fire_are_per_project() {
    let tmp = TempDir::new().unwrap();
    let wd = tmp.path().display();
    let toml = format!(
        r#"
working_dir = "{wd}"
disk_usage_threshold = 100

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "{wd}"

[[projects]]
id = "alpha"
working_dir = "{wd}"

[[projects]]
id = "beta"
working_dir = "{wd}"

[[agents]]
name = "worker"
layer = "Core"
cli_tool = "echo"
task = "hi"
schedule = "0 * * * *"
project = "alpha"

[[agents]]
name = "worker"
layer = "Core"
cli_tool = "echo"
task = "hi"
schedule = "0 * * * *"
project = "beta"
"#
    );
    let config = OrchestratorConfig::from_toml(&toml).unwrap();
    let mut orch = AgentOrchestrator::new(config).unwrap();

    // Plant last_tick 2h ago so an occurrence of "0 * * * *" is due now.
    let now = chrono::Utc::now();
    orch.set_last_tick_time(now - chrono::Duration::hours(2));
    // Suppress ONLY alpha/worker via its per-project key.
    orch.set_last_cron_fire("alpha", "worker", now);

    orch.check_cron_schedules().await;

    assert!(
        orch.active_agents
            .contains_key(&project_key("beta", "worker")),
        "beta/worker should fire -- its (project,name) key was not suppressed"
    );
    assert!(
        !orch
            .active_agents
            .contains_key(&project_key("alpha", "worker")),
        "alpha/worker must stay suppressed by its own per-project last_cron_fire"
    );
}