greentic-runner-host 1.2.0

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

/// Bridges a `DwAgentGraph` flow node into the graph executor.
///
/// The concrete impl (constructed in the runner binary / pack loader, Task 8)
/// wraps [`greentic_aw_runtime::graph::GraphExecutor`]. The engine holds it as
/// a trait object so `engine.rs` stays free of AW-runtime construction details
/// — mirroring [`super::agent_node::AgentNodeHandler`].
#[async_trait::async_trait]
pub trait GraphNodeHandler: Send + Sync {
    /// Execute (or resume) a graph run for this session. `flow_input`
    /// expects `{"user_text": "..."}`; returns
    /// `{"reply", "trail", "terminated_by"}` — the same envelope as DwAgent.
    async fn execute(
        &self,
        tenant_id: &str,
        env_id: &str,
        graph_id: &str,
        session_id: &str,
        flow_input: &Value,
    ) -> Result<Value>;
}

// ---------------------------------------------------------------------------
// agentic-worker feature: full DwAgentGraph / GraphExecutor integration
// ---------------------------------------------------------------------------

#[cfg(feature = "agentic-worker")]
mod aw {
    use std::collections::HashMap;
    use std::str::FromStr;
    use std::sync::Arc;
    use std::time::Duration;

    use anyhow::Result;
    use greentic_aw_runtime::CachingGraphProvider;
    use greentic_aw_runtime::HttpGraphProvider;
    use greentic_aw_runtime::ToolLedger;
    use greentic_aw_runtime::config_provider::InMemoryConfigProvider;
    use greentic_aw_runtime::error::{AgentError, ConfigError};
    use greentic_aw_runtime::graph::{
        AgentTurnFn, AgentTurnRequest, AgentTurnResult, ApprovalFn, ApprovalOutcome,
        ApprovalRequest, BoxFut, CheckpointError, CheckpointStore, GraphConfig, GraphExecError,
        GraphExecutor, GraphRole, GraphRunState, RunStatus, SupervisorFn, SupervisorRequest,
        SupervisorResult, ToolCallRequest, ToolFn,
    };
    use greentic_aw_runtime::state::{AgentStateStore, ChatMessage, ConversationState};
    use greentic_aw_runtime::tools::dispatch_tool_call;
    use greentic_aw_runtime::{
        AgentConfig, AgentInput, AgentLimits, AgentOutput, AgentRuntime, LlmBackend,
        LlmProviderRef, StepObserver, Telemetry, TenantContext, TokenMeter, ToolRef,
    };
    use greentic_ext_runtime::ExtensionRuntime;
    use serde_json::{Value, json};

    use crate::runner::knowledge_index::IndexMount;
    use crate::trace::agent_audit::AgentAuditObserver;
    use crate::trace::audit_sink::AuditSink;

    use super::GraphNodeHandler;

    /// Build a [`greentic_types::TenantCtx`] for the agent-graph audit
    /// observer from the flow node's plain `tenant_id`/`env_id` strings.
    ///
    /// Mirrors `agent_node::tenant_ctx_for_audit` exactly (duplicated rather
    /// than shared: that helper is module-private to `agent_node`'s `aw`
    /// module). An id that fails the newtype's validation (should not happen
    /// once a graph node has been routed to a tenant) still yields a
    /// well-formed `TenantCtx` rather than panicking — the audit event is
    /// best-effort, never load-bearing.
    fn tenant_ctx_for_audit(tenant_id: &str, env_id: &str) -> greentic_types::TenantCtx {
        let env = greentic_types::EnvId::from_str(env_id)
            .unwrap_or_else(|_| greentic_types::EnvId::new("local").expect("local env id"));
        let tenant = greentic_types::TenantId::from_str(tenant_id)
            .unwrap_or_else(|_| greentic_types::TenantId::new("local").expect("local tenant id"));
        greentic_types::TenantCtx::new(env, tenant)
    }

    /// Fixed, user-safe reply returned when a graph run fails. The detailed
    /// error is logged but never surfaced to the flow output, so internal
    /// failure modes do not leak to end users. Mirrors
    /// [`super::super::agent_node`]'s `SANITISED_ERROR_REPLY`.
    const SANITISED_ERROR_REPLY: &str = "Something went wrong. Please try again.";

    /// Reply returned when the requested graph is not available (no such graph
    /// in the provider). User-safe; the missing-graph id is logged separately.
    const GRAPH_UNAVAILABLE_REPLY: &str =
        "This worker isn't available right now. Please try again later.";

    /// Resolution sentinel emitted by the agent's reply when it considers the
    /// issue fully resolved. Matched case-insensitively and stripped from the
    /// visible reply. Copied verbatim from the greentic-designer spike
    /// (`src/orchestrate/agent_graph/agent_turn.rs`).
    const RESOLVED_SENTINEL: &str = "[[RESOLVED]]";

    /// Upper bound on the number of fresh-run-id suffixes tried when a session's
    /// run id is already in a terminal state (see [`derive_run_id`]).
    const MAX_RUN_ID_SUFFIX: u32 = 100;

    /// Error returned by [`RuntimeGraphNodeHandler::derive_run_id`].
    ///
    /// Kept local to `runner-host`: `GraphExecError` (from `greentic-aw-runtime`)
    /// has no suffix-exhaustion variant and we should not pollute the upstream
    /// crate with a runner-host-specific concern.
    #[derive(Debug, thiserror::Error)]
    enum RunIdError {
        /// Checkpoint IO failed while scanning for a free slot.
        ///
        /// Note: `checkpoint.load` returns `CheckpointError` directly (not
        /// `GraphExecError`), so we convert both via their respective `From`
        /// impls. `GraphExecError::Checkpoint` wraps `CheckpointError` upstream;
        /// here we keep the original for a tighter error surface.
        #[error(transparent)]
        Checkpoint(#[from] CheckpointError),
        /// All `MAX_RUN_ID_SUFFIX` slots for this session are occupied (terminal).
        /// Distinct from `GraphExecError::IterationCap` (graph visit limit) so
        /// the caller can surface a targeted user reply.
        #[error("all run-id slots exhausted for base run `{base_run_id}`")]
        SuffixExhausted { base_run_id: String },
    }

    /// `true` when `reply` contains the resolution sentinel (case-insensitive).
    fn detect_resolved(reply: &str) -> bool {
        reply
            .to_ascii_lowercase()
            .contains(&RESOLVED_SENTINEL.to_ascii_lowercase())
    }

    /// Strip the sentinel from `reply` (first case-insensitive occurrence) and
    /// trim surrounding whitespace so the user-visible text is clean.
    fn strip_sentinel(reply: &str) -> String {
        let lower = reply.to_ascii_lowercase();
        if let Some(idx) = lower.find(&RESOLVED_SENTINEL.to_ascii_lowercase()) {
            let mut out = reply.to_string();
            out.replace_range(idx..idx + RESOLVED_SENTINEL.len(), "");
            return out.trim().to_string();
        }
        reply.trim().to_string()
    }

    // -----------------------------------------------------------------------
    // GraphConfigSource
    // -----------------------------------------------------------------------

    /// Resolves a [`GraphConfig`] for a `(tenant, graph_id)` pair.
    ///
    /// Object-safe (returns [`BoxFut`]) so it can be held as
    /// `Arc<dyn GraphConfigSource>`. The pack loader (Task 8) fills the
    /// concrete implementation; tests use [`InMemoryGraphProvider`].
    pub trait GraphConfigSource: Send + Sync {
        fn graph_config<'a>(
            &'a self,
            tenant: &'a TenantContext,
            graph_id: &'a str,
        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>>;
    }

    /// [`GraphConfigSource`] backed by an in-memory `graph_id -> GraphConfig`
    /// map. Graphs are operator-global for the MVP: lookup is keyed purely by
    /// `graph_id`; the `tenant` argument is accepted (to satisfy the trait
    /// contract) but not used for keying. Reuses [`ConfigError::AgentNotFound`]
    /// as the crate's canonical "not found" variant.
    pub struct InMemoryGraphProvider {
        graphs: HashMap<String, GraphConfig>,
    }

    impl InMemoryGraphProvider {
        /// Wrap a `graph_id -> GraphConfig` map in a [`GraphConfigSource`].
        pub fn new(graphs: HashMap<String, GraphConfig>) -> Self {
            Self { graphs }
        }
    }

    impl GraphConfigSource for InMemoryGraphProvider {
        fn graph_config<'a>(
            &'a self,
            _tenant: &'a TenantContext,
            graph_id: &'a str,
        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
            let found = self.graphs.get(graph_id).cloned();
            let graph_id_owned = graph_id.to_string();
            Box::pin(async move { found.ok_or(ConfigError::AgentNotFound(graph_id_owned)) })
        }
    }

    // -----------------------------------------------------------------------
    // GraphConfigSource adapter for CachingGraphProvider<HttpGraphProvider>
    // -----------------------------------------------------------------------

    /// Adapts [`CachingGraphProvider<HttpGraphProvider>`] into the
    /// [`GraphConfigSource`] trait so it can be stored as an
    /// `Arc<dyn GraphConfigSource>` alongside [`InMemoryGraphProvider`].
    ///
    /// This is a 5-line adapter that bridges the inherent-method API of
    /// `CachingGraphProvider` (defined in `greentic-aw-runtime`) into the
    /// trait object used by `runner-host`.
    impl GraphConfigSource for CachingGraphProvider<HttpGraphProvider> {
        fn graph_config<'a>(
            &'a self,
            tenant: &'a TenantContext,
            graph_id: &'a str,
        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
            Box::pin(async move { self.graph_config(tenant, graph_id).await })
        }
    }

    // -----------------------------------------------------------------------
    // LayeredGraphProvider
    // -----------------------------------------------------------------------

    /// Tries the primary [`GraphConfigSource`], falling back to the secondary
    /// when the primary reports the graph missing or has an infrastructure
    /// failure. A `Misconfigured` error is propagated, never masked by the
    /// fallback — matching [`greentic_aw_runtime::LayeredConfigProvider`]'s
    /// semantics exactly.
    ///
    /// Fallback triggers:
    /// - `ConfigError::AgentNotFound` — graph absent from the primary (HTTP
    ///   registry doesn't know it yet; local pack may have it).
    /// - `ConfigError::Internal` — transient infrastructure failure (network
    ///   timeout, 5xx) — local pack can serve as a degraded fallback.
    ///
    /// Non-fallback (surfaces immediately):
    /// - `ConfigError::Misconfigured` — corrupt document or bad auth token;
    ///   the operator must fix the document — silently serving stale local
    ///   data would mask the problem.
    pub struct LayeredGraphProvider<P: GraphConfigSource, F: GraphConfigSource> {
        primary: P,
        fallback: F,
    }

    impl<P: GraphConfigSource, F: GraphConfigSource> LayeredGraphProvider<P, F> {
        pub fn new(primary: P, fallback: F) -> Self {
            Self { primary, fallback }
        }
    }

    impl<P: GraphConfigSource, F: GraphConfigSource> GraphConfigSource for LayeredGraphProvider<P, F> {
        fn graph_config<'a>(
            &'a self,
            tenant: &'a TenantContext,
            graph_id: &'a str,
        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
            Box::pin(async move {
                match self.primary.graph_config(tenant, graph_id).await {
                    Ok(cfg) => Ok(cfg),
                    Err(ConfigError::AgentNotFound(_)) | Err(ConfigError::Internal(_)) => {
                        self.fallback.graph_config(tenant, graph_id).await
                    }
                    // Misconfigured + any future ConfigError variant: surface,
                    // never mask. New variants fall through here and propagate
                    // by default; revisit only if a new variant should fall back.
                    Err(other) => Err(other),
                }
            })
        }
    }

    // -----------------------------------------------------------------------
    // Admin graph registry wiring
    // -----------------------------------------------------------------------

    /// Build a cached [`HttpGraphProvider`] from `GREENTIC_AW_ADMIN_ENDPOINT` +
    /// `GREENTIC_AW_ADMIN_TOKEN`. Returns `None` when either is unset/empty,
    /// so the runtime keeps using the local pack provider alone.
    ///
    /// Mirrors [`super::agent_node::registry_from_env`] exactly — same env
    /// vars, same "both must be present" semantics.
    fn graph_registry_from_env() -> Option<CachingGraphProvider<HttpGraphProvider>> {
        let endpoint = std::env::var("GREENTIC_AW_ADMIN_ENDPOINT")
            .ok()
            .filter(|s| !s.is_empty())?;
        let token = std::env::var("GREENTIC_AW_ADMIN_TOKEN")
            .ok()
            .filter(|s| !s.is_empty())?;
        Some(CachingGraphProvider::new(HttpGraphProvider::new(
            endpoint, token,
        )))
    }

    // -----------------------------------------------------------------------
    // Pack-sidecar graph loader
    // -----------------------------------------------------------------------

    /// Parse an `agent-graph.json` sidecar (raw bytes from a `.gtpack`) into a
    /// validated [`GraphConfig`].
    ///
    /// Mirrors the lenient posture of
    /// [`super::super::agent_node::agent_configs_from_manifest`]: every failure
    /// mode — invalid UTF-8, malformed JSON, schema-version mismatch, or graph
    /// validation error — is logged via [`tracing::warn!`] (with `pack_id`) and
    /// yields `None`, so a single bad graph never prevents the rest of the pack
    /// from loading. The `pack_id` argument is used only in log messages.
    pub fn graph_config_from_sidecar(pack_id: &str, bytes: &[u8]) -> Option<GraphConfig> {
        let raw = match std::str::from_utf8(bytes) {
            Ok(raw) => raw,
            Err(error) => {
                tracing::warn!(
                    pack_id,
                    error = %error,
                    "skipping agent-graph sidecar: not valid UTF-8"
                );
                return None;
            }
        };
        match GraphConfig::from_json(raw) {
            Ok(config) => Some(config),
            Err(error) => {
                tracing::warn!(
                    pack_id,
                    error = %error,
                    "skipping malformed agent-graph sidecar in pack"
                );
                None
            }
        }
    }

    // -----------------------------------------------------------------------
    // Production graph-handler construction
    // -----------------------------------------------------------------------

    /// Build the production `DwAgentGraph` handler if the environment is
    /// configured. Mirrors
    /// [`super::super::agent_node::build_agent_node_handler`]: it returns `None`
    /// (so `DwAgentGraph` flow dispatch errors clearly) under any of these
    /// graceful-degradation conditions:
    /// - `graphs` is empty (no graphs from any pack sidecar);
    /// - `GREENTIC_AW_REDIS_URL` is unset/empty;
    /// - the AW Redis connection fails;
    /// - the extension runtime fails to initialise.
    ///
    /// The shared runtime Arcs (state store, ext runtime, LLM backend,
    /// telemetry, token meter, ledger) are built exactly as for the single-agent
    /// path; the durable checkpoint store reuses the same multiplexed Redis
    /// connection manager.
    ///
    /// `tenant`, `secrets` and `unit` are the values the `dw.agent` handler of
    /// the same `TenantRuntime` receives (`unit` is the deployed unit's
    /// `bundle_id`, `None` on the legacy tenant-only path). They feed only the
    /// pack-carried A2A tool source ([`graph_a2a_source`]) and, `tenant` and
    /// `secrets` only, the Chronicle-index knowledge mount ([`IndexMount`]);
    /// the rest of this path keeps its env-only secrets, as before.
    ///
    /// Bills every turn through `agent_node::resolve_billing_meter(None)` (the
    /// env-configured sink, or none); see [`build_graph_node_handler_metered`].
    #[allow(clippy::too_many_arguments)]
    pub async fn build_graph_node_handler(
        graphs: HashMap<String, GraphConfig>,
        audit_sink: Option<AuditSink>,
        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
        merged_agents: HashMap<String, AgentConfig>,
        tenant: String,
        secrets: crate::secrets::DynSecretsManager,
        unit: Option<String>,
    ) -> Option<Arc<dyn GraphNodeHandler>> {
        build_graph_node_handler_metered(
            graphs,
            audit_sink,
            packs,
            merged_agents,
            tenant,
            secrets,
            unit,
            super::super::agent_node::resolve_billing_meter(None),
        )
        .await
    }

    /// [`build_graph_node_handler`] with the `TenantRuntime`'s already-resolved
    /// billing sink, shared with its `dw.agent` runtime. Every agent and
    /// supervisor turn bills through it, attributed to `unit` as `project_id`.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn build_graph_node_handler_metered(
        graphs: HashMap<String, GraphConfig>,
        audit_sink: Option<AuditSink>,
        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
        merged_agents: HashMap<String, AgentConfig>,
        tenant: String,
        secrets: crate::secrets::DynSecretsManager,
        unit: Option<String>,
        billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
    ) -> Option<Arc<dyn GraphNodeHandler>> {
        use crate::runner::aw_backends::{AwBackends, build_aw_backends};
        use greentic_aw_runtime::OtelTelemetry;

        if graphs.is_empty() {
            return None; // nothing to serve
        }

        let AwBackends {
            state_store,
            token_meter,
            tool_ledger: ledger,
            checkpoint_store: checkpoint,
        } = build_aw_backends().await?;

        // Process-level graph serve path has no per-tenant secrets context;
        // tool secrets resolve from the env only. It likewise has no embedding
        // host, so the ext LLM port falls back to the env-keyed `EnvLlmPort`.
        let ext_runtime = super::super::agent_node::build_ext_runtime(
            std::sync::Arc::new(super::super::agent_node::EnvSecretsBackend),
            None,
            None,
            &packs,
        )?;
        let llm = super::super::agent_node::build_llm_backend(&ext_runtime);
        let telemetry = Arc::new(OtelTelemetry);

        let graph_count = graphs.len();
        // Build the graph config source: HTTP registry (cached) primary →
        // InMemoryGraphProvider (local packs) fallback, when the admin env
        // vars are configured; otherwise local packs only.
        //
        // Mirrors the agent-config composition in
        // `agent_node::build_agent_node_handler`:
        //   Some(http) → CachingConfigProvider(Layered(http, overlay))
        //   None       → CachingConfigProvider(overlay)
        //
        // The graph path skips the ManifestToolOverlay (no manifest overlay
        // exists for graphs) and the CachingGraphProvider is already embedded
        // inside the `CachingGraphProvider<HttpGraphProvider>` returned by
        // `graph_registry_from_env`. The local InMemoryGraphProvider needs no
        // separate cache (it is in-memory and O(1)).
        let local = InMemoryGraphProvider::new(graphs);
        let provider: Arc<dyn GraphConfigSource> = match graph_registry_from_env() {
            Some(http) => Arc::new(LayeredGraphProvider::new(http, local)),
            None => Arc::new(local),
        };

        let a2a_source = graph_a2a_source(&packs, &tenant, &secrets, unit.as_deref());
        // Chronicle-index retrieval for `agent_ref` turns. Captured here, with
        // the runtime's own secrets tenant, so the mount does not depend on the
        // tenant each turn happens to run under.
        let index_mount = IndexMount {
            secrets: Some(super::super::agent_node::mcp_secrets_manager(&secrets)),
            secret_tenant: Some(tenant.clone()),
        };
        let handler = RuntimeGraphNodeHandler::from_parts(
            provider,
            checkpoint,
            state_store,
            ext_runtime,
            llm,
            telemetry,
            token_meter,
            ledger,
            audit_sink,
            packs,
            Arc::new(merged_agents),
            a2a_source,
            index_mount,
        )
        .with_billing(billing_meter, unit);

        tracing::info!(graph_count, "AW graph runtime constructed");
        Some(Arc::new(handler))
    }

    /// The pack-carried A2A tool source for a graph handler's agent turns and
    /// Tool nodes.
    ///
    /// Built from exactly the inputs the single-turn `dw.agent` runtime uses —
    /// the same packs, tenant and deployed unit, and the same remote-tool
    /// secrets manager (`agent_node::mcp_secrets_manager`, so an explicit
    /// `SECRETS_BACKEND` wins here too) — through the same helper, so
    /// `GREENTIC_AW_A2A=0`, first-pack-wins dedup and the credential URI
    /// (`secrets://default/<tenant>/<auth_team|_>/a2a/<agent_id>[.unit-<seg>]`)
    /// cannot differ between the two paths.
    ///
    /// Built once per handler, not per turn: the handler belongs to one
    /// `TenantRuntime`, so tenant, unit and packs are fixed for its lifetime,
    /// and rebuilding per turn would throw away the source's agent-card cache.
    pub(crate) fn graph_a2a_source(
        packs: &[Arc<crate::pack::PackRuntime>],
        tenant: &str,
        secrets: &crate::secrets::DynSecretsManager,
        unit: Option<&str>,
    ) -> Option<Arc<greentic_aw_runtime::A2aToolSource>> {
        crate::runner::a2a_pack_source::a2a_source_from_packs(
            packs,
            tenant,
            Some(super::super::agent_node::mcp_secrets_manager(secrets)),
            unit,
        )
    }

    // -----------------------------------------------------------------------
    // RuntimeGraphNodeHandler
    // -----------------------------------------------------------------------

    /// Supplies the per-visit [`AgentTurnFn`]/[`SupervisorFn`] closures used by
    /// [`RuntimeGraphNodeHandler::execute`].
    ///
    /// `execute` already receives the graph run's real `tenant_id`/`env_id`
    /// (see its signature), but [`AgentTurnFn`]/[`SupervisorFn`] (from
    /// `greentic-aw-runtime`, not modifiable here) only pass an
    /// [`AgentTurnRequest`]/[`SupervisorRequest`] at invocation time — neither
    /// carries a tenant. So the audit sink + real tenant cannot be baked into
    /// a closure built once at handler-construction time and reused
    /// call-after-call; instead `execute` asks this seam for a *fresh*
    /// closure on every call, passing the sink + the real tenant it just
    /// resolved from its own parameters (EPIC-B B-3b Task 1 plumbing; Task 2
    /// makes `run_one_agent_turn`/`run_one_supervisor_turn` actually build an
    /// `AgentAuditObserver` from them instead of ignoring them).
    ///
    /// [`RuntimeTurnSource`] (production) rebuilds via
    /// [`build_agent_turn`]/[`build_supervisor`] from the shared runtime Arcs
    /// every call. [`FixedTurnSource`] (test-only, via
    /// [`RuntimeGraphNodeHandler::with_effects`]) ignores the sink/tenant and
    /// hands back the same injected closures every time, preserving today's
    /// deterministic-effect test style untouched.
    trait TurnEffectSource: Send + Sync {
        fn agent_turn(
            &self,
            audit_sink: Option<AuditSink>,
            real_tenant: greentic_types::TenantCtx,
            billing: TurnBilling,
        ) -> AgentTurnFn;
        fn supervisor(
            &self,
            audit_sink: Option<AuditSink>,
            real_tenant: greentic_types::TenantCtx,
            billing: TurnBilling,
        ) -> SupervisorFn;
    }

    /// How a graph turn's LLM spend is billed: the `TenantRuntime`'s shared
    /// billing sink (`agent_node::resolve_billing_meter` — the host-installed
    /// per-unit meter, else the env-configured one, else none) and the deployed
    /// unit (`bundle_id`) the spend is attributed to as `project_id`.
    ///
    /// Before this existed every graph turn ran on the per-visit runtime's
    /// default `NoopBillingMeter` under a synthetic `("graph", "run")` tenant,
    /// so agent-graph workers emitted no usage at all.
    #[derive(Clone, Default)]
    pub(crate) struct TurnBilling {
        pub(crate) meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
        pub(crate) project_id: Option<String>,
    }

    impl TurnBilling {
        /// The [`TenantContext`] a graph turn runs (and bills) under: the REAL
        /// tenant/env the flow node was dispatched with, plus the unit.
        fn turn_tenant(&self, real_tenant: &greentic_types::TenantCtx) -> TenantContext {
            TenantContext::new(real_tenant.tenant_id.as_str(), real_tenant.env.as_str())
                .with_project_id(self.project_id.clone())
        }

        /// Install the shared sink on a per-visit runtime; no sink leaves the
        /// runtime's `NoopBillingMeter` in place.
        fn install(&self, runtime: AgentRuntime) -> AgentRuntime {
            match &self.meter {
                Some(meter) => runtime.with_billing_meter(Arc::clone(meter)),
                None => runtime,
            }
        }
    }

    /// Production [`TurnEffectSource`]: holds the constituent runtime Arcs
    /// (extension runtime, LLM backend, telemetry, token meter, ledger; the
    /// state store lives directly on [`RuntimeGraphNodeHandler`]) so it can
    /// build a lightweight [`AgentRuntime`] *per agent visit* with a fresh
    /// single-entry [`InMemoryConfigProvider`] — mirroring the
    /// greentic-designer spike's per-visit runtime construction.
    struct RuntimeTurnSource {
        state_store: Arc<dyn AgentStateStore>,
        ext_runtime: Arc<ExtensionRuntime>,
        llm: Arc<dyn LlmBackend>,
        telemetry: Arc<dyn Telemetry>,
        token_meter: Arc<dyn TokenMeter>,
        ledger: Arc<dyn ToolLedger>,
        /// MCP tool source, built ONCE (mirrors the other Arcs) so its 5-min
        /// TTL catalog cache + warmed HTTP client are reused across every
        /// graph-agent visit rather than rebuilt (empty-cache) per turn.
        mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
        /// Pack-carried A2A tool source ([`graph_a2a_source`]), built once for
        /// the same reason as `mcp_source`: its agent-card cache is reused
        /// across every graph-agent visit. The supervisor stays tool-free.
        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
        /// The tenant's loaded packs, used to build a fresh, tenant-scoped
        /// [`greentic_aw_runtime::ComponentToolSource`] on EVERY turn (unlike
        /// `mcp_source`, this is NOT built once — the component source is
        /// tenant-pinned, and building it per turn from the in-memory pack
        /// list is cheap; see [`run_one_agent_turn`]).
        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
        /// Process-level merged agent configs (pack + operator-overridden),
        /// threaded into [`run_one_agent_turn`] so a graph node's `agent_ref`
        /// resolves to that agent's full [`AgentConfig`] at turn time.
        merged_agents: Arc<HashMap<String, AgentConfig>>,
        /// Chronicle-index knowledge mount for `agent_ref` turns, carrying the
        /// real tenant's secrets (see [`build_graph_node_handler`]).
        index_mount: IndexMount,
    }

    impl TurnEffectSource for RuntimeTurnSource {
        fn agent_turn(
            &self,
            audit_sink: Option<AuditSink>,
            real_tenant: greentic_types::TenantCtx,
            billing: TurnBilling,
        ) -> AgentTurnFn {
            build_agent_turn(
                self.state_store.clone(),
                self.ext_runtime.clone(),
                self.llm.clone(),
                self.telemetry.clone(),
                self.token_meter.clone(),
                self.ledger.clone(),
                self.mcp_source.clone(),
                self.a2a_source.clone(),
                self.packs.clone(),
                self.merged_agents.clone(),
                self.index_mount.clone(),
                audit_sink,
                real_tenant,
                billing,
            )
        }

        fn supervisor(
            &self,
            audit_sink: Option<AuditSink>,
            real_tenant: greentic_types::TenantCtx,
            billing: TurnBilling,
        ) -> SupervisorFn {
            build_supervisor(
                self.state_store.clone(),
                self.ext_runtime.clone(),
                self.llm.clone(),
                self.telemetry.clone(),
                self.token_meter.clone(),
                self.ledger.clone(),
                self.merged_agents.clone(),
                audit_sink,
                real_tenant,
                billing,
            )
        }
    }

    /// **Test-only** [`TurnEffectSource`] that always returns the same
    /// injected closures, ignoring the audit sink/tenant. Lets
    /// [`RuntimeGraphNodeHandler::with_effects`] keep injecting deterministic
    /// effects without needing real `AgentRuntime` Arcs.
    #[cfg(test)]
    struct FixedTurnSource {
        agent_turn: AgentTurnFn,
        supervisor: SupervisorFn,
    }

    #[cfg(test)]
    impl TurnEffectSource for FixedTurnSource {
        fn agent_turn(
            &self,
            _audit_sink: Option<AuditSink>,
            _real_tenant: greentic_types::TenantCtx,
            _billing: TurnBilling,
        ) -> AgentTurnFn {
            self.agent_turn.clone()
        }

        fn supervisor(
            &self,
            _audit_sink: Option<AuditSink>,
            _real_tenant: greentic_types::TenantCtx,
            _billing: TurnBilling,
        ) -> SupervisorFn {
            self.supervisor.clone()
        }
    }

    /// Production [`GraphNodeHandler`] wrapping the durable graph executor.
    ///
    /// Tool dispatch goes through the shared [`ExtensionRuntime`] via
    /// [`dispatch_tool_call`], with `a2a:` refs routed to the handler's
    /// pack-carried A2A catalog.
    pub struct RuntimeGraphNodeHandler {
        graphs: Arc<dyn GraphConfigSource>,
        checkpoint: Arc<dyn CheckpointStore>,
        state_store: Arc<dyn AgentStateStore>,
        turn_source: Arc<dyn TurnEffectSource>,
        tool: ToolFn,
        approval: ApprovalFn,
        /// Best-effort agent-step audit sink (EPIC-B B-3b), threaded from
        /// [`build_graph_node_handler`]. `None` when no NATS audit client is
        /// configured (`GREENTIC_EVENTS_NATS_URL` unset/unreachable) — the
        /// `run_agent_step` seam then stays on the plain `.step()` path,
        /// byte-identical regardless of this field's value.
        audit_sink: Option<AuditSink>,
        /// Billing sink + unit for every agent and supervisor turn (see
        /// [`TurnBilling`]). Default: no sink, no unit — set by
        /// [`RuntimeGraphNodeHandler::with_billing`].
        billing: TurnBilling,
    }

    impl RuntimeGraphNodeHandler {
        /// Bill every agent and supervisor turn through `meter`, attributed to
        /// the deployed unit `project_id` (the revision's `bundle_id`). `None`
        /// keeps the per-visit runtimes on `NoopBillingMeter`.
        #[must_use]
        pub fn with_billing(
            mut self,
            meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
            project_id: Option<String>,
        ) -> Self {
            self.billing = TurnBilling { meter, project_id };
            self
        }

        /// Build a handler from the runtime's constituent parts.
        ///
        /// **Deviation from the Task-7 `from_runtime(runtime: Arc<AgentRuntime>, …)`
        /// signature:** `AgentRuntime`'s inner Arcs (`ext_runtime`, `llm`,
        /// `telemetry`, `token_meter`, `ledger`) are `pub(crate)` and cannot be
        /// extracted from an `Arc<AgentRuntime>` outside the `greentic-aw-runtime`
        /// crate, so a per-visit runtime cannot be reconstructed from a shared
        /// `AgentRuntime`. The task explicitly allows this: "an acceptable
        /// alternative is a `from_parts(...)` constructor taking those Arcs
        /// directly." The pack loader (Task 8) already holds these Arcs when it
        /// would otherwise build an `AgentRuntime`, so it wires them here instead.
        #[allow(clippy::too_many_arguments)]
        pub fn from_parts(
            graphs: Arc<dyn GraphConfigSource>,
            checkpoint: Arc<dyn CheckpointStore>,
            state_store: Arc<dyn AgentStateStore>,
            ext_runtime: Arc<ExtensionRuntime>,
            llm: Arc<dyn LlmBackend>,
            telemetry: Arc<dyn Telemetry>,
            token_meter: Arc<dyn TokenMeter>,
            ledger: Arc<dyn ToolLedger>,
            audit_sink: Option<AuditSink>,
            packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
            merged_agents: Arc<HashMap<String, AgentConfig>>,
            a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
            index_mount: IndexMount,
        ) -> Self {
            // The Tool node and the agent turns share one A2A source, so an
            // `a2a:` ref resolves identically whichever of the two dispatches it.
            let tool = build_tool(ext_runtime.clone(), a2a_source.clone());
            // Built once here (like the other Arcs) so the MCP catalog cache +
            // HTTP client are reused across every graph-agent turn.
            // No per-tenant secrets manager reachable in this constructor
            // (out of scope for this task — see `agent_node::mcp_source_from_env`'s
            // doc comment); matches this path's pre-existing behavior.
            let mcp_source = super::super::agent_node::mcp_source_from_env(None);
            let turn_source: Arc<dyn TurnEffectSource> = Arc::new(RuntimeTurnSource {
                state_store: state_store.clone(),
                ext_runtime,
                llm,
                telemetry,
                token_meter,
                ledger,
                mcp_source,
                a2a_source,
                packs,
                merged_agents,
                index_mount,
            });
            // NOTE: the real `ApprovalFn` is designer-provided (it wires the
            // `greentic.approval.request.v1` / `.response.v1` NATS round trip
            // so a human decision can arrive asynchronously). This in-process
            // runner-host path does not yet have that transport wired up, so
            // it always parks (`Awaiting`) — safe (a graph run simply stays
            // `AwaitingInput`, and `derive_run_id` resumes rather than forks
            // it on every later call for the same session) but not yet
            // resolvable from here. A future designer-side approval bridge
            // (subscriber + node) replaces this with a real consumer.
            let approval = default_approval_awaiting();
            Self {
                graphs,
                checkpoint,
                state_store,
                turn_source,
                tool,
                approval,
                audit_sink,
                billing: TurnBilling::default(),
            }
        }

        /// **Test-only** constructor that injects effect closures directly,
        /// bypassing per-visit [`AgentRuntime`] construction. Not available
        /// outside `#[cfg(test)]`; production code must use [`from_parts`].
        ///
        /// [`from_parts`]: RuntimeGraphNodeHandler::from_parts
        #[cfg(test)]
        #[allow(clippy::too_many_arguments)]
        pub(crate) fn with_effects(
            graphs: Arc<dyn GraphConfigSource>,
            checkpoint: Arc<dyn CheckpointStore>,
            state_store: Arc<dyn AgentStateStore>,
            agent_turn: AgentTurnFn,
            tool: ToolFn,
            supervisor: SupervisorFn,
            approval: ApprovalFn,
        ) -> Self {
            Self {
                graphs,
                checkpoint,
                state_store,
                turn_source: Arc::new(FixedTurnSource {
                    agent_turn,
                    supervisor,
                }),
                tool,
                approval,
                audit_sink: None,
                billing: TurnBilling::default(),
            }
        }

        /// Resolve the run id to drive for this `(session, graph)` and whether
        /// the existing record (if any) is mid-flight.
        ///
        /// Base run id is `"{safe_session}__{graph_id}"` where `safe_session` is
        /// the incoming `session_id` with every `':'` replaced by `'_'`.
        ///
        /// **Why sanitize `':'`?**  Flow session ids frequently embed channel
        /// correlation ids that contain colons (e.g. MS Teams thread ids such as
        /// `msteams:thread:19xyz`). The checkpoint store key contract forbids
        /// `':'`, so using the raw session id causes every such graph run to fail
        /// at save-time. The replacement is stable: the same incoming
        /// `session_id` always maps to the same `safe_session`, so checkpoint
        /// resume works correctly across calls.
        ///
        /// When the base slot is already terminal (`Succeeded`/`Failed`), retry
        /// `"{safe_session}__{graph_id}__{n}"` for `n = 2..` until a slot is
        /// absent (→ start fresh) or non-terminal — `Running` or `AwaitingInput`
        /// (→ resume). Bounded at
        /// [`MAX_RUN_ID_SUFFIX`]. Exhausting all suffixes returns
        /// [`RunIdError::SuffixExhausted`] (distinct from
        /// [`GraphExecError::IterationCap`] so the caller can surface a
        /// targeted reply).
        async fn derive_run_id(
            &self,
            tenant: &TenantContext,
            graph_id: &str,
            session_id: &str,
        ) -> Result<RunSlot, RunIdError> {
            // Sanitize colons: flow session ids (e.g. Teams thread correlation
            // ids) may contain ':' which the checkpoint key contract forbids.
            let safe_session = session_id.replace(':', "_");
            let base = format!("{safe_session}__{graph_id}");
            match self.checkpoint.load(tenant, &base).await? {
                None => return Ok(RunSlot::start(base)),
                // `AwaitingInput` is a parked, non-terminal state (the run is
                // paused at an approval node, not done) — same resume
                // treatment as `Running`. Without this arm, every call after
                // a park would fall through to the terminal branch below and
                // mint a fresh `__n` run id, orphaning the parked run forever
                // (it can never be decided because nothing ever resumes it)
                // and silently forking the conversation.
                Some(rec)
                    if matches!(rec.status, RunStatus::Running | RunStatus::AwaitingInput) =>
                {
                    return Ok(RunSlot::resume(base));
                }
                Some(_) => {}
            }
            for n in 2..=MAX_RUN_ID_SUFFIX {
                let candidate = format!("{safe_session}__{graph_id}__{n}");
                match self.checkpoint.load(tenant, &candidate).await? {
                    None => return Ok(RunSlot::start(candidate)),
                    Some(rec)
                        if matches!(rec.status, RunStatus::Running | RunStatus::AwaitingInput) =>
                    {
                        return Ok(RunSlot::resume(candidate));
                    }
                    Some(_) => continue,
                }
            }
            // All suffix slots are occupied (terminal). This is a distinct
            // error from the graph's own IterationCap: it means the session has
            // exhausted the run-id namespace, not that any single run looped.
            Err(RunIdError::SuffixExhausted { base_run_id: base })
        }
    }

    /// Outcome of [`RuntimeGraphNodeHandler::derive_run_id`]: which run id to
    /// drive and whether to start it fresh or resume an in-flight record.
    struct RunSlot {
        run_id: String,
        resume: bool,
    }

    impl RunSlot {
        fn start(run_id: String) -> Self {
            Self {
                run_id,
                resume: false,
            }
        }
        fn resume(run_id: String) -> Self {
            Self {
                run_id,
                resume: true,
            }
        }
    }

    #[async_trait::async_trait]
    impl GraphNodeHandler for RuntimeGraphNodeHandler {
        async fn execute(
            &self,
            tenant_id: &str,
            env_id: &str,
            graph_id: &str,
            session_id: &str,
            flow_input: &Value,
        ) -> Result<Value> {
            // Contract mirror of agent_node.rs: a missing/empty `user_text`
            // resolves to an empty string and the run proceeds (it never returns
            // Err for this case).
            let user_text = flow_input
                .get("user_text")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string();

            let tenant = TenantContext::new(tenant_id, env_id);

            // Resolve the graph. A missing graph is a user-facing "unavailable"
            // outcome, never an Err.
            let cfg = match self.graphs.graph_config(&tenant, graph_id).await {
                Ok(cfg) => cfg,
                Err(error) => {
                    tracing::warn!(error = %error, graph_id, "graph config not found");
                    return Ok(error_envelope(GRAPH_UNAVAILABLE_REPLY));
                }
            };

            // Acquire the session lock before driving (mirrors the single-agent
            // loop's default 5s wait). Held across the drive via the guard.
            let _lock = match self
                .state_store
                .acquire_lock(&tenant, session_id, Duration::from_secs(5))
                .await
            {
                Ok(guard) => guard,
                Err(error) => {
                    tracing::warn!(error = %error, graph_id, session_id, "session lock failed");
                    return Ok(error_envelope(SANITISED_ERROR_REPLY));
                }
            };

            let slot = match self.derive_run_id(&tenant, graph_id, session_id).await {
                Ok(slot) => slot,
                Err(RunIdError::SuffixExhausted { .. }) => {
                    tracing::warn!(
                        graph_id,
                        session_id,
                        "all run-id slots exhausted for session"
                    );
                    return Ok(error_envelope(
                        "Too many runs for this session. Please start a new conversation.",
                    ));
                }
                Err(RunIdError::Checkpoint(error)) => {
                    tracing::warn!(error = %error, graph_id, session_id, "run-id derivation failed");
                    return Ok(error_envelope(SANITISED_ERROR_REPLY));
                }
            };

            // The real tenant/env `execute` already received — the same one
            // driving executor/checkpoint/run-id above. (The turn functions
            // build their per-visit `TenantContext` from it plus the unit —
            // see `TurnBilling::turn_tenant`.) Rebuilt fresh on
            // every call — see `TurnEffectSource` — so the sink + real tenant
            // reach `run_one_agent_turn`/`run_one_supervisor_turn`, which feed
            // them into the shared `run_agent_step` seam that builds the
            // `AgentAuditObserver` (EPIC-B B-3b Task 2).
            let real_tenant = tenant_ctx_for_audit(tenant_id, env_id);
            let agent_turn = self.turn_source.agent_turn(
                self.audit_sink.clone(),
                real_tenant.clone(),
                self.billing.clone(),
            );
            let supervisor = self.turn_source.supervisor(
                self.audit_sink.clone(),
                real_tenant,
                self.billing.clone(),
            );

            let executor = GraphExecutor::new(
                self.checkpoint.clone(),
                agent_turn,
                self.tool.clone(),
                supervisor,
                self.approval.clone(),
            );

            let result = if slot.resume {
                executor.resume(&tenant, &slot.run_id).await
            } else {
                executor
                    .start(&tenant, &slot.run_id, &cfg, &user_text)
                    .await
            };

            match result {
                // `AwaitingInput` means the run parked at an approval node
                // (see `default_approval_awaiting` below): it is neither a
                // completed respond nor a failure, so it must not be
                // reported as `terminated_by: "respond"` (a caller branching
                // on that value would wrongly treat the pause as done) nor
                // surfaced as an error. This runner-host path has no
                // approval-transport integration yet (that lands with the
                // designer NATS bridge), so a parked run has no other
                // observable signal beyond this envelope + the warning
                // below — the run itself remains durably `AwaitingInput` in
                // the checkpoint store and `derive_run_id` resumes it (not
                // forks a new run) on every subsequent call for the same
                // session until a decision arrives.
                Ok(outcome) if outcome.status == RunStatus::AwaitingInput => {
                    tracing::warn!(
                        graph_id,
                        session_id,
                        run_id = %slot.run_id,
                        "graph run parked awaiting human approval; no approval \
                         transport is wired on this in-process runner-host path, \
                         so the run stays AwaitingInput until an external decision \
                         resolves it"
                    );
                    Ok(json!({
                        "reply": outcome.reply,
                        "trail": outcome.trail,
                        "terminated_by": "awaiting_approval",
                    }))
                }
                Ok(outcome) => Ok(json!({
                    "reply": outcome.reply,
                    "trail": outcome.trail,
                    "terminated_by": "respond",
                })),
                Err(error) => {
                    tracing::warn!(error = %error, graph_id, session_id, "graph run failed");
                    // The DwAgent envelope only carries "respond" / "error".
                    // IterationCap (graph's own node-visit limit) gets a distinct,
                    // still user-safe reply; every other runtime failure falls back
                    // to the generic sanitised message.
                    let reply = match error {
                        GraphExecError::IterationCap { .. } => {
                            "This is taking longer than expected. Please try again."
                        }
                        _ => SANITISED_ERROR_REPLY,
                    };
                    Ok(error_envelope(reply))
                }
            }
        }
    }

    /// Build the `{"reply", "trail", "terminated_by": "error"}` envelope. The
    /// trail is empty: a failed/unavailable run surfaces no completed-node trail
    /// to the flow output (the detail is logged instead).
    fn error_envelope(reply: &str) -> Value {
        json!({
            "reply": reply,
            "trail": Vec::<Value>::new(),
            "terminated_by": "error",
        })
    }

    /// Seed a fresh [`ConversationState`] from the graph run's message log so the
    /// per-visit agent has full context (including after a checkpoint resume).
    ///
    /// Tool-role graph messages are folded in as a plain user-context line
    /// rather than a `ChatMessage::Tool` (which needs a `call_id` paired to an
    /// assistant `tool_calls[]` entry the graph state does not track) — matching
    /// the designer spike.
    fn seed_state_from_graph(
        tenant: &TenantContext,
        session_id: &str,
        state: &GraphRunState,
    ) -> ConversationState {
        let mut seeded = ConversationState::empty(tenant, session_id);
        for m in &state.messages {
            match m.role {
                GraphRole::User => seeded.messages.push(ChatMessage::User {
                    content: m.content.clone(),
                }),
                GraphRole::Assistant => seeded.messages.push(ChatMessage::Assistant {
                    content: m.content.clone(),
                    tool_calls: vec![],
                }),
                GraphRole::Tool => seeded.messages.push(ChatMessage::User {
                    content: format!("Tool result: {}", m.content),
                }),
            }
        }
        seeded
    }

    /// Build the [`AgentTurnFn`] effect closure.
    ///
    /// Each invocation constructs a lightweight [`AgentRuntime`] with a fresh
    /// single-entry [`InMemoryConfigProvider`] (agent id `"{graph_id}.{node_id}"`,
    /// the node's system prompt, no tools — the graph owns tool dispatch via the
    /// explicit Tool node) reusing the shared runtime Arcs. Conversation context
    /// is re-seeded from the durable [`GraphRunState`] on every visit; the
    /// per-visit session id is `"{session_id}__{graph_id}__{node_id}"`.
    #[allow(clippy::too_many_arguments)]
    fn build_agent_turn(
        state_store: Arc<dyn AgentStateStore>,
        ext_runtime: Arc<ExtensionRuntime>,
        llm: Arc<dyn LlmBackend>,
        telemetry: Arc<dyn Telemetry>,
        token_meter: Arc<dyn TokenMeter>,
        ledger: Arc<dyn ToolLedger>,
        mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
        merged_agents: Arc<HashMap<String, AgentConfig>>,
        index_mount: IndexMount,
        audit_sink: Option<AuditSink>,
        real_tenant: greentic_types::TenantCtx,
        billing: TurnBilling,
    ) -> AgentTurnFn {
        Arc::new(move |req: AgentTurnRequest| {
            let state_store = state_store.clone();
            let ext_runtime = ext_runtime.clone();
            let llm = llm.clone();
            let telemetry = telemetry.clone();
            let token_meter = token_meter.clone();
            let ledger = ledger.clone();
            let mcp_source = mcp_source.clone();
            let a2a_source = a2a_source.clone();
            let packs = packs.clone();
            let merged_agents = merged_agents.clone();
            let audit_sink = audit_sink.clone();
            let real_tenant = real_tenant.clone();
            let index_mount = index_mount.clone();
            let billing = billing.clone();
            Box::pin(async move {
                run_one_agent_turn(
                    req,
                    state_store,
                    ext_runtime,
                    llm,
                    telemetry,
                    token_meter,
                    ledger,
                    mcp_source,
                    a2a_source,
                    packs,
                    merged_agents,
                    audit_sink.as_ref(),
                    &real_tenant,
                    &index_mount,
                    &billing,
                )
                .await
            }) as BoxFut<'static, Result<AgentTurnResult, GraphExecError>>
        })
    }

    /// Drive one graph-node agent step: [`AgentRuntime::step`] when no audit
    /// sink is configured, or [`AgentRuntime::step_with_observer`] with an
    /// [`AgentAuditObserver`] when one is (EPIC-B B-3b Task 2). Shared by
    /// [`run_one_agent_turn`] and [`run_one_supervisor_turn`] so the
    /// audit-injection seam is defined exactly once.
    ///
    /// `tenant`/`session_id`/`agent_id` are the per-visit state identifiers
    /// (`TurnBilling::turn_tenant` — the real tenant/env plus the unit — and
    /// the derived session/agent ids); `tenant` is also what the billing sink
    /// attributes the turn to. `real_tenant` is used ONLY to build the audit
    /// observer's `TenantCtx`, unchanged by the billing wiring.
    ///
    /// Off by default: when `audit_sink` is `None` (no NATS audit client
    /// configured), this is exactly `runtime.step(...)` — byte-identical to
    /// the call before this observer existed.
    async fn run_agent_step(
        runtime: &AgentRuntime,
        tenant: TenantContext,
        session_id: &str,
        agent_id: &str,
        input: AgentInput,
        audit_sink: Option<&AuditSink>,
        real_tenant: &greentic_types::TenantCtx,
    ) -> std::result::Result<AgentOutput, AgentError> {
        match audit_sink {
            Some(sink) => {
                let observer: Arc<dyn StepObserver> = Arc::new(AgentAuditObserver::new(
                    sink.clone(),
                    real_tenant.clone(),
                    agent_id.to_string(),
                    session_id.to_string(),
                ));
                runtime
                    .step_with_observer(tenant, session_id, agent_id, input, observer)
                    .await
            }
            None => runtime.step(tenant, session_id, agent_id, input).await,
        }
    }

    /// Parse a graph node's declared tool reference string into a [`ToolRef`].
    ///
    /// Format convention: `"<extension_id>/<tool_name>"`, split on the LAST
    /// `/` (so an `extension_id` that itself contains `/`, e.g.
    /// `"component:owner/repo"`, is preserved intact). Returns `None` — with a
    /// `tracing::warn!` naming the skipped string — when there is no `/`, or
    /// when either side of the split is empty. Never panics: this runs against
    /// node-authored config, not host-controlled input.
    fn parse_tool_ref(s: &str) -> Option<ToolRef> {
        match s.rsplit_once('/') {
            Some((extension_id, tool_name))
                if !extension_id.is_empty() && !tool_name.is_empty() =>
            {
                Some(ToolRef {
                    extension_id: extension_id.to_string(),
                    tool_name: tool_name.to_string(),
                    description: None,
                    input_schema: None,
                    usage_note: None,
                })
            }
            _ => {
                tracing::warn!(tool_ref = %s, "skipping malformed graph-node tool ref (expected \"<extension_id>/<tool_name>\")");
                None
            }
        }
    }

    /// Map a graph node's declared `tools: Vec<String>` (see
    /// [`AgentTurnRequest::tools`]) to the `Vec<ToolRef>` the ephemeral
    /// per-visit [`AgentConfig`] expects. Malformed entries are dropped by
    /// [`parse_tool_ref`] (warned, never fatal) rather than failing the turn.
    fn map_tool_refs(tools: &[String]) -> Vec<ToolRef> {
        tools.iter().filter_map(|t| parse_tool_ref(t)).collect()
    }

    /// The [`AgentConfig`] a graph agent-turn runs.
    ///
    /// `req.agent_ref` present (`Some(id)`) → the full published config
    /// resolved from `merged` (memory/knowledge/guardrails intact, exactly as
    /// stored) — errors when `id` is not in the map. `req.agent_ref` absent
    /// (`None`) → the stripped ephemeral config fabricated from the node's
    /// own inline fields (today's unchanged one-shot behaviour: no
    /// guardrails, no memory, no knowledge).
    fn resolve_turn_config(
        req: &AgentTurnRequest,
        merged: &HashMap<String, AgentConfig>,
        agent_id: &str,
    ) -> Result<AgentConfig, GraphExecError> {
        if let Some(id) = req.agent_ref.as_deref() {
            return merged.get(id).cloned().ok_or_else(|| {
                GraphExecError::AgentTurn(format!("referenced agent '{id}' not found"))
            });
        }
        // `inherit_from` is the specialist case: keep this node's own prompt and
        // model — that is what makes a specialist a specialist — but adopt the
        // referenced worker's capability surface. Using `agent_ref` here instead
        // would overwrite the prompt and collapse every specialist in a
        // generated graph into an identical copy of its parent.
        //
        // Like the supervisor path, an id that does not resolve FAILS rather
        // than running stripped: a specialist believed to be guarded and
        // tool-equipped but running bare is worse than one that never claimed
        // to be.
        if let Some(id) = req.inherit_from.as_deref() {
            let parent = merged.get(id).ok_or_else(|| {
                GraphExecError::AgentTurn(format!(
                    "node '{}': inherit_from '{}' not found in merged agents; \
                     refusing to run without its tools and guardrails",
                    req.node_id, id
                ))
            })?;
            return Ok(AgentConfig {
                agent_id: agent_id.to_string(),
                system_prompt: req.system_prompt.clone(),
                llm: LlmProviderRef {
                    provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
                    model: req.model.clone(),
                    credential_ref: None,
                },
                // Inherited capability surface.
                tools: parent.tools.clone(),
                guardrails: parent.guardrails.clone(),
                memory: parent.memory.clone(),
                knowledge: parent.knowledge.clone(),
                limits: parent.limits.clone(),
                conversational: false,
                opening_message: None,
                on_text_while_parked: Default::default(),
            });
        }
        Ok(AgentConfig {
            agent_id: agent_id.to_string(),
            system_prompt: req.system_prompt.clone(),
            tools: map_tool_refs(&req.tools),
            guardrails: vec![],
            llm: LlmProviderRef {
                provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
                model: req.model.clone(),
                credential_ref: None,
            },
            limits: AgentLimits::default(),
            memory: None,
            knowledge: None,
            conversational: false,
            opening_message: None,
            on_text_while_parked: Default::default(),
        })
    }

    /// Drive one [`AgentRuntime::step`] for an agent-node visit. Derives the
    /// agent/session ids, seeds conversation context, runs the step, and maps the
    /// reply's resolution sentinel.
    ///
    /// `audit_sink`/`real_tenant` are forwarded to [`run_agent_step`], which
    /// injects an [`AgentAuditObserver`] built from `real_tenant` when a sink
    /// is configured (EPIC-B B-3b Task 2).
    ///
    /// When `req.agent_ref` is `Some`, [`resolve_turn_config`] resolves the
    /// full published `AgentConfig` from `merged_agents` and the runtime is
    /// built with the same fidelity as `agent_node::build_agent_runtime`
    /// (guardrails + short-term memory + feature-gated long-term/knowledge).
    /// `agent_ref: None` stays byte-unchanged: the stripped ephemeral config,
    /// no guardrails/memory/knowledge attached.
    #[allow(clippy::too_many_arguments)]
    async fn run_one_agent_turn(
        req: AgentTurnRequest,
        state_store: Arc<dyn AgentStateStore>,
        ext_runtime: Arc<ExtensionRuntime>,
        llm: Arc<dyn LlmBackend>,
        telemetry: Arc<dyn Telemetry>,
        token_meter: Arc<dyn TokenMeter>,
        ledger: Arc<dyn ToolLedger>,
        mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
        merged_agents: Arc<HashMap<String, AgentConfig>>,
        audit_sink: Option<&AuditSink>,
        real_tenant: &greentic_types::TenantCtx,
        index_mount: &IndexMount,
        billing: &TurnBilling,
    ) -> Result<AgentTurnResult, GraphExecError> {
        // The request carries no tenant/graph/session — they live on the
        // GraphRunState's seeded session. The executor seeds the run state with
        // the tenant-scoped messages, so we reconstruct a turn-scoped session
        // purely for the per-visit runtime. Conversation durability is owned by
        // the graph checkpoint, not this ephemeral store.
        //
        // The tenant is the REAL one the node was dispatched with (plus the
        // deployed unit), not a synthetic `("graph", "run")`: it is also the
        // tenant the billing sink attributes this turn's LLM spend to.
        let tenant = billing.turn_tenant(real_tenant);
        let session_id = format!("graph__{}", req.node_id);
        let agent_id = format!("graph.{}", req.node_id);

        let seeded = seed_state_from_graph(&tenant, &session_id, &req.state);
        if let Err(error) = state_store.save(&tenant, &session_id, &seeded).await {
            return Err(GraphExecError::AgentTurn(format!(
                "seeding conversation state: {error}"
            )));
        }

        let cfg = resolve_turn_config(&req, &merged_agents, &agent_id)?;
        // Key the config provider — and the `.step()` call — by the id the
        // runtime will actually resolve config under: the referenced agent's
        // own id when `agent_ref` is set (so guardrail/memory/knowledge
        // bindings on that published agent are addressed correctly), else the
        // synthetic per-node id used today.
        let step_agent_id = req.agent_ref.clone().unwrap_or_else(|| agent_id.clone());
        let mut provider = InMemoryConfigProvider::new();
        provider.insert(&tenant, &step_agent_id, cfg.clone());

        // TODO(guardrail): inline (agent_ref: None) graph-node AgentRuntime bypasses
        // guardrails (v1 scope is dw.agent flow nodes only). A referenced agent
        // (agent_ref: Some) gets full guardrail/memory/knowledge fidelity below.
        // MCP tool source: mirror the `dw.agent` path so a graph agent declaring an
        // `mcp:<server>/<tool>` ref resolves it against the tenant's registered MCP
        // servers (same double-authorization: tenant registers the server + the node's
        // tool allowlist must reference it). `None` unless the admin creds are set.
        //
        // Component tool source: unlike `mcp_source` (built once, reused across
        // every graph-agent visit), the component source is tenant-pinned, so it
        // is rebuilt PER TURN from the in-memory `packs` list — cheap, and keeps
        // a `component:<ref>` tool ref scoped to the real tenant.
        let component_source = super::super::agent_node::component_source_from_packs(
            &packs,
            real_tenant.tenant_id.as_str(),
        );
        let mut runtime = AgentRuntime::new(
            Arc::new(provider),
            state_store,
            ext_runtime.clone(),
            llm,
            telemetry,
            token_meter,
            ledger,
            mcp_source,
        )
        .with_component_source(component_source)
        // A2A: the handler's pack-carried source (see `graph_a2a_source`),
        // for inline, inheriting and referenced agents alike — exactly what
        // the single-turn `dw.agent` runtime attaches.
        .with_a2a_source(a2a_source);
        runtime = billing.install(runtime);

        // Full fidelity ONLY for a referenced agent — mirrors
        // `agent_node::build_agent_runtime`'s guardrail/short-term-memory/
        // long-term/knowledge attachment sequence exactly. The `agent_ref:
        // None` inline path stays byte-unchanged (no guardrails/memory/
        // knowledge), preserving today's one-shot graph-node behaviour.
        if req.agent_ref.is_some() {
            runtime = runtime
                .with_guardrails(
                    Arc::new(greentic_aw_runtime::guardrail::StaticGuardrailPolicy(
                        cfg.guardrails.clone(),
                    )),
                    Arc::new(
                        greentic_aw_runtime::guardrail::ExtRuntimeGuardrailEvaluator {
                            ext_runtime: ext_runtime.clone(),
                        },
                    ),
                )
                .with_short_term_memory(Arc::new(
                    greentic_aw_runtime::memory::InMemoryMemoryProvider::new(),
                ));
            // Long-term memory and corpus knowledge from every registered
            // agent-runtime extension (see `runtime_ext`).
            runtime = crate::runner::runtime_ext::attach_all(runtime).await;
            // Knowledge delegated to a design-extension tool. Not feature-gated
            // (see `knowledge_ext`); it wraps whatever corpus backend an
            // extension above left in place. Inside the `agent_ref.is_some()` arm with the rest
            // of the full-fidelity attachment sequence, so the `agent_ref: None`
            // inline path stays byte-unchanged.
            // Chronicle-index retrieval beneath it, reading its credentials
            // under the secrets tenant the mount captured at construction.
            runtime = index_mount.attach(runtime);
            runtime = crate::runner::knowledge_ext::attach(runtime, ext_runtime.clone());
        }

        // The latest user turn is the most recent user message in the seeded log
        // (the executor pushes the initial user message and re-seeds it here);
        // pass an empty input so we do not duplicate it — the step appends the
        // input as a fresh user turn, so an empty string keeps the history intact.
        let input = AgentInput {
            text: String::new(),
            ..Default::default()
        };

        let out = run_agent_step(
            &runtime,
            tenant.clone(),
            &session_id,
            &step_agent_id,
            input,
            audit_sink,
            real_tenant,
        )
        .await
        .map_err(|e| GraphExecError::AgentTurn(format!("agent step failed: {e}")))?;

        Ok(AgentTurnResult {
            resolved: detect_resolved(&out.reply),
            reply: strip_sentinel(&out.reply),
        })
    }

    /// Routing sentinel that the supervisor LLM must include in its reply to
    /// select a branch. Parsed case-insensitively.
    const ROUTE_SENTINEL_PREFIX: &str = "[[ROUTE:";
    const ROUTE_SENTINEL_SUFFIX: &str = "]]";

    /// Build the [`SupervisorFn`] effect closure.
    ///
    /// Each invocation constructs a lightweight [`AgentRuntime`] (same pattern
    /// as [`build_agent_turn`]) with a system prompt that appends a route menu
    /// to the node's own `systemPrompt`. The reply is scanned for
    /// `[[ROUTE:<branch>]]`; if the sentinel is absent or the branch is unknown
    /// the executor falls back to the FIRST route with a `tracing::warn!`.
    #[allow(clippy::too_many_arguments)]
    fn build_supervisor(
        state_store: Arc<dyn AgentStateStore>,
        ext_runtime: Arc<ExtensionRuntime>,
        llm: Arc<dyn LlmBackend>,
        telemetry: Arc<dyn Telemetry>,
        token_meter: Arc<dyn TokenMeter>,
        ledger: Arc<dyn ToolLedger>,
        merged_agents: Arc<HashMap<String, AgentConfig>>,
        audit_sink: Option<AuditSink>,
        real_tenant: greentic_types::TenantCtx,
        billing: TurnBilling,
    ) -> SupervisorFn {
        Arc::new(move |req: SupervisorRequest| {
            let merged_agents = merged_agents.clone();
            let state_store = state_store.clone();
            let ext_runtime = ext_runtime.clone();
            let llm = llm.clone();
            let telemetry = telemetry.clone();
            let token_meter = token_meter.clone();
            let ledger = ledger.clone();
            let audit_sink = audit_sink.clone();
            let real_tenant = real_tenant.clone();
            let billing = billing.clone();
            Box::pin(async move {
                run_one_supervisor_turn(
                    req,
                    state_store,
                    ext_runtime,
                    llm,
                    telemetry,
                    token_meter,
                    ledger,
                    merged_agents,
                    audit_sink.as_ref(),
                    &real_tenant,
                    &billing,
                )
                .await
            }) as BoxFut<'static, Result<SupervisorResult, GraphExecError>>
        })
    }

    /// Resolve the guardrails a supervisor node runs under.
    ///
    /// A supervisor inherits its worker's GUARDRAILS and nothing else — it
    /// routes, it does not work, so tools, memory and knowledge stay unset.
    /// Guardrails are the exception because this node sees the operator's raw
    /// input first: it is where inbound content-safety has to run.
    ///
    /// An `agent_ref` that does not resolve FAILS the turn rather than routing
    /// unguarded. A supervisor believed to be protected but running bare is the
    /// precise failure this inheritance exists to prevent, and a silent
    /// downgrade would be indistinguishable from success.
    fn resolve_supervisor_guardrails(
        agent_ref: Option<&str>,
        merged: &HashMap<String, AgentConfig>,
        node_id: &str,
    ) -> Result<Vec<greentic_aw_runtime::config::GuardrailRef>, GraphExecError> {
        let Some(id) = agent_ref else {
            return Ok(vec![]);
        };
        merged
            .get(id)
            .map(|parent| parent.guardrails.clone())
            .ok_or_else(|| {
                GraphExecError::Supervisor(format!(
                    "node '{node_id}': agent_ref '{id}' not found in merged agents; \
                     refusing to route without its guardrails"
                ))
            })
    }

    /// Drive one supervisor routing turn via [`AgentRuntime::step`].
    ///
    /// The routing prompt appends a route menu to the node's `systemPrompt`:
    ///
    /// ```text
    /// <node system_prompt>
    ///
    /// Available routes:
    /// - billing: Billing and payment questions
    /// - tech: Technical support issues
    ///
    /// Reply with [[ROUTE:<branch>]] to select a route.
    /// ```
    ///
    /// The agent reply is scanned for `[[ROUTE:<branch>]]` (case-insensitive).
    /// If the sentinel is absent or the branch does not match a declared route,
    /// the first route is used as fallback with a `tracing::warn!`.
    ///
    /// `audit_sink`/`real_tenant` are forwarded to [`run_agent_step`], which
    /// injects an [`AgentAuditObserver`] built from `real_tenant` when a sink
    /// is configured (EPIC-B B-3b Task 2).
    #[allow(clippy::too_many_arguments)]
    async fn run_one_supervisor_turn(
        req: SupervisorRequest,
        state_store: Arc<dyn AgentStateStore>,
        ext_runtime: Arc<ExtensionRuntime>,
        llm: Arc<dyn LlmBackend>,
        telemetry: Arc<dyn Telemetry>,
        token_meter: Arc<dyn TokenMeter>,
        ledger: Arc<dyn ToolLedger>,
        merged_agents: Arc<HashMap<String, AgentConfig>>,
        audit_sink: Option<&AuditSink>,
        real_tenant: &greentic_types::TenantCtx,
        billing: &TurnBilling,
    ) -> Result<SupervisorResult, GraphExecError> {
        // Real tenant + unit, as for an agent turn: routing is an LLM call too.
        let tenant = billing.turn_tenant(real_tenant);
        let session_id = format!("graph__{}_sup", req.node_id);
        let agent_id = format!("graph.{}.supervisor", req.node_id);

        // Build the route menu suffix.
        let mut route_menu = String::from("\n\nAvailable routes:\n");
        for r in &req.routes {
            route_menu.push_str(&format!("- {}: {}\n", r.branch, r.description));
        }
        route_menu.push_str("\nReply with [[ROUTE:<branch>]] to select a route.");

        let routing_system_prompt = format!("{}{}", req.system_prompt, route_menu);

        let seeded = seed_state_from_graph(&tenant, &session_id, &req.state);
        if let Err(error) = state_store.save(&tenant, &session_id, &seeded).await {
            return Err(GraphExecError::Supervisor(format!(
                "seeding conversation state: {error}"
            )));
        }

        let guardrails =
            resolve_supervisor_guardrails(req.agent_ref.as_deref(), &merged_agents, &req.node_id)?;

        let cfg = AgentConfig {
            agent_id: agent_id.clone(),
            system_prompt: routing_system_prompt,
            tools: vec![],
            guardrails,
            llm: LlmProviderRef {
                provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
                model: req.model.clone(),
                credential_ref: None,
            },
            limits: AgentLimits::default(),
            memory: None,
            knowledge: None,
            conversational: false,
            opening_message: None,
            on_text_while_parked: Default::default(),
        };
        let mut provider = InMemoryConfigProvider::new();
        provider.insert(&tenant, &agent_id, cfg);

        let runtime = billing.install(AgentRuntime::new(
            Arc::new(provider),
            state_store,
            ext_runtime,
            llm,
            telemetry,
            token_meter,
            ledger,
            // Supervisor routing runs with an empty tool list; MCP tools are
            // never offered on this path.
            None,
        ));

        let input = AgentInput {
            text: String::new(),
            ..Default::default()
        };

        let out = run_agent_step(
            &runtime,
            tenant.clone(),
            &session_id,
            &agent_id,
            input,
            audit_sink,
            real_tenant,
        )
        .await
        .map_err(|e| GraphExecError::Supervisor(format!("supervisor step failed: {e}")))?;

        // Parse [[ROUTE:<branch>]] from the reply (case-insensitive).
        // Do this BEFORE stripping so we read from the unmodified reply.
        let branch = parse_route_branch(&out.reply, &req.routes).unwrap_or_else(|| {
            let fallback = req
                .routes
                .first()
                .map(|r| r.branch.clone())
                .unwrap_or_default();
            tracing::warn!(
                node_id = req.node_id,
                reply = %out.reply,
                fallback = %fallback,
                "supervisor reply missing or unknown [[ROUTE:]] sentinel; falling back to first route"
            );
            fallback
        });

        // Strip the [[ROUTE:<branch>]] sentinel from the stored assistant message
        // so the message log does not expose routing instructions to downstream nodes.
        let raw_reply = strip_route_sentinel(&out.reply);

        Ok(SupervisorResult { branch, raw_reply })
    }

    /// Parse `[[ROUTE:<branch>]]` from the reply and return the branch label if
    /// it matches one of the declared routes. Returns `None` if the sentinel is
    /// absent or the extracted branch is not in the route list.
    fn parse_route_branch(
        reply: &str,
        routes: &[greentic_aw_runtime::graph::SupervisorRoute],
    ) -> Option<String> {
        let lower = reply.to_ascii_lowercase();
        let prefix_lower = ROUTE_SENTINEL_PREFIX.to_ascii_lowercase();
        let suffix_lower = ROUTE_SENTINEL_SUFFIX.to_ascii_lowercase();
        let start = lower.find(&prefix_lower)?;
        let after_prefix = start + prefix_lower.len();
        let end = lower[after_prefix..].find(&suffix_lower)?;
        let branch = reply[after_prefix..after_prefix + end].trim().to_string();
        // Validate against declared routes (case-sensitive match, per spec).
        if routes.iter().any(|r| r.branch == branch) {
            Some(branch)
        } else {
            None
        }
    }

    /// Strip the `[[ROUTE:<branch>]]` sentinel (case-insensitive, first occurrence)
    /// from a supervisor reply, trimming surrounding whitespace.
    ///
    /// If no sentinel is present the reply is returned trimmed. Used to clean
    /// up the text before it is pushed into the message log as an assistant
    /// message.
    fn strip_route_sentinel(reply: &str) -> String {
        let lower = reply.to_ascii_lowercase();
        let prefix_lower = ROUTE_SENTINEL_PREFIX.to_ascii_lowercase();
        let suffix_lower = ROUTE_SENTINEL_SUFFIX.to_ascii_lowercase();
        if let Some(start) = lower.find(&prefix_lower) {
            let after_prefix = start + prefix_lower.len();
            if let Some(end) = lower[after_prefix..].find(&suffix_lower) {
                let sentinel_end = after_prefix + end + suffix_lower.len();
                let mut out = reply.to_string();
                out.replace_range(start..sentinel_end, "");
                return out.trim().to_string();
            }
        }
        reply.trim().to_string()
    }

    /// Build the [`ToolFn`] effect closure.
    ///
    /// `tool_name` is parsed as `"extension_id/tool_name"` (split on the FIRST
    /// `'/'`). Anything without a `'/'`, or an empty side, is a
    /// [`GraphExecError::Tool`]. Dispatch goes through the shared
    /// [`ExtensionRuntime`] via [`dispatch_tool_call`], which wraps the blocking
    /// `invoke_tool` in `spawn_blocking`.
    fn build_tool(
        ext_runtime: Arc<ExtensionRuntime>,
        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
    ) -> ToolFn {
        Arc::new(move |req: ToolCallRequest| {
            let ext_runtime = ext_runtime.clone();
            let a2a_source = a2a_source.clone();
            Box::pin(async move { run_one_tool(req, ext_runtime, a2a_source).await })
                as BoxFut<'static, Result<Value, GraphExecError>>
        })
    }

    /// Default [`ApprovalFn`] for the in-process runner-host path: always
    /// reports `Awaiting`.
    ///
    /// The real `ApprovalFn` is designer-provided and wires the
    /// `greentic.approval.request.v1` / `.response.v1` round trip so a human
    /// decision can arrive asynchronously and unpark the run. This in-process
    /// default has no such transport, so it parks the run safely
    /// (`RunStatus::AwaitingInput`) but never resolves it. `derive_run_id`
    /// resumes (not forks) the parked run on every subsequent call for the
    /// same session, so it stays resolvable once a real `ApprovalFn` is
    /// wired in. See the `from_parts` doc comment; the designer-side
    /// approval bridge (subscriber + node, cross-repo Phase 2) supplies the
    /// real consumer.
    fn default_approval_awaiting() -> ApprovalFn {
        Arc::new(|_req: ApprovalRequest| Box::pin(async move { Ok(ApprovalOutcome::Awaiting) }))
    }

    /// Parse + dispatch a single Tool-node call. See [`build_tool`].
    async fn run_one_tool(
        req: ToolCallRequest,
        ext_runtime: Arc<ExtensionRuntime>,
        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
    ) -> Result<Value, GraphExecError> {
        let (extension_id, tool_name) = req.tool_name.split_once('/').ok_or_else(|| {
            GraphExecError::Tool(format!(
                "tool name '{}' must be 'extension_id/tool_name'",
                req.tool_name
            ))
        })?;
        if extension_id.is_empty() || tool_name.is_empty() {
            return Err(GraphExecError::Tool(format!(
                "tool name '{}' must be 'extension_id/tool_name' (non-empty parts)",
                req.tool_name
            )));
        }

        // The graph Tool node carries no arguments today: dispatch with an empty
        // object. A future schema can thread structured args from node config.
        let call = greentic_aw_runtime::state::ToolCallRecord {
            call_id: format!("{}__{}", req.node_id, tool_name),
            extension_id: extension_id.to_string(),
            tool_name: tool_name.to_string(),
            args: json!({}),
        };

        // A Tool node names 'extension_id/tool'. An `a2a:<agent_id>/ask` ref
        // dispatches through the handler's pack-carried A2A catalog (the same
        // source the agent turns use; see `graph_a2a_source`), which reads its
        // credential with the tenant and unit it captured at build time, so
        // the placeholder `TenantContext` below does not reach it. mcp:,
        // component:, flow: and sorla: refs are still not wired here — the
        // agent-graph Tool node has no catalog for them, and such a ref
        // returns the dispatcher's "no catalog wired" error value.
        // No per-request TenantContext is available at the graph-node layer;
        // use a no-op placeholder so the extension's host-LLM port receives an
        // empty context (equivalent to the previous `invoke_tool` default).
        let a2a = match a2a_source.as_ref() {
            Some(source) => Some(source.catalog().await),
            None => None,
        };
        let tenant = TenantContext::new("", "");
        // `dispatch_tool_call`, not its `_in_conversation` sibling: a graph
        // node holds no `ConversationState`, so there is nowhere to keep a
        // remote A2A `contextId` between calls. An `a2a:` tool reached from
        // here therefore opens a fresh remote task each time and cannot
        // answer an `input-required`. Closing that needs the graph executor's
        // own checkpoint to carry the continuations, which is a separate
        // change to a different state machine.
        dispatch_tool_call(ext_runtime, None, None, None, None, a2a, call, &tenant)
            .await
            .map_err(|e| GraphExecError::Tool(format!("dispatch '{}': {e}", req.tool_name)))
    }

    #[cfg(all(test, feature = "agentic-worker"))]
    mod tests {
        use std::collections::HashMap;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU32, Ordering};

        use greentic_aw_runtime::graph::model::SupervisorRoute;
        use greentic_aw_runtime::graph::{
            AgentTurnFn, AgentTurnRequest, AgentTurnResult, ApprovalFn, ApprovalOutcome,
            ApprovalRequest, GraphConfig, InMemoryCheckpointStore, SupervisorFn, SupervisorRequest,
            SupervisorResult, ToolCallRequest, ToolFn,
        };
        use greentic_aw_runtime::mock::MockAgentStateStore;
        use serde_json::json;

        use super::*;

        // -------------------------------------------------------------------
        // Fixtures
        // -------------------------------------------------------------------

        /// Minimal triage-style graph: agent → lookup tool → router → respond,
        /// router maxIterations=3. Mirrors the aw-runtime test fixture (which is
        /// `pub(crate)` to that crate and thus not importable here).
        fn triage_graph_json(max_iterations: u32) -> String {
            json!({
                "schemaVersion": 1,
                "entry": "agent",
                "nodes": [
                    {"id": "agent", "kind": "agent", "systemPrompt": "You triage.", "model": "gpt-4o-mini", "tools": []},
                    {"id": "lookup", "kind": "tool", "toolName": "kb/search"},
                    {"id": "router", "kind": "router", "maxIterations": max_iterations},
                    {"id": "respond", "kind": "respond"}
                ],
                "edges": [
                    {"from": "agent", "to": "lookup"},
                    {"from": "lookup", "to": "router"},
                    {"from": "router", "to": "agent", "branch": "loop"},
                    {"from": "router", "to": "respond", "branch": "resolved"}
                ]
            })
            .to_string()
        }

        fn triage_cfg(max_iterations: u32) -> GraphConfig {
            GraphConfig::from_json(&triage_graph_json(max_iterations)).expect("fixture valid")
        }

        /// Graph with a human-in-the-loop approval gate: `start` (agent) ->
        /// `approval` -> `respond` (branch `"approved"`). Mirrors the
        /// aw-runtime executor test fixture (`approval_json` in
        /// `graph/executor.rs`), which is `pub(crate)` there and thus not
        /// importable here.
        fn approval_graph_json() -> String {
            json!({
                "schemaVersion": 2,
                "entry": "start",
                "nodes": [
                    {"id": "start", "kind": "agent", "systemPrompt": "greet the user", "model": "gpt-4o-mini", "tools": []},
                    {"id": "approval", "kind": "approval", "title": "Approve refund?", "mode": "always"},
                    {"id": "respond", "kind": "respond"}
                ],
                "edges": [
                    {"from": "start", "to": "approval"},
                    {"from": "approval", "to": "respond", "branch": "approved"}
                ]
            })
            .to_string()
        }

        fn approval_cfg() -> GraphConfig {
            GraphConfig::from_json(&approval_graph_json()).expect("approval fixture valid")
        }

        /// An [`ApprovalFn`] whose decision flips based on a shared flag:
        /// `Awaiting` while `false`, `Decided { branch: "approved" }` once
        /// `true`. Lets a single handler drive both the initial park and a
        /// later resume-with-decision within one test.
        fn approval_fn_toggle(decide: Arc<std::sync::atomic::AtomicBool>) -> ApprovalFn {
            Arc::new(move |_req: ApprovalRequest| {
                let decide = decide.clone();
                Box::pin(async move {
                    if decide.load(Ordering::SeqCst) {
                        Ok(ApprovalOutcome::Decided {
                            branch: "approved".to_string(),
                        })
                    } else {
                        Ok(ApprovalOutcome::Awaiting)
                    }
                })
            })
        }

        fn provider_with(graph_id: &str, cfg: GraphConfig) -> Arc<InMemoryGraphProvider> {
            let mut graphs = HashMap::new();
            graphs.insert(graph_id.to_string(), cfg);
            Arc::new(InMemoryGraphProvider::new(graphs))
        }

        /// Agent closure that resolves on the n-th (non-replayed) call.
        fn agent_fn_resolves_on(counter: Arc<AtomicU32>, resolve_on_call: u32) -> AgentTurnFn {
            Arc::new(move |req: AgentTurnRequest| {
                let n = counter.fetch_add(1, Ordering::SeqCst) + 1;
                let resolved = n >= resolve_on_call;
                let reply = format!("reply-{n} from {}", req.node_id);
                Box::pin(async move { Ok(AgentTurnResult { reply, resolved }) })
            })
        }

        fn tool_fn_ok() -> ToolFn {
            Arc::new(move |_req: ToolCallRequest| {
                Box::pin(async move { Ok(json!({"found": true})) })
            })
        }

        /// A no-op supervisor fn for tests that do not exercise supervisor nodes.
        fn supervisor_fn_noop() -> SupervisorFn {
            Arc::new(|_req: SupervisorRequest| {
                Box::pin(async move {
                    Err(greentic_aw_runtime::graph::GraphExecError::Supervisor(
                        "supervisor fn should not be called in this test".into(),
                    ))
                })
            })
        }

        /// A trivial approval fn that always reports `Awaiting` — none of
        /// these fixtures contain an approval node, so this is never invoked.
        fn approval_fn_awaiting() -> ApprovalFn {
            Arc::new(|_req: ApprovalRequest| Box::pin(async move { Ok(ApprovalOutcome::Awaiting) }))
        }

        fn handler_with(
            graphs: Arc<dyn GraphConfigSource>,
            agent_turn: AgentTurnFn,
            tool: ToolFn,
        ) -> RuntimeGraphNodeHandler {
            RuntimeGraphNodeHandler::with_effects(
                graphs,
                Arc::new(InMemoryCheckpointStore::default()),
                Arc::new(MockAgentStateStore::new()),
                agent_turn,
                tool,
                supervisor_fn_noop(),
                approval_fn_awaiting(),
            )
        }

        // -------------------------------------------------------------------
        // parse_tool_ref / map_tool_refs tests
        // -------------------------------------------------------------------

        #[test]
        fn parse_tool_ref_splits_on_last_slash() {
            assert_eq!(
                super::parse_tool_ref("myext/dothing"),
                Some(ToolRef {
                    extension_id: "myext".into(),
                    tool_name: "dothing".into(),
                    description: None,
                    input_schema: None,
                    usage_note: None,
                })
            );
            assert_eq!(
                super::parse_tool_ref("component:owner/repo/list"),
                Some(ToolRef {
                    extension_id: "component:owner/repo".into(),
                    tool_name: "list".into(),
                    description: None,
                    input_schema: None,
                    usage_note: None,
                })
            );
            assert_eq!(super::parse_tool_ref("noslash"), None);
            assert_eq!(super::parse_tool_ref("trailing/"), None);
        }

        #[test]
        fn parse_tool_ref_rejects_leading_slash() {
            // Empty extension_id half — also malformed, never panics.
            assert_eq!(super::parse_tool_ref("/dothing"), None);
        }

        #[test]
        fn map_tool_refs_drops_malformed_entries_and_keeps_valid_ones() {
            let tools = vec![
                "myext/dothing".to_string(),
                "noslash".to_string(),
                "other/thing".to_string(),
            ];
            let refs = super::map_tool_refs(&tools);
            assert_eq!(
                refs,
                vec![
                    ToolRef {
                        extension_id: "myext".into(),
                        tool_name: "dothing".into(),
                        description: None,
                        input_schema: None,
                        usage_note: None,
                    },
                    ToolRef {
                        extension_id: "other".into(),
                        tool_name: "thing".into(),
                        description: None,
                        input_schema: None,
                        usage_note: None,
                    },
                ]
            );
        }

        // -------------------------------------------------------------------
        // graph_config_from_sidecar tests
        // -------------------------------------------------------------------

        #[test]
        fn sidecar_valid_triage_parses() {
            let bytes = triage_graph_json(3).into_bytes();
            let cfg = super::graph_config_from_sidecar("test-pack", &bytes);
            assert!(cfg.is_some(), "valid triage sidecar must parse");
        }

        #[test]
        fn sidecar_malformed_json_returns_none() {
            let bytes = b"{ this is not valid json";
            // Must not panic; a malformed sidecar is skipped (None).
            let cfg = super::graph_config_from_sidecar("test-pack", bytes);
            assert!(cfg.is_none(), "malformed JSON sidecar must yield None");
        }

        #[test]
        fn sidecar_unsupported_schema_version_returns_none() {
            let bytes = json!({
                "schemaVersion": 99,
                "entry": "agent",
                "nodes": [
                    {"id": "agent", "kind": "agent", "systemPrompt": "x", "model": "gpt-4o-mini", "tools": []},
                    {"id": "respond", "kind": "respond"}
                ],
                "edges": [{"from": "agent", "to": "respond"}]
            })
            .to_string()
            .into_bytes();
            let cfg = super::graph_config_from_sidecar("test-pack", &bytes);
            assert!(
                cfg.is_none(),
                "unsupported schemaVersion must be rejected (None)"
            );
        }

        // -------------------------------------------------------------------
        // Tests
        // -------------------------------------------------------------------

        #[tokio::test]
        async fn executes_graph_and_returns_dw_agent_envelope() {
            let handler = handler_with(
                provider_with("triage", triage_cfg(3)),
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
                tool_fn_ok(),
            );

            let out = handler
                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "help"}))
                .await
                .expect("execute should succeed");

            assert_eq!(out["terminated_by"].as_str(), Some("respond"));
            assert!(
                out["reply"].as_str().unwrap_or("").contains("reply-1"),
                "reply should carry agent output: {:?}",
                out["reply"]
            );
            assert!(
                out["trail"]
                    .as_array()
                    .map(|a| !a.is_empty())
                    .unwrap_or(false),
                "trail should be a non-empty array: {:?}",
                out["trail"]
            );
        }

        #[tokio::test]
        async fn same_session_resumes_completed_run_with_fresh_run() {
            // Shared checkpoint + state stores so the second call sees the first
            // run's terminal record and mints a fresh `__2` run id.
            let graphs = provider_with("triage", triage_cfg(3));
            let checkpoint = Arc::new(InMemoryCheckpointStore::default());
            let state_store = Arc::new(MockAgentStateStore::new());
            let counter = Arc::new(AtomicU32::new(0));

            let handler = RuntimeGraphNodeHandler::with_effects(
                graphs,
                checkpoint.clone(),
                state_store,
                agent_fn_resolves_on(counter, 1),
                tool_fn_ok(),
                supervisor_fn_noop(),
                approval_fn_awaiting(),
            );

            let first = handler
                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "one"}))
                .await
                .expect("first call succeeds");
            assert_eq!(first["terminated_by"].as_str(), Some("respond"));

            let second = handler
                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "two"}))
                .await
                .expect("second call succeeds with fresh run id");
            assert_eq!(second["terminated_by"].as_str(), Some("respond"));

            // The fresh run id (`__2`) must exist in the checkpoint store.
            let tenant = TenantContext::new("t", "e");
            let fresh = checkpoint
                .load(&tenant, "sess-1__triage__2")
                .await
                .expect("store ok");
            assert!(fresh.is_some(), "fresh __2 run id should be recorded");
        }

        /// Task C3: a graph run parked at an approval node (`RunStatus::
        /// AwaitingInput`) must be surfaced as neither a completed respond
        /// nor a failure, and — unlike a terminal (`Succeeded`/`Failed`) run
        /// — the SAME run id must be resumed on every later call for the
        /// same session, not forked into a fresh `__n` slot (which would
        /// orphan the parked run: it could never be decided because nothing
        /// would ever resume it again).
        #[tokio::test]
        async fn awaiting_input_parks_without_orphaning_and_resumes_on_decision() {
            let graphs = provider_with("approval-graph", approval_cfg());
            let checkpoint = Arc::new(InMemoryCheckpointStore::default());
            let state_store = Arc::new(MockAgentStateStore::new());
            let decide = Arc::new(std::sync::atomic::AtomicBool::new(false));

            let handler = RuntimeGraphNodeHandler::with_effects(
                graphs,
                checkpoint.clone(),
                state_store,
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
                tool_fn_ok(),
                supervisor_fn_noop(),
                approval_fn_toggle(decide.clone()),
            );
            let tenant = TenantContext::new("t", "e");

            // Call 1: the run drives to the approval node and parks.
            let first = handler
                .execute(
                    "t",
                    "e",
                    "approval-graph",
                    "sess-approve",
                    &json!({"user_text": "please refund"}),
                )
                .await
                .expect("a parked run must be Ok, not an Err");
            assert_ne!(
                first["terminated_by"].as_str(),
                Some("respond"),
                "a parked run must not be reported as a completed respond: {first:?}"
            );
            assert_ne!(
                first["terminated_by"].as_str(),
                Some("error"),
                "a parked run must not be reported as an error: {first:?}"
            );

            let rec = checkpoint
                .load(&tenant, "sess-approve__approval-graph")
                .await
                .expect("store accessible")
                .expect("base run id must be recorded");
            assert_eq!(
                rec.status,
                RunStatus::AwaitingInput,
                "persisted record must reflect the park"
            );

            // Call 2 (still undecided): must RESUME the base run id in
            // place, not fork "__2" (the bug this test guards against).
            let second = handler
                .execute(
                    "t",
                    "e",
                    "approval-graph",
                    "sess-approve",
                    &json!({"user_text": "still waiting"}),
                )
                .await
                .expect("a re-parked run must be Ok, not an Err");
            assert_ne!(second["terminated_by"].as_str(), Some("respond"));

            let forked = checkpoint
                .load(&tenant, "sess-approve__approval-graph__2")
                .await
                .expect("store accessible");
            assert!(
                forked.is_none(),
                "an AwaitingInput run must resume in place, not fork a fresh run id"
            );

            // Call 3: the decision has arrived — the SAME base run id
            // resolves via `executor.resume()`, not a fresh run.
            decide.store(true, Ordering::SeqCst);
            let third = handler
                .execute(
                    "t",
                    "e",
                    "approval-graph",
                    "sess-approve",
                    &json!({"user_text": "resolve"}),
                )
                .await
                .expect("execute should succeed once decided");
            assert_eq!(third["terminated_by"].as_str(), Some("respond"));

            let rec = checkpoint
                .load(&tenant, "sess-approve__approval-graph")
                .await
                .expect("store accessible")
                .expect("base run id must still be recorded");
            assert_eq!(
                rec.status,
                RunStatus::Succeeded,
                "the base run id must resolve once decided, not a forked one"
            );
        }

        #[tokio::test]
        async fn missing_graph_returns_structured_error_reply() {
            let handler = handler_with(
                provider_with("triage", triage_cfg(3)),
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
                tool_fn_ok(),
            );

            let out = handler
                .execute("t", "e", "unknown", "sess-1", &json!({"user_text": "hi"}))
                .await
                .expect("missing graph must NOT return Err");

            assert_eq!(out["terminated_by"].as_str(), Some("error"));
            assert!(
                out["reply"]
                    .as_str()
                    .unwrap_or("")
                    .to_ascii_lowercase()
                    .contains("available"),
                "reply should mention availability: {:?}",
                out["reply"]
            );
        }

        #[tokio::test]
        async fn missing_user_text_matches_agent_node_contract() {
            // agent_node.rs treats missing `user_text` as an empty string and
            // proceeds (never Err). Assert the same contract here.
            let handler = handler_with(
                provider_with("triage", triage_cfg(3)),
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
                tool_fn_ok(),
            );

            let out = handler
                .execute("t", "e", "triage", "sess-1", &json!({}))
                .await
                .expect("missing user_text must NOT return Err (matches agent_node)");

            assert_eq!(out["terminated_by"].as_str(), Some("respond"));
        }

        #[tokio::test]
        async fn iteration_cap_maps_to_error_envelope() {
            // maxIterations=1000 on the router → the executor's global
            // MAX_NODE_VISITS cap (64) trips first → IterationCap → "error".
            let handler = handler_with(
                provider_with("triage", triage_cfg(1000)),
                // never resolves → loops until the global visit cap
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), u32::MAX),
                tool_fn_ok(),
            );

            let out = handler
                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "loop"}))
                .await
                .expect("iteration cap must NOT return Err");

            assert_eq!(out["terminated_by"].as_str(), Some("error"));
            assert_ne!(
                out["reply"].as_str(),
                Some(SANITISED_ERROR_REPLY),
                "iteration cap should use a distinct reply"
            );
        }

        /// Regression test: flow session ids can contain `':'` (e.g. MS Teams
        /// channel correlation ids like `"msteams:thread:19xyz"`). The checkpoint
        /// store rejects keys that contain `':'`, so without sanitization every
        /// such graph run fails at save-time. [`derive_run_id`] must replace every
        /// `':'` with `'_'` before composing the checkpoint key.
        #[tokio::test]
        async fn colon_bearing_session_id_executes_successfully() {
            let handler = handler_with(
                provider_with("triage", triage_cfg(3)),
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
                tool_fn_ok(),
            );

            // Session id with multiple colons — typical of Teams thread ids.
            let out = handler
                .execute(
                    "t",
                    "e",
                    "triage",
                    "msteams:thread:19xyz",
                    &json!({"user_text": "hello"}),
                )
                .await
                .expect("colon-bearing session id must NOT return Err");

            assert_eq!(
                out["terminated_by"].as_str(),
                Some("respond"),
                "colon-bearing session id should complete successfully: {:?}",
                out
            );
        }

        // -------------------------------------------------------------------
        // LayeredGraphProvider tests
        // -------------------------------------------------------------------

        /// Provider that always returns the given error.
        struct ErrGraphProvider(fn() -> ConfigError);

        impl GraphConfigSource for ErrGraphProvider {
            fn graph_config<'a>(
                &'a self,
                _tenant: &'a TenantContext,
                _graph_id: &'a str,
            ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
                let e = (self.0)();
                Box::pin(async move { Err(e) })
            }
        }

        /// Fallback that panics if consulted — proves primary short-circuits.
        struct PanicGraphProvider;

        impl GraphConfigSource for PanicGraphProvider {
            fn graph_config<'a>(
                &'a self,
                _tenant: &'a TenantContext,
                _graph_id: &'a str,
            ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
                Box::pin(
                    async move { panic!("fallback must not be consulted when primary returns Ok") },
                )
            }
        }

        #[tokio::test]
        async fn layered_primary_ok_short_circuits_fallback() {
            let mut graphs = HashMap::new();
            graphs.insert("g".to_string(), triage_cfg(3));
            let primary = InMemoryGraphProvider::new(graphs);
            let layered = LayeredGraphProvider::new(primary, PanicGraphProvider);
            let tc = TenantContext::new("t", "e");
            // If fallback were consulted, PanicGraphProvider panics and fails this.
            let cfg = layered.graph_config(&tc, "g").await.unwrap();
            assert_eq!(cfg.graph.entry, "agent");
        }

        #[tokio::test]
        async fn layered_falls_back_on_not_found() {
            let mut graphs = HashMap::new();
            graphs.insert("g".to_string(), triage_cfg(3));
            let fb = InMemoryGraphProvider::new(graphs);
            let layered = LayeredGraphProvider::new(
                ErrGraphProvider(|| ConfigError::AgentNotFound("g".into())),
                fb,
            );
            let tc = TenantContext::new("t", "e");
            let cfg = layered.graph_config(&tc, "g").await.unwrap();
            assert_eq!(cfg.graph.entry, "agent");
        }

        #[tokio::test]
        async fn layered_falls_back_on_internal() {
            let mut graphs = HashMap::new();
            graphs.insert("g".to_string(), triage_cfg(3));
            let fb = InMemoryGraphProvider::new(graphs);
            let layered = LayeredGraphProvider::new(
                ErrGraphProvider(|| ConfigError::Internal("down".into())),
                fb,
            );
            let tc = TenantContext::new("t", "e");
            let cfg = layered.graph_config(&tc, "g").await.unwrap();
            assert_eq!(cfg.graph.entry, "agent");
        }

        #[tokio::test]
        async fn layered_propagates_misconfigured_without_fallback() {
            let fb = InMemoryGraphProvider::new(HashMap::new());
            let layered = LayeredGraphProvider::new(
                ErrGraphProvider(|| ConfigError::Misconfigured("bad schema".into())),
                fb,
            );
            let tc = TenantContext::new("t", "e");
            let result = layered.graph_config(&tc, "g").await;
            assert!(
                matches!(result, Err(ConfigError::Misconfigured(_))),
                "Misconfigured must NOT fall back: {result:?}"
            );
        }

        // -------------------------------------------------------------------
        // graph_registry_from_env tests
        // -------------------------------------------------------------------

        #[test]
        #[serial_test::serial]
        #[allow(unsafe_code)]
        fn graph_registry_from_env_requires_both_vars() {
            // SAFETY: #[serial] serializes env-mutating tests; vars cleaned up.
            unsafe {
                std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
                std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
            }
            assert!(super::graph_registry_from_env().is_none());

            unsafe {
                std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
            }
            assert!(
                super::graph_registry_from_env().is_none(),
                "endpoint alone is not enough"
            );

            unsafe {
                std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
            }
            assert!(super::graph_registry_from_env().is_some());

            // Token-alone (no endpoint) must also be None.
            unsafe {
                std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
            }
            assert!(
                super::graph_registry_from_env().is_none(),
                "token alone is not enough"
            );

            unsafe {
                std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
            }
        }

        // -------------------------------------------------------------------
        // Supervisor fixture
        // -------------------------------------------------------------------

        /// Supervisor graph (schemaVersion 2): sup → agent_billing / agent_tech →
        /// router → respond. Mirrors the aw-runtime `supervisor_json()` fixture
        /// (which is `pub(crate)` to that crate and cannot be imported here).
        ///
        /// Topology:
        ///   sup (supervisor: routes=[billing, tech])
        ///    ├─[billing]─► agent_billing ─► router_billing ─┬─[loop]──► sup
        ///    │                                               └─[resolved]─► respond
        ///    └─[tech]────► agent_tech ───► router_tech    ─┬─[loop]──► sup
        ///                                                   └─[resolved]─► respond
        fn supervisor_graph_json() -> String {
            json!({
                "schemaVersion": 2,
                "entry": "sup",
                "nodes": [
                    {
                        "id": "sup",
                        "kind": "supervisor",
                        "systemPrompt": "Route the request to the correct specialist.",
                        "model": "gpt-4o-mini",
                        "routes": [
                            {"branch": "billing", "description": "Billing and payment questions"},
                            {"branch": "tech",    "description": "Technical support issues"}
                        ]
                    },
                    {"id": "agent_billing", "kind": "agent", "systemPrompt": "Billing.", "model": "gpt-4o-mini", "tools": []},
                    {"id": "router_billing", "kind": "router", "maxIterations": 2},
                    {"id": "agent_tech",    "kind": "agent", "systemPrompt": "Tech.",    "model": "gpt-4o-mini", "tools": []},
                    {"id": "router_tech",   "kind": "router", "maxIterations": 2},
                    {"id": "respond",       "kind": "respond"}
                ],
                "edges": [
                    {"from": "sup",           "to": "agent_billing",  "branch": "billing"},
                    {"from": "sup",           "to": "agent_tech",     "branch": "tech"},
                    {"from": "agent_billing", "to": "router_billing"},
                    {"from": "router_billing","to": "agent_billing",  "branch": "loop"},
                    {"from": "router_billing","to": "respond",        "branch": "resolved"},
                    {"from": "agent_tech",    "to": "router_tech"},
                    {"from": "router_tech",   "to": "agent_tech",     "branch": "loop"},
                    {"from": "router_tech",   "to": "respond",        "branch": "resolved"}
                ]
            })
            .to_string()
        }

        fn supervisor_cfg() -> GraphConfig {
            GraphConfig::from_json(&supervisor_graph_json()).expect("supervisor fixture valid")
        }

        /// Helpers for building [`SupervisorRoute`] values inline.
        fn route(branch: &str, description: &str) -> SupervisorRoute {
            SupervisorRoute {
                branch: branch.to_string(),
                description: description.to_string(),
            }
        }

        /// Build a supervisor fn that always routes to `fixed_branch`.
        fn supervisor_fn_routes_to(fixed_branch: &str) -> SupervisorFn {
            let branch = fixed_branch.to_string();
            Arc::new(move |_req: SupervisorRequest| {
                let branch = branch.clone();
                Box::pin(async move {
                    Ok(SupervisorResult {
                        branch: branch.clone(),
                        raw_reply: format!("I'll route this. [[ROUTE:{branch}]] Done."),
                    })
                })
            })
        }

        // Build a handler wired with the given supervisor fn (and a no-op agent
        // that always resolves immediately).
        fn supervisor_handler(
            graphs: Arc<dyn GraphConfigSource>,
            supervisor: SupervisorFn,
        ) -> RuntimeGraphNodeHandler {
            let agent: AgentTurnFn = agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1);
            RuntimeGraphNodeHandler::with_effects(
                graphs,
                Arc::new(InMemoryCheckpointStore::default()),
                Arc::new(MockAgentStateStore::new()),
                agent,
                tool_fn_ok(),
                supervisor,
                approval_fn_awaiting(),
            )
        }

        // -------------------------------------------------------------------
        // parse_route_branch unit tests
        // -------------------------------------------------------------------

        /// Two routes for the parse tests.
        fn billing_tech_routes() -> Vec<SupervisorRoute> {
            vec![
                route("billing", "Billing and payment questions"),
                route("tech", "Technical support issues"),
            ]
        }

        #[test]
        fn parse_route_extracts_billing_from_reply() {
            // Standard case: sentinel embedded in a longer reply.
            let reply = "I analysed the message. [[ROUTE:billing]] Go ahead.";
            let result = parse_route_branch(reply, &billing_tech_routes());
            assert_eq!(result, Some("billing".to_string()));
        }

        #[test]
        fn parse_route_case_insensitive_prefix() {
            // The prefix [[ROUTE: is matched case-insensitively; the extracted
            // branch label must still match the declared route exactly
            // (case-sensitive per spec).
            let reply = "[[route:tech]] is the answer";
            let result = parse_route_branch(reply, &billing_tech_routes());
            assert_eq!(result, Some("tech".to_string()));
        }

        #[test]
        fn parse_route_missing_sentinel_returns_none() {
            // No sentinel at all → None (caller's unwrap_or_else picks first route).
            let reply = "I think billing would be best here.";
            let result = parse_route_branch(reply, &billing_tech_routes());
            assert_eq!(result, None);
        }

        #[test]
        fn parse_route_unknown_branch_returns_none() {
            // Sentinel present but branch label does not match any declared route.
            let reply = "[[ROUTE:unknown_branch]] routing";
            let result = parse_route_branch(reply, &billing_tech_routes());
            assert_eq!(result, None);
        }

        #[test]
        fn parse_route_multiple_sentinels_uses_first() {
            // When multiple sentinels are present the function uses the FIRST one
            // (find on the lowercased string returns the first occurrence).
            let reply = "[[ROUTE:billing]] or [[ROUTE:tech]]";
            let result = parse_route_branch(reply, &billing_tech_routes());
            assert_eq!(
                result,
                Some("billing".to_string()),
                "multiple sentinels: first occurrence wins"
            );
        }

        #[test]
        fn parse_route_branch_label_whitespace_trimmed() {
            // Whitespace around the branch label inside the sentinel is trimmed.
            let reply = "[[ROUTE:  billing  ]]";
            let result = parse_route_branch(reply, &billing_tech_routes());
            assert_eq!(result, Some("billing".to_string()));
        }

        // -------------------------------------------------------------------
        // strip_route_sentinel unit tests
        // -------------------------------------------------------------------

        #[test]
        fn strip_sentinel_removes_token_leaves_rest() {
            let reply = "I'll route this. [[ROUTE:billing]] Proceeding.";
            let stripped = strip_route_sentinel(reply);
            assert!(
                !stripped.contains("[[ROUTE:billing]]"),
                "sentinel must be removed: {stripped:?}"
            );
            assert!(
                stripped.contains("Proceeding"),
                "text after sentinel must survive: {stripped:?}"
            );
        }

        #[test]
        fn strip_sentinel_no_sentinel_returns_trimmed() {
            let reply = "  No routing needed here.  ";
            let stripped = strip_route_sentinel(reply);
            assert_eq!(stripped, "No routing needed here.");
        }

        #[test]
        fn strip_sentinel_case_insensitive_removal() {
            let reply = "Decision: [[route:tech]] done.";
            let stripped = strip_route_sentinel(reply);
            assert!(
                !stripped.to_ascii_lowercase().contains("[[route:"),
                "sentinel must be stripped case-insensitively: {stripped:?}"
            );
        }

        #[test]
        fn strip_sentinel_only_first_occurrence_removed() {
            // If two sentinels appear, only the first is stripped.
            let reply = "[[ROUTE:billing]] first [[ROUTE:tech]] second";
            let stripped = strip_route_sentinel(reply);
            assert!(
                !stripped.contains("[[ROUTE:billing]]"),
                "first sentinel must be gone: {stripped:?}"
            );
            // The second sentinel remains (we only strip the first occurrence).
            assert!(
                stripped.contains("[[ROUTE:tech]]"),
                "second sentinel must remain: {stripped:?}"
            );
        }

        // -------------------------------------------------------------------
        // Fallback: parse_route_branch None → first-route fallback
        // -------------------------------------------------------------------

        #[test]
        fn parse_route_none_documents_fallback_to_first_route() {
            // This is a pure-fn test of the fallback path used in
            // `run_one_supervisor_turn` via `unwrap_or_else(|| first_route)`.
            // When parse_route_branch returns None, the build_supervisor closure
            // picks req.routes.first().branch as the fallback.
            let routes = billing_tech_routes();
            let garbage = "absolutely no routing sentinel here";
            let parsed = parse_route_branch(garbage, &routes);
            assert_eq!(parsed, None, "no sentinel → None from parser");

            // Simulate the fallback: first route is "billing".
            let fallback = parsed
                .unwrap_or_else(|| routes.first().map(|r| r.branch.clone()).unwrap_or_default());
            assert_eq!(
                fallback, "billing",
                "None → first route 'billing' as fallback"
            );
        }

        // -------------------------------------------------------------------
        // Handler-level supervisor routing tests
        // -------------------------------------------------------------------

        #[tokio::test]
        async fn supervisor_routes_to_billing_returns_respond_envelope() {
            // The mock supervisor always picks "billing". The billing agent
            // resolves immediately. Expect terminated_by="respond" and a
            // non-empty reply.
            let handler = supervisor_handler(
                provider_with("sup_graph", supervisor_cfg()),
                supervisor_fn_routes_to("billing"),
            );

            let out = handler
                .execute(
                    "t",
                    "e",
                    "sup_graph",
                    "sess-sup-1",
                    &json!({"user_text": "I need billing help"}),
                )
                .await
                .expect("supervisor execute must not Err");

            assert_eq!(
                out["terminated_by"].as_str(),
                Some("respond"),
                "billing path must terminate at respond: {out:?}"
            );
            assert!(
                out["reply"].as_str().is_some_and(|r| !r.is_empty()),
                "reply must be non-empty: {out:?}"
            );
            assert!(
                out["trail"].as_array().is_some_and(|t| !t.is_empty()),
                "trail must be non-empty: {out:?}"
            );
        }

        #[tokio::test]
        async fn supervisor_routes_to_tech_returns_respond_envelope() {
            // Same topology, supervisor picks "tech" branch instead.
            let handler = supervisor_handler(
                provider_with("sup_graph", supervisor_cfg()),
                supervisor_fn_routes_to("tech"),
            );

            let out = handler
                .execute(
                    "t",
                    "e",
                    "sup_graph",
                    "sess-sup-2",
                    &json!({"user_text": "my device is broken"}),
                )
                .await
                .expect("supervisor tech-route execute must not Err");

            assert_eq!(
                out["terminated_by"].as_str(),
                Some("respond"),
                "tech path must terminate at respond: {out:?}"
            );
        }

        #[tokio::test]
        async fn supervisor_fallback_on_missing_sentinel_still_completes() {
            // A supervisor fn that returns a raw_reply with NO [[ROUTE:]] sentinel.
            // The build_supervisor closure maps None→first-route ("billing").
            // The handler-level execute() must still complete (not Err).
            //
            // Because with_effects injects the supervisor fn directly (bypassing
            // build_supervisor's parse), we simulate the fallback by having the
            // fn return the first route explicitly — matching what build_supervisor
            // does in production via parse_route_branch(...)
            //   .unwrap_or_else(|| routes.first().branch).
            // The pure-fn fallback path is fully covered by
            // `parse_route_none_documents_fallback_to_first_route`.
            let supervisor: SupervisorFn = Arc::new(|_req: SupervisorRequest| {
                // No sentinel in raw_reply; we return first-route directly as
                // the mock of the fallback behaviour.
                Box::pin(async move {
                    Ok(SupervisorResult {
                        branch: "billing".to_string(),
                        raw_reply: "I think billing is right.".to_string(),
                    })
                })
            });

            let handler =
                supervisor_handler(provider_with("sup_graph", supervisor_cfg()), supervisor);

            let out = handler
                .execute(
                    "t",
                    "e",
                    "sup_graph",
                    "sess-sup-3",
                    &json!({"user_text": "help me"}),
                )
                .await
                .expect("fallback supervisor must not Err");

            assert_eq!(
                out["terminated_by"].as_str(),
                Some("respond"),
                "fallback path must still reach respond: {out:?}"
            );
        }

        // -------------------------------------------------------------------
        // EPIC-B B-3b Task 2: `AgentAuditObserver` injection at the graph
        // turn `.step` seam (`run_agent_step`, shared by `run_one_agent_turn`
        // and `run_one_supervisor_turn`).
        // -------------------------------------------------------------------

        fn real_tenant_ctx(tenant: &str, env: &str) -> greentic_types::TenantCtx {
            greentic_types::TenantCtx::new(
                greentic_types::EnvId::try_from(env).expect("valid env id"),
                greentic_types::TenantId::try_from(tenant).expect("valid tenant id"),
            )
        }

        /// Build an [`AgentRuntime`] scripted to make one `remember` (host
        /// built-in short-term-memory) tool call before replying "done".
        /// Mirrors `agent_node`'s `runtime_with_scripted_remember_call`
        /// fixture — the host built-in path fires
        /// `StepObserver::on_tool_call`/`on_tool_result` without needing a
        /// real WASM extension dispatch, so it is the cheapest way to drive a
        /// genuine tool call through the seam.
        ///
        /// `run_one_agent_turn`/`run_one_supervisor_turn` hardcode
        /// `tools: vec![]` + `memory: None` on their ephemeral per-visit
        /// `AgentConfig` (graph-node agents have no tool/memory access in v1
        /// scope — see the `TODO(guardrail)` comment at each call site), so
        /// no tool call can ever reach the observer through those two
        /// functions today. This fixture instead drives the shared
        /// `run_agent_step` seam directly with its own memory-enabled
        /// config — the exact same `match audit_sink { .. }` code both turn
        /// functions delegate to — so the real-tenant wiring is verified
        /// against genuine tool-call traffic rather than asserted in the
        /// abstract.
        fn agent_runtime_with_scripted_remember_call(
            tenant: &TenantContext,
            agent_id: &str,
        ) -> AgentRuntime {
            use greentic_aw_runtime::cost::MockTokenMeter;
            use greentic_aw_runtime::llm::LlmResponse;
            use greentic_aw_runtime::mock::{MockLlmBackend, MockTelemetry, NoopToolLedger};
            use greentic_aw_runtime::state::ToolCallRecord;
            use greentic_aw_runtime::{InMemoryMemoryProvider, MemoryProviderRef, MemorySettings};

            let llm = Arc::new(MockLlmBackend::new(vec![
                Ok(LlmResponse {
                    content: None,
                    tool_calls: vec![ToolCallRecord {
                        call_id: "c1".into(),
                        extension_id: "host".into(),
                        tool_name: "remember".into(),
                        args: json!({"key": "k", "value": "v"}),
                    }],
                    tokens_in: 1,
                    tokens_out: 1,
                }),
                Ok(LlmResponse {
                    content: Some("done".into()),
                    tool_calls: vec![],
                    tokens_in: 1,
                    tokens_out: 1,
                }),
            ]));

            let cfg = AgentConfig {
                agent_id: agent_id.to_string(),
                system_prompt: "test".into(),
                tools: vec![],
                guardrails: vec![],
                llm: LlmProviderRef {
                    provider: "openai".into(),
                    model: "gpt-4o-mini".into(),
                    credential_ref: None,
                },
                limits: AgentLimits::default(),
                memory: Some(MemorySettings {
                    short_term: Some(MemoryProviderRef {
                        provider: "inmemory".into(),
                        capability: "cap://memory/short-term".into(),
                        params: Default::default(),
                        credential_ref: None,
                    }),
                    long_term: None,
                }),
                knowledge: None,
                conversational: false,
                opening_message: None,
                on_text_while_parked: Default::default(),
            };
            let mut provider = InMemoryConfigProvider::new();
            provider.insert(tenant, agent_id, cfg);

            AgentRuntime::new(
                Arc::new(provider),
                Arc::new(MockAgentStateStore::new()),
                Arc::new(ExtensionRuntime::for_test().unwrap()),
                llm,
                Arc::new(MockTelemetry::new()),
                Arc::new(MockTokenMeter::new(0)),
                Arc::new(NoopToolLedger),
                None,
            )
            .with_short_term_memory(Arc::new(InMemoryMemoryProvider::new()))
        }

        #[tokio::test]
        async fn run_agent_step_with_audit_sink_enqueues_events_under_real_tenant_not_state_tenant()
        {
            // The SYNTHETIC state tenant every graph-node turn uses today —
            // must NOT leak into the audit subject.
            let state_tenant = TenantContext::new("graph", "run");
            let agent_id = "graph.agent-1";
            let session_id = "graph__agent-1";
            let runtime = agent_runtime_with_scripted_remember_call(&state_tenant, agent_id);

            let (tx, mut rx) = tokio::sync::mpsc::channel(16);
            let sink = AuditSink::from_sender(tx);
            let real_tenant = real_tenant_ctx("acme", "prod");

            let input = AgentInput {
                text: String::new(),
                ..Default::default()
            };
            let out = run_agent_step(
                &runtime,
                state_tenant.clone(),
                session_id,
                agent_id,
                input,
                Some(&sink),
                &real_tenant,
            )
            .await
            .expect("step should succeed");
            assert_eq!(out.reply, "done");

            let (subject, bytes) = rx.try_recv().expect("tool_call audit event enqueued");
            assert_eq!(
                subject, "audit.acme.agent.tool_call",
                "audit subject must carry the REAL tenant (\"acme\"), not the synthetic state tenant (\"graph\")"
            );
            let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
            assert_eq!(value["payload"]["tool"], json!("remember"));
            assert_eq!(value["payload"]["agent_id"], json!(agent_id));

            let (subject, bytes) = rx.try_recv().expect("tool_result audit event enqueued");
            assert_eq!(subject, "audit.acme.agent.tool_result");
            let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
            assert_eq!(value["payload"]["tool"], json!("remember"));

            assert!(
                rx.try_recv().is_err(),
                "exactly two audit events enqueued (one tool_call, one tool_result)"
            );
        }

        #[tokio::test]
        async fn run_agent_step_without_audit_sink_uses_plain_step_path_unchanged() {
            // Same scripted tool call as the audited test above, but no audit
            // sink at all — proves the "off" branch (runtime.step, no
            // observer constructed) still dispatches the tool call and
            // returns the same reply, exactly as it did before
            // AgentAuditObserver existed.
            let state_tenant = TenantContext::new("graph", "run");
            let agent_id = "graph.agent-1";
            let session_id = "graph__agent-1";
            let runtime = agent_runtime_with_scripted_remember_call(&state_tenant, agent_id);
            let real_tenant = real_tenant_ctx("acme", "prod");

            let input = AgentInput {
                text: String::new(),
                ..Default::default()
            };
            let out = run_agent_step(
                &runtime,
                state_tenant.clone(),
                session_id,
                agent_id,
                input,
                None,
                &real_tenant,
            )
            .await
            .expect("step should succeed");

            assert_eq!(out.reply, "done");
        }

        /// Minimal [`MockLlmBackend`] that always replies with `reply` and no
        /// tool calls — enough to drive `run_one_agent_turn`/
        /// `run_one_supervisor_turn` end to end without needing tool access
        /// (which their hardcoded ephemeral `AgentConfig` does not grant).
        fn plain_reply_llm(reply: &str) -> Arc<dyn LlmBackend> {
            use greentic_aw_runtime::llm::LlmResponse;
            use greentic_aw_runtime::mock::MockLlmBackend;

            Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
                content: Some(reply.to_string()),
                tool_calls: vec![],
                tokens_in: 1,
                tokens_out: 1,
            })]))
        }

        fn agent_turn_request(node_id: &str, system_prompt: &str) -> AgentTurnRequest {
            AgentTurnRequest {
                node_id: node_id.to_string(),
                system_prompt: system_prompt.to_string(),
                model: "gpt-4o-mini".to_string(),
                state: GraphRunState::default(),
                provider: None,
                tools: vec![],
                agent_ref: None,
                inherit_from: None,
            }
        }

        /// Shared effect Arcs for `run_one_agent_turn`/`run_one_supervisor_turn`
        /// test calls: state store, ext runtime, telemetry, token meter, ledger.
        type AgentTurnEffects = (
            Arc<dyn AgentStateStore>,
            Arc<ExtensionRuntime>,
            Arc<dyn Telemetry>,
            Arc<dyn TokenMeter>,
            Arc<dyn ToolLedger>,
        );

        fn agent_turn_effects() -> AgentTurnEffects {
            use greentic_aw_runtime::cost::MockTokenMeter;
            use greentic_aw_runtime::mock::{MockTelemetry, NoopToolLedger};

            (
                Arc::new(MockAgentStateStore::new()),
                Arc::new(ExtensionRuntime::for_test().unwrap()),
                Arc::new(MockTelemetry::new()),
                Arc::new(MockTokenMeter::new(0)),
                Arc::new(NoopToolLedger),
            )
        }

        #[tokio::test]
        async fn run_one_agent_turn_without_audit_sink_completes_unchanged() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");

            let result = run_one_agent_turn(
                agent_turn_request("agent", "You triage."),
                state_store,
                ext_runtime,
                plain_reply_llm("all good [[RESOLVED]]"),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect("turn should succeed");

            assert!(result.resolved);
            assert_eq!(result.reply, "all good");
        }

        #[tokio::test]
        async fn run_one_agent_turn_with_audit_sink_completes_same_reply_as_without() {
            // `agent_turn_request` declares no tools, and the mock LLM never
            // emits tool calls, so no audit event is expected here either —
            // this test guards that routing through `step_with_observer` does
            // not change the turn's outcome. Genuine tool-call
            // audit-under-real-tenant coverage lives in
            // `run_agent_step_with_audit_sink_enqueues_events_under_real_tenant_not_state_tenant`.
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let (tx, mut rx) = tokio::sync::mpsc::channel(16);
            let sink = AuditSink::from_sender(tx);
            let real_tenant = real_tenant_ctx("acme", "prod");

            let result = run_one_agent_turn(
                agent_turn_request("agent", "You triage."),
                state_store,
                ext_runtime,
                plain_reply_llm("all good [[RESOLVED]]"),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(HashMap::new()),
                Some(&sink),
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect("turn should succeed");

            assert!(result.resolved);
            assert_eq!(result.reply, "all good");
            assert!(
                rx.try_recv().is_err(),
                "no tool call happens on this path, so no audit event is expected"
            );
        }

        /// Wiring assertion (Task 2): a request whose `tools` field declares a
        /// well-formed ref reaches the ephemeral per-visit `AgentConfig`
        /// unharmed — the turn still completes (the runtime only warns, never
        /// fails, on tools that don't resolve against the test `ExtensionRuntime`
        /// — see `preflight_warn_tools`/`missing_tools` in `greentic-aw-runtime`).
        /// `map_tool_refs`/`parse_tool_ref` above cover the mapping itself;
        /// this proves `run_one_agent_turn` actually calls it instead of the
        /// old hardcoded `tools: vec![]`.
        #[tokio::test]
        async fn run_one_agent_turn_with_declared_tools_still_completes() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");

            let mut req = agent_turn_request("agent", "You triage.");
            req.tools = vec!["myext/dothing".to_string()];

            let result = run_one_agent_turn(
                req,
                state_store,
                ext_runtime,
                plain_reply_llm("all good [[RESOLVED]]"),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect("turn should succeed even with a declared-but-unregistered tool");

            assert!(result.resolved);
            assert_eq!(result.reply, "all good");
        }

        // -------------------------------------------------------------------
        // SP1 Task 3: `agent_ref` resolution
        // -------------------------------------------------------------------

        /// A published-agent config with a distinctive `system_prompt` marker
        /// ("FAQ-BOT") plus non-empty `memory`/`knowledge` bindings, standing
        /// in for a real `merged_agents` entry resolved by `agent_ref`.
        fn faq_bot_agent_config() -> AgentConfig {
            use greentic_aw_runtime::config::KnowledgeSettings;
            use greentic_aw_runtime::{MemoryProviderRef, MemorySettings};

            AgentConfig {
                agent_id: "faq".to_string(),
                system_prompt: "You are FAQ-BOT. Answer only from the knowledge base.".to_string(),
                tools: vec![],
                guardrails: vec![],
                llm: LlmProviderRef {
                    provider: "openai".to_string(),
                    model: "gpt-4o-mini".to_string(),
                    credential_ref: None,
                },
                limits: AgentLimits::default(),
                memory: Some(MemorySettings {
                    short_term: Some(MemoryProviderRef {
                        provider: "inmemory".to_string(),
                        capability: "cap://memory/short-term".to_string(),
                        params: Default::default(),
                        credential_ref: None,
                    }),
                    long_term: None,
                }),
                knowledge: Some(KnowledgeSettings {
                    knowledge: Some(MemoryProviderRef {
                        provider: "chronicle".to_string(),
                        capability: "cap://dw.knowledge".to_string(),
                        params: Default::default(),
                        credential_ref: None,
                    }),
                    embedding: None,
                    top_k: 5,
                }),
                conversational: false,
                opening_message: None,
                on_text_while_parked: Default::default(),
            }
        }

        /// Like [`plain_reply_llm`] but returns the concrete
        /// [`greentic_aw_runtime::mock::MockLlmBackend`] (not erased to
        /// `Arc<dyn LlmBackend>`) so the test can inspect `seen_system_prompts`
        /// after the turn completes.
        fn recording_llm(reply: &str) -> Arc<greentic_aw_runtime::mock::MockLlmBackend> {
            use greentic_aw_runtime::llm::LlmResponse;
            use greentic_aw_runtime::mock::MockLlmBackend;

            Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
                content: Some(reply.to_string()),
                tool_calls: vec![],
                tokens_in: 1,
                tokens_out: 1,
            })]))
        }

        #[test]
        fn resolve_turn_config_agent_ref_present_returns_full_config_from_map() {
            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), faq_bot_agent_config());

            let mut req = agent_turn_request("s", "inline prompt, should be ignored");
            req.agent_ref = Some("faq".to_string());

            let cfg = resolve_turn_config(&req, &merged, "graph.s").expect("resolves");

            assert!(cfg.system_prompt.contains("FAQ-BOT"));
            assert!(cfg.memory.is_some(), "memory carried through unstripped");
            assert!(
                cfg.knowledge.is_some(),
                "knowledge carried through unstripped"
            );
        }

        #[test]
        fn resolve_turn_config_agent_ref_none_returns_stripped_inline_config() {
            let merged = HashMap::new();
            let req = agent_turn_request("s", "You triage.");

            let cfg = resolve_turn_config(&req, &merged, "graph.s").expect("resolves");

            assert_eq!(cfg.system_prompt, "You triage.");
            assert_eq!(cfg.agent_id, "graph.s");
            assert!(cfg.memory.is_none());
            assert!(cfg.knowledge.is_none());
            assert!(cfg.guardrails.is_empty());
        }

        #[test]
        fn resolve_turn_config_agent_ref_missing_returns_err() {
            let merged = HashMap::new();
            let mut req = agent_turn_request("s", "inline prompt");
            req.agent_ref = Some("missing".to_string());

            let err = resolve_turn_config(&req, &merged, "graph.s").expect_err("must error");

            assert!(
                err.to_string()
                    .contains("referenced agent 'missing' not found"),
                "unexpected error message: {err}"
            );
        }

        #[tokio::test]
        async fn run_one_agent_turn_with_agent_ref_uses_referenced_config_system_prompt() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");

            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), faq_bot_agent_config());

            let mut req = agent_turn_request("s", "inline prompt, should NOT be used");
            req.agent_ref = Some("faq".to_string());

            let llm = recording_llm("all good [[RESOLVED]]");

            let result = run_one_agent_turn(
                req,
                state_store,
                ext_runtime,
                llm.clone(),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(merged),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect("turn should succeed");

            assert!(result.resolved);
            assert_eq!(result.reply, "all good");

            let seen = llm.seen_system_prompts.lock().expect("lock poisoned");
            assert_eq!(seen.len(), 1);
            assert!(
                seen[0].contains("FAQ-BOT"),
                "expected the referenced agent's system prompt, got: {}",
                seen[0]
            );
            assert!(
                !seen[0].contains("should NOT be used"),
                "the node's inline system prompt must not be used when agent_ref is set"
            );
        }

        #[tokio::test]
        async fn run_one_agent_turn_without_agent_ref_uses_inline_system_prompt() {
            // Regression: agent_ref = None stays byte-unchanged — the node's
            // own inline system_prompt is what the LLM sees, not any entry
            // from `merged_agents` (even when one happens to exist).
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");

            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), faq_bot_agent_config());

            let req = agent_turn_request("s", "You triage inline.");
            let llm = recording_llm("all good [[RESOLVED]]");

            let result = run_one_agent_turn(
                req,
                state_store,
                ext_runtime,
                llm.clone(),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(merged),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect("turn should succeed");

            assert!(result.resolved);

            let seen = llm.seen_system_prompts.lock().expect("lock poisoned");
            assert_eq!(seen.len(), 1);
            assert!(seen[0].contains("You triage inline."));
            assert!(!seen[0].contains("FAQ-BOT"));
        }

        #[tokio::test]
        async fn run_one_agent_turn_with_missing_agent_ref_errors() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");

            let mut req = agent_turn_request("s", "inline prompt");
            req.agent_ref = Some("missing".to_string());

            let err = run_one_agent_turn(
                req,
                state_store,
                ext_runtime,
                plain_reply_llm("unused"),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect_err("must error when agent_ref doesn't resolve");

            assert!(
                err.to_string()
                    .contains("referenced agent 'missing' not found"),
                "unexpected error message: {err}"
            );
        }

        /// The specialist case: `inherit_from` adopts the worker's capability
        /// surface WITHOUT overwriting the node's own prompt. If this ever
        /// regressed to `agent_ref` semantics, every specialist in a generated
        /// graph would collapse into an identical copy of its parent.
        #[test]
        fn inherit_from_keeps_the_node_prompt_and_adopts_the_capability_surface() {
            use greentic_aw_runtime::config::GuardrailRef;

            let mut parent = faq_bot_agent_config();
            parent.guardrails = vec![GuardrailRef {
                cap_id: "greentic:guardrail/pii".to_string(),
                offer_id: None,
                config: serde_json::json!({}),
                mode: Default::default(),
            }];
            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), parent);

            let mut req = agent_turn_request("spec-billing", "You handle billing only.");
            req.inherit_from = Some("faq".to_string());

            let cfg = resolve_turn_config(&req, &merged, "graph.spec-billing")
                .expect("a resolvable inherit_from must succeed");

            assert_eq!(
                cfg.system_prompt, "You handle billing only.",
                "the specialist keeps its OWN prompt — this is the whole point"
            );
            assert_eq!(cfg.guardrails.len(), 1, "guardrails are inherited");
            assert!(cfg.memory.is_some(), "memory is inherited");
            assert!(cfg.knowledge.is_some(), "knowledge is inherited");
        }

        /// An unresolvable `inherit_from` fails rather than running stripped.
        #[test]
        fn inherit_from_unresolvable_fails_rather_than_running_stripped() {
            let merged = HashMap::new();
            let mut req = agent_turn_request("spec", "Specialist prompt.");
            req.inherit_from = Some("ghost".to_string());

            let err = resolve_turn_config(&req, &merged, "graph.spec")
                .expect_err("an unknown inherit_from must not silently succeed");
            let msg = err.to_string();
            assert!(
                msg.contains("ghost") && msg.contains("refusing to run"),
                "error should name the id and say it refused: {msg}"
            );
        }

        /// `agent_ref` still wins when both are set — it already takes
        /// everything, including the prompt.
        #[test]
        fn agent_ref_takes_precedence_over_inherit_from() {
            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), faq_bot_agent_config());

            let mut req = agent_turn_request("spec", "Specialist prompt.");
            req.agent_ref = Some("faq".to_string());
            req.inherit_from = Some("faq".to_string());

            let cfg = resolve_turn_config(&req, &merged, "graph.spec").expect("resolvable");
            assert_eq!(
                cfg.system_prompt, "You are FAQ-BOT. Answer only from the knowledge base.",
                "agent_ref adopts the referenced prompt wholesale"
            );
        }

        /// A supervisor with no `agent_ref` keeps today's behaviour: no
        /// guardrails, and nothing fails.
        #[test]
        fn supervisor_without_agent_ref_resolves_no_guardrails() {
            let merged = HashMap::new();
            let got = resolve_supervisor_guardrails(None, &merged, "router")
                .expect("absent agent_ref is not an error");
            assert!(got.is_empty());
        }

        /// The point of the whole change: a supervisor pointed at its worker
        /// runs under that worker's guardrails.
        #[test]
        fn supervisor_with_agent_ref_inherits_the_parent_guardrails() {
            use greentic_aw_runtime::config::GuardrailRef;

            let mut parent = faq_bot_agent_config();
            parent.guardrails = vec![GuardrailRef {
                cap_id: "greentic:guardrail/pii".to_string(),
                offer_id: None,
                config: serde_json::json!({}),
                mode: Default::default(),
            }];
            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), parent);

            let got = resolve_supervisor_guardrails(Some("faq"), &merged, "router")
                .expect("a resolvable agent_ref must succeed");
            assert_eq!(got.len(), 1);
            assert_eq!(got[0].cap_id, "greentic:guardrail/pii");
        }

        /// An unresolvable `agent_ref` FAILS rather than routing unguarded — a
        /// supervisor believed to be protected but running bare is exactly what
        /// this inheritance exists to prevent.
        #[test]
        fn supervisor_with_unresolvable_agent_ref_fails_rather_than_routing_bare() {
            let merged = HashMap::new();
            let err = resolve_supervisor_guardrails(Some("ghost"), &merged, "router")
                .expect_err("an unknown agent_ref must not silently succeed");
            let msg = err.to_string();
            assert!(
                msg.contains("ghost") && msg.contains("refusing to route"),
                "error should name the id and say it refused: {msg}"
            );
        }

        /// A supervisor inherits guardrails ONLY — the referenced worker's
        /// memory and knowledge are deliberately left behind. It routes, it
        /// does not work.
        #[test]
        fn supervisor_inherits_guardrails_but_not_memory_or_knowledge() {
            use greentic_aw_runtime::config::GuardrailRef;

            let mut parent = faq_bot_agent_config();
            parent.guardrails = vec![GuardrailRef {
                cap_id: "greentic:guardrail/pii".to_string(),
                offer_id: None,
                config: serde_json::json!({}),
                mode: Default::default(),
            }];
            assert!(parent.memory.is_some(), "fixture should carry memory");
            assert!(parent.knowledge.is_some(), "fixture should carry knowledge");

            let mut merged = HashMap::new();
            merged.insert("faq".to_string(), parent);

            let got =
                resolve_supervisor_guardrails(Some("faq"), &merged, "router").expect("resolvable");
            assert_eq!(got.len(), 1, "guardrails come across");
        }

        #[tokio::test]
        async fn run_one_supervisor_turn_without_audit_sink_completes_unchanged() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");
            let routes = vec![
                SupervisorRoute {
                    branch: "billing".into(),
                    description: "Billing questions".into(),
                },
                SupervisorRoute {
                    branch: "tech".into(),
                    description: "Technical support".into(),
                },
            ];
            let req = SupervisorRequest {
                node_id: "router".to_string(),
                system_prompt: "Route the user.".to_string(),
                model: "gpt-4o-mini".to_string(),
                routes,
                state: GraphRunState::default(),
                provider: None,
                agent_ref: None,
            };

            // No [[ROUTE:..]] sentinel in the reply -> falls back to the
            // first declared route.
            let result = run_one_supervisor_turn(
                req,
                state_store,
                ext_runtime,
                plain_reply_llm("I'm not sure, let me think."),
                telemetry,
                token_meter,
                ledger,
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &TurnBilling::default(),
            )
            .await
            .expect("supervisor turn should succeed");

            assert_eq!(result.branch, "billing");
        }

        #[tokio::test]
        async fn run_one_supervisor_turn_with_audit_sink_completes_same_branch_as_without() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let (tx, mut rx) = tokio::sync::mpsc::channel(16);
            let sink = AuditSink::from_sender(tx);
            let real_tenant = real_tenant_ctx("acme", "prod");
            let routes = vec![
                SupervisorRoute {
                    branch: "billing".into(),
                    description: "Billing questions".into(),
                },
                SupervisorRoute {
                    branch: "tech".into(),
                    description: "Technical support".into(),
                },
            ];
            let req = SupervisorRequest {
                node_id: "router".to_string(),
                system_prompt: "Route the user.".to_string(),
                model: "gpt-4o-mini".to_string(),
                routes,
                state: GraphRunState::default(),
                provider: None,
                agent_ref: None,
            };

            let result = run_one_supervisor_turn(
                req,
                state_store,
                ext_runtime,
                plain_reply_llm("I'm not sure, let me think."),
                telemetry,
                token_meter,
                ledger,
                Arc::new(HashMap::new()),
                Some(&sink),
                &real_tenant,
                &TurnBilling::default(),
            )
            .await
            .expect("supervisor turn should succeed");

            assert_eq!(result.branch, "billing");
            assert!(
                rx.try_recv().is_err(),
                "no tool call happens on this path, so no audit event is expected"
            );
        }

        // -------------------------------------------------------------------
        // Billing of graph turns
        // -------------------------------------------------------------------

        /// (tenant_id, env_id, project_id, agent_id, model) per `emit`.
        type GraphEmit = (String, String, Option<String>, String, String);

        #[derive(Default)]
        struct RecordingGraphMeter {
            calls: std::sync::Mutex<Vec<GraphEmit>>,
        }

        impl greentic_aw_runtime::billing::BillingMeter for RecordingGraphMeter {
            fn emit<'a>(
                &'a self,
                tenant: &'a TenantContext,
                _input_tokens: u64,
                _output_tokens: u64,
                agent_id: &'a str,
                model: &'a str,
            ) -> std::pin::Pin<
                Box<
                    dyn std::future::Future<
                            Output = Result<(), greentic_aw_runtime::billing::BillingError>,
                        > + Send
                        + 'a,
                >,
            > {
                self.calls.lock().expect("lock").push((
                    tenant.tenant_id.clone(),
                    tenant.env_id.clone(),
                    tenant.project_id.clone(),
                    agent_id.to_string(),
                    model.to_string(),
                ));
                Box::pin(async { Ok(()) })
            }

            fn over_budget<'a>(
                &'a self,
                _tenant: &'a TenantContext,
            ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>>
            {
                Box::pin(std::future::ready(false))
            }
        }

        fn unit_billing(meter: &Arc<RecordingGraphMeter>) -> TurnBilling {
            TurnBilling {
                meter: Some(
                    Arc::clone(meter) as Arc<dyn greentic_aw_runtime::billing::BillingMeter>
                ),
                project_id: Some("support-bot".to_string()),
            }
        }

        /// An agent-graph turn bills through the unit's installed sink, under
        /// the REAL tenant/env the node was dispatched with and the deployed
        /// unit — not the synthetic `("graph", "run")` tenant every graph turn
        /// used to run under, which also meant no sink at all.
        #[tokio::test]
        async fn a_graph_agent_turn_bills_the_real_tenant_and_the_unit() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");
            let meter = Arc::new(RecordingGraphMeter::default());

            run_one_agent_turn(
                agent_turn_request("triage", "You triage."),
                state_store,
                ext_runtime,
                plain_reply_llm("routed [[RESOLVED]]"),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &unit_billing(&meter),
            )
            .await
            .expect("turn succeeds");

            let calls = meter.calls.lock().expect("lock");
            assert_eq!(calls.len(), 1, "one LLM iteration → one billing emit");
            assert_eq!(
                calls[0],
                (
                    "acme".to_string(),
                    "prod".to_string(),
                    Some("support-bot".to_string()),
                    "graph.triage".to_string(),
                    "gpt-4o-mini".to_string(),
                )
            );
        }

        /// Supervisor routing is an LLM call too, and bills the same way.
        #[tokio::test]
        async fn a_supervisor_routing_turn_is_billed() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");
            let meter = Arc::new(RecordingGraphMeter::default());
            let req = SupervisorRequest {
                node_id: "router".to_string(),
                system_prompt: "Route the user.".to_string(),
                model: "claude-3-haiku".to_string(),
                routes: vec![SupervisorRoute {
                    branch: "billing".into(),
                    description: "Billing questions".into(),
                }],
                state: GraphRunState::default(),
                provider: None,
                agent_ref: None,
            };

            run_one_supervisor_turn(
                req,
                state_store,
                ext_runtime,
                plain_reply_llm("[[ROUTE:billing]]"),
                telemetry,
                token_meter,
                ledger,
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &unit_billing(&meter),
            )
            .await
            .expect("supervisor turn succeeds");

            let calls = meter.calls.lock().expect("lock");
            assert_eq!(calls.len(), 1);
            assert_eq!(calls[0].0, "acme");
            assert_eq!(calls[0].1, "prod");
            assert_eq!(calls[0].2.as_deref(), Some("support-bot"));
            assert_eq!(calls[0].3, "graph.router.supervisor");
            assert_eq!(calls[0].4, "claude-3-haiku");
        }

        /// No installed sink leaves the turn exactly as unbilled as before —
        /// and it still runs.
        #[tokio::test]
        async fn a_graph_turn_without_a_sink_still_runs() {
            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
            let real_tenant = real_tenant_ctx("acme", "prod");
            let result = run_one_agent_turn(
                agent_turn_request("triage", "You triage."),
                state_store,
                ext_runtime,
                plain_reply_llm("hello"),
                telemetry,
                token_meter,
                ledger,
                None,
                None,
                Arc::new(vec![]),
                Arc::new(HashMap::new()),
                None,
                &real_tenant,
                &crate::runner::knowledge_index::IndexMount::default(),
                &TurnBilling::default(),
            )
            .await
            .expect("turn succeeds with no sink");
            assert_eq!(result.reply, "hello");
        }

        #[test]
        fn with_billing_sets_the_sink_and_unit_on_the_handler() {
            let handler = handler_with(
                Arc::new(InMemoryGraphProvider::new(HashMap::new())),
                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
                tool_fn_ok(),
            );
            assert!(handler.billing.meter.is_none());
            let meter = Arc::new(RecordingGraphMeter::default());
            let handler = handler.with_billing(
                Some(meter as Arc<dyn greentic_aw_runtime::billing::BillingMeter>),
                Some("support-bot".to_string()),
            );
            assert!(handler.billing.meter.is_some());
            assert_eq!(handler.billing.project_id.as_deref(), Some("support-bot"));
        }
    }

    /// Graph turns and graph Tool nodes resolve `a2a:` tools from the same
    /// pack-carried source a single-turn `dw.agent` does
    /// ([`graph_a2a_source`]). Env-mutating, so every test is `#[serial]`
    /// (crate convention, as in `a2a_pack_source`'s tests).
    #[cfg(all(test, feature = "agentic-worker"))]
    #[allow(clippy::unwrap_used, clippy::expect_used)]
    mod a2a_tests {
        use std::collections::HashMap;
        use std::future::Future;
        use std::pin::Pin;
        use std::sync::{Arc, Mutex};

        use greentic_aw_runtime::cost::MockTokenMeter;
        use greentic_aw_runtime::error::LlmError;
        use greentic_aw_runtime::graph::{AgentTurnRequest, GraphRunState, ToolCallRequest};
        use greentic_aw_runtime::llm::{LlmBackend, LlmRequest, LlmResponse};
        use greentic_aw_runtime::mock::{MockAgentStateStore, MockTelemetry, NoopToolLedger};
        use greentic_aw_runtime::state::ToolCallRecord;
        use greentic_aw_runtime::{AgentConfig, AgentLimits, LlmProviderRef, ToolRef};
        use greentic_ext_runtime::ExtensionRuntime;
        use serde_json::json;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        use super::{RuntimeTurnSource, TurnEffectSource, build_tool, graph_a2a_source};

        /// A hyphenated id, as the admin mints them.
        const AGENT_ID: &str = "8d2f0c1e-recipe";
        const TENANT: &str = "acme";
        const UNIT: &str = "unit-1";

        async fn serve_agent(server: &MockServer, reply: &str) {
            let card = json!({
                "name": "Recipe Agent",
                "description": "Suggests dishes.",
                "version": "1.0.0",
                "supportedInterfaces": [{
                    "url": format!("{}/a2a", server.uri()),
                    "protocolBinding": "JSONRPC",
                    "protocolVersion": "1.0"
                }],
                "capabilities": {"streaming": false, "pushNotifications": false},
                "defaultInputModes": ["text/plain"],
                "defaultOutputModes": ["text/plain"],
                "skills": []
            });
            Mock::given(method("GET"))
                .and(path("/.well-known/agent-card.json"))
                .respond_with(ResponseTemplate::new(200).set_body_json(card))
                .mount(server)
                .await;
            Mock::given(method("POST"))
                .and(path("/a2a"))
                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                    "jsonrpc": "2.0", "id": 1,
                    "result": {"message": {"messageId": "m-2", "role": "ROLE_AGENT",
                                           "parts": [{"text": reply}]}}
                })))
                .mount(server)
                .await;
        }

        /// A pack whose `assets/a2a-routes.json` names one team-scoped agent at
        /// `server`.
        fn pack_for(server: &MockServer) -> (tempfile::TempDir, Arc<crate::pack::PackRuntime>) {
            let dir = tempfile::tempdir().unwrap();
            std::fs::create_dir_all(dir.path().join("assets")).unwrap();
            let sidecar = json!([{
                "agent_id": AGENT_ID,
                "name": "Recipe agent",
                "base_url": server.uri(),
                "auth_header_name": null,
                "auth_team": "sales",
                "requires_auth": true
            }]);
            std::fs::write(
                dir.path().join("assets/a2a-routes.json"),
                sidecar.to_string(),
            )
            .unwrap();
            let pack = Arc::new(crate::pack::tests::pack_runtime_for_dir(dir.path()));
            (dir, pack)
        }

        struct MapSecrets(HashMap<String, Vec<u8>>);

        #[async_trait::async_trait]
        impl greentic_secrets_lib::SecretsManager for MapSecrets {
            async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
                self.0
                    .get(path)
                    .cloned()
                    .ok_or_else(|| greentic_secrets_lib::SecretError::NotFound(path.to_string()))
            }
            async fn write(&self, _: &str, _: &[u8]) -> greentic_secrets_lib::Result<()> {
                Ok(())
            }
            async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
                Ok(())
            }
        }

        /// A store holding the token ONLY at the unit-scoped URI, so a call
        /// that authenticates proves the tenant, the team and the unit all
        /// reached the source.
        fn unit_scoped_store() -> crate::secrets::DynSecretsManager {
            let uri = greentic_aw_runtime::scoped_secrets::secret_uri_candidates(
                "a2a",
                TENANT,
                Some("sales"),
                Some(UNIT),
                AGENT_ID,
            )
            .unwrap()
            .remove(0);
            assert!(uri.contains(".unit-"), "first candidate is the unit scope");
            Arc::new(MapSecrets(HashMap::from([(uri, b"tok-1".to_vec())])))
        }

        #[allow(unsafe_code)]
        fn set_gate(value: Option<&str>) {
            // SAFETY: every caller is #[serial] (crate convention).
            unsafe {
                match value {
                    Some(v) => std::env::set_var("GREENTIC_AW_A2A", v),
                    None => std::env::remove_var("GREENTIC_AW_A2A"),
                }
            }
        }

        /// LLM backend recording the tools offered on each call, then
        /// replaying a script.
        struct RecordingLlm {
            responses: Mutex<Vec<LlmResponse>>,
            offered: Mutex<Vec<Vec<(String, String)>>>,
        }

        impl LlmBackend for RecordingLlm {
            fn complete<'a>(
                &'a self,
                req: LlmRequest,
            ) -> Pin<Box<dyn Future<Output = Result<LlmResponse, LlmError>> + Send + 'a>>
            {
                self.offered.lock().unwrap().push(
                    req.tools
                        .iter()
                        .map(|t| (t.extension_id.clone(), t.tool_name.clone()))
                        .collect(),
                );
                let next = {
                    let mut queue = self.responses.lock().unwrap();
                    if queue.is_empty() {
                        Err(LlmError::Transport("script exhausted".into()))
                    } else {
                        Ok(queue.remove(0))
                    }
                };
                Box::pin(async move { next })
            }
        }

        fn tool_ref() -> String {
            format!("a2a:{AGENT_ID}")
        }

        /// The worker a specialist inherits from: it binds the `a2a:` tool
        /// with the author contract the designer ships.
        fn worker_with_a2a_tool() -> AgentConfig {
            AgentConfig {
                agent_id: "worker".into(),
                system_prompt: "sys".into(),
                tools: vec![ToolRef {
                    extension_id: tool_ref(),
                    tool_name: "ask".into(),
                    description: Some("Ask the Recipe agent agent.".into()),
                    input_schema: Some(json!({
                        "type": "object",
                        "properties": {"message": {"type": "string"}},
                        "required": ["message"]
                    })),
                    usage_note: None,
                }],
                llm: LlmProviderRef {
                    provider: "mock".into(),
                    model: "m".into(),
                    credential_ref: None,
                },
                limits: AgentLimits::default(),
                memory: None,
                knowledge: None,
                guardrails: vec![],
                conversational: false,
                opening_message: None,
                on_text_while_parked: Default::default(),
            }
        }

        /// Drive one graph agent turn through the PRODUCTION turn source (the
        /// same `RuntimeTurnSource` `from_parts` builds), for a specialist that
        /// inherits the worker's tools. Returns the reply and the tools offered
        /// on the first LLM call.
        async fn run_specialist_turn(
            a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
            calls_tool: bool,
        ) -> (String, Vec<(String, String)>) {
            let mut script = Vec::new();
            if calls_tool {
                script.push(LlmResponse {
                    content: None,
                    tool_calls: vec![ToolCallRecord {
                        call_id: "c1".into(),
                        extension_id: tool_ref(),
                        tool_name: "ask".into(),
                        args: json!({"message": "eggs?"}),
                    }],
                    tokens_in: 5,
                    tokens_out: 5,
                });
            }
            script.push(LlmResponse {
                content: Some("Try an omelette. [[RESOLVED]]".into()),
                tool_calls: vec![],
                tokens_in: 5,
                tokens_out: 5,
            });
            let llm = Arc::new(RecordingLlm {
                responses: Mutex::new(script),
                offered: Mutex::new(Vec::new()),
            });
            let source = RuntimeTurnSource {
                state_store: Arc::new(MockAgentStateStore::new()),
                ext_runtime: Arc::new(ExtensionRuntime::for_test().unwrap()),
                llm: llm.clone(),
                telemetry: Arc::new(MockTelemetry::new()),
                token_meter: Arc::new(MockTokenMeter::new(0)),
                ledger: Arc::new(NoopToolLedger),
                mcp_source: None,
                a2a_source,
                packs: Arc::new(vec![]),
                merged_agents: Arc::new(HashMap::from([(
                    "worker".to_string(),
                    worker_with_a2a_tool(),
                )])),
                index_mount: crate::runner::knowledge_index::IndexMount::default(),
            };
            let real_tenant = greentic_types::TenantCtx::new(
                greentic_types::EnvId::try_from("prod").unwrap(),
                greentic_types::TenantId::try_from(TENANT).unwrap(),
            );
            let turn = source.agent_turn(None, real_tenant, super::TurnBilling::default());
            let result = turn(AgentTurnRequest {
                node_id: "specialist".into(),
                system_prompt: "You suggest recipes.".into(),
                model: "m".into(),
                state: GraphRunState::default(),
                provider: Some("mock".into()),
                tools: vec![],
                agent_ref: None,
                inherit_from: Some("worker".into()),
            })
            .await
            .expect("the turn completes");
            let offered = llm
                .offered
                .lock()
                .unwrap()
                .first()
                .cloned()
                .unwrap_or_default();
            (result.reply, offered)
        }

        /// (a) A graph agent turn is offered the `a2a:` tool from a pack
        /// carrying `assets/a2a-routes.json`, and calling it reaches the agent
        /// with the unit-scoped credential.
        #[tokio::test]
        #[serial_test::serial]
        async fn a_graph_agent_turn_is_offered_and_calls_a_pack_carried_a2a_tool() {
            set_gate(None);
            let server = MockServer::start().await;
            serve_agent(&server, "an omelette").await;
            let (_dir, pack) = pack_for(&server);
            let source = graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT));
            assert!(source.is_some(), "the sidecar must yield a source");

            let (reply, offered) = run_specialist_turn(source, true).await;

            assert!(
                offered.contains(&(tool_ref(), "ask".to_string())),
                "the a2a tool must be offered to a graph agent turn; offered: {offered:?}"
            );
            assert_eq!(reply, "Try an omelette.");
            let requests = server.received_requests().await.unwrap();
            let post = requests
                .iter()
                .find(|r| r.method.as_str() == "POST")
                .expect("the agent must have been called");
            assert_eq!(
                post.headers
                    .get("authorization")
                    .and_then(|v| v.to_str().ok()),
                Some("Bearer tok-1"),
                "the credential is read at the unit scope the handler was built for"
            );
        }

        /// (b) `GREENTIC_AW_A2A=0` disables the graph path too: no source is
        /// built, so the turn is offered no `a2a:` tool.
        #[tokio::test]
        #[serial_test::serial]
        async fn the_env_gate_disables_a2a_for_graph_turns() {
            let server = MockServer::start().await;
            serve_agent(&server, "unused").await;
            let (_dir, pack) = pack_for(&server);
            set_gate(Some("0"));
            let gated = graph_a2a_source(
                std::slice::from_ref(&pack),
                TENANT,
                &unit_scoped_store(),
                Some(UNIT),
            );
            set_gate(None);
            assert!(gated.is_none(), "the operator's kill switch must hold");

            let (_, offered) = run_specialist_turn(gated, false).await;
            assert!(
                !offered.iter().any(|(ext, _)| ext.starts_with("a2a:")),
                "a disabled A2A source must offer no a2a: tool; offered: {offered:?}"
            );
            assert!(
                server.received_requests().await.unwrap().is_empty(),
                "a disabled source must never dial the agent"
            );
            assert!(
                graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT)).is_some(),
                "control: the same pack builds a source with the gate unset"
            );
        }

        /// (c) A graph Tool node naming `a2a:<agent_id>/ask` dispatches through
        /// the handler's A2A catalog rather than the extension runtime.
        #[tokio::test]
        #[serial_test::serial]
        async fn a_graph_tool_node_dispatches_an_a2a_ref() {
            set_gate(None);
            let server = MockServer::start().await;
            serve_agent(&server, "an omelette").await;
            let (_dir, pack) = pack_for(&server);
            let source = graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT));
            let tool = build_tool(Arc::new(ExtensionRuntime::for_test().unwrap()), source);

            let value = tool(ToolCallRequest {
                node_id: "lookup".into(),
                tool_name: format!("{}/ask", tool_ref()),
                state: GraphRunState::default(),
            })
            .await
            .expect("dispatch succeeds");

            assert_eq!(
                value,
                json!({"status": "completed", "agent": AGENT_ID, "reply": "an omelette"})
            );
            let requests = server.received_requests().await.unwrap();
            let post = requests
                .iter()
                .find(|r| r.method.as_str() == "POST")
                .expect("the agent must have been called");
            assert_eq!(
                post.headers
                    .get("authorization")
                    .and_then(|v| v.to_str().ok()),
                Some("Bearer tok-1")
            );
        }
    }
}

#[cfg(feature = "agentic-worker")]
pub use aw::{
    GraphConfigSource, InMemoryGraphProvider, LayeredGraphProvider, RuntimeGraphNodeHandler,
    build_graph_node_handler, graph_config_from_sidecar,
};

#[cfg(feature = "agentic-worker")]
pub(crate) use aw::build_graph_node_handler_metered;