bamboo-engine 2026.10.22

Execution engine and orchestration for the Bamboo agent framework
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
use std::sync::Arc;

use async_trait::async_trait;
use bamboo_domain::{TaskItem, TaskItemStatus, TaskList};
use chrono::Utc;
use futures::stream;
use tokio::sync::{mpsc, Mutex};
use tokio_util::sync::CancellationToken;

use crate::runtime::config::AgentLoopConfig;
use bamboo_agent_core::tools::{FunctionCall, Tool, ToolCtx, ToolError, ToolOutcome, ToolResult};
use bamboo_agent_core::{Message, Session};
use bamboo_llm::{LLMChunk, LLMError, LLMProvider, LLMStream};
use bamboo_metrics::storage::MetricsStorage;
use bamboo_tools::BuiltinToolExecutorBuilder;

fn task_list_with_in_progress_item(session_id: &str, description: &str) -> TaskList {
    TaskList {
        session_id: session_id.to_string(),
        title: "Agent Tasks".to_string(),
        items: vec![TaskItem {
            id: "task-1".to_string(),
            description: description.to_string(),
            status: TaskItemStatus::InProgress,
            ..TaskItem::default()
        }],
        created_at: Utc::now(),
        updated_at: Utc::now(),
    }
}

/// Regression test: tool calls executed inside the agent loop MUST receive a ToolExecutionContext
/// with `session_id=Some(...)`, including ordinary custom tools.
#[tokio::test]
async fn agent_loop_passes_session_id_into_tool_execution_context() {
    let trace = bamboo_infrastructure::telemetry::test_support::TraceTest::default();
    struct QueueProvider {
        // Each `chat_stream` call pops one pre-baked stream.
        queue: Mutex<Vec<Vec<bamboo_llm::provider::Result<LLMChunk>>>>,
    }

    #[async_trait]
    impl LLMProvider for QueueProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            let mut guard = self.queue.lock().await;
            if guard.is_empty() {
                panic!("test provider queue exhausted");
            }
            let items = guard.remove(0);
            Ok(Box::pin(stream::iter(items)))
        }
    }

    struct SessionIdRequiredTool {
        seen_session_id: Arc<Mutex<Option<String>>>,
    }

    #[async_trait]
    impl Tool for SessionIdRequiredTool {
        fn name(&self) -> &str {
            "session_context_probe"
        }

        fn description(&self) -> &str {
            "test tool that requires session_id in ToolExecutionContext"
        }

        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "goal": { "type": "string" }
                },
                "required": ["goal"]
            })
        }

        async fn invoke(
            &self,
            _args: serde_json::Value,
            ctx: ToolCtx,
        ) -> Result<ToolOutcome, ToolError> {
            let Some(session_id) = ctx.session_id else {
                return Err(ToolError::Execution(
                    "missing session_id in tool context".to_string(),
                ));
            };

            *self.seen_session_id.lock().await = Some(session_id.to_string());

            Ok(ToolOutcome::Completed(ToolResult {
                success: true,
                result: "ok".to_string(),
                display_preference: None,
                images: Vec::new(),
            }))
        }
    }

    let seen_session_id = Arc::new(Mutex::new(None));
    let tools = BuiltinToolExecutorBuilder::new()
        .with_tool(SessionIdRequiredTool {
            seen_session_id: seen_session_id.clone(),
        })
        .expect("register test tool")
        .build();

    let tool_call = bamboo_agent_core::tools::ToolCall {
        id: "call_context_probe".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "session_context_probe".to_string(),
            arguments: r#"{"goal":"do it"}"#.to_string(),
        },
    };

    let provider = Arc::new(QueueProvider {
        queue: Mutex::new(vec![
            vec![Ok(LLMChunk::ToolCalls(vec![tool_call])), Ok(LLMChunk::Done)],
            vec![Ok(LLMChunk::Token("done".to_string())), Ok(LLMChunk::Done)],
        ]),
    });

    let mut session = Session::new("session-ctx-test", "ignored");

    let (event_tx, _event_rx) = mpsc::channel(64);
    let config = AgentLoopConfig {
        run_budget: bamboo_config::RunBudgetConfig {
            max_rounds: Some(3),
            ..Default::default()
        },
        system_prompt: Some("sys".to_string()),
        model_name: Some("test-model".to_string()),
        ..Default::default()
    };

    trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "hello".to_string(),
            event_tx,
            provider,
            Arc::new(tools),
            CancellationToken::new(),
            config,
        ))
        .await
        .expect("agent loop should succeed");

    assert_eq!(
        seen_session_id.lock().await.clone(),
        Some("session-ctx-test".to_string())
    );
    let spans = trace.spans();
    let agent = spans
        .iter()
        .find(|s| s.name == "invoke_agent")
        .expect("real invocation span");
    let calls: Vec<_> = spans
        .iter()
        .filter(|s| s.name.starts_with("chat "))
        .collect();
    let tools: Vec<_> = spans
        .iter()
        .filter(|s| s.name.starts_with("execute_tool "))
        .collect();
    assert_eq!(calls.len(), 2, "one span per actual provider request");
    assert_eq!(tools.len(), 1, "one span per actual tool dispatch");
    assert_eq!(tools[0].name, "execute_tool session_context_probe");
    for span in calls.into_iter().chain(tools) {
        assert_eq!(span.parent_span_id, agent.span_context.span_id());
        assert_eq!(span.span_context.trace_id(), agent.span_context.trace_id());
        assert!(span.events.is_empty());
    }
    let exported = format!("{spans:?}");
    assert!(
        !exported.contains("do it"),
        "tool arguments must not be exported"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn agent_loop_explicit_gold_requires_managed_account_admission() {
    use crate::runtime::config::{AuxiliaryModelConfig, GoldConfig, PromptMemoryFlags};
    use bamboo_domain::ProviderModelRef;
    use bamboo_llm::{Config, ProviderRegistry};
    use serde_json::json;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, Request, ResponseTemplate};

    let account_a = MockServer::start().await;
    let account_b = MockServer::start().await;
    let main_calls = Arc::new(AtomicUsize::new(0));
    let main_counter = main_calls.clone();
    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .respond_with(move |request: &Request| {
            let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
            let model = body["model"].as_str().unwrap();
            let (delta, delay) = match model {
                "main-a" if main_counter.fetch_add(1, Ordering::SeqCst) % 2 == 0 => (
                    json!({"tool_calls": [{
                        "index": 0, "id": "fixture-update-goal", "type": "function",
                        "function": {
                            "name": "update_goal",
                            "arguments": json!({"status": "complete"}).to_string()
                        }
                    }]}),
                    false,
                ),
                "main-a" => (json!({"content": "synthetic done"}), true),
                "explicit-gold" => (
                    json!({"tool_calls": [{
                        "index": 0, "id": "fixture-gold", "type": "function",
                        "function": {
                            "name": "report_gold_evaluation",
                            "arguments": json!({
                                "decision": "achieved",
                                "confidence": "high",
                                "reasoning": "synthetic goal verified",
                                "missing_information": []
                            }).to_string()
                        }
                    }]}),
                    false,
                ),
                _ => panic!("unexpected model in synthetic account A: {model}"),
            };
            let frame = json!({
                "id": "synthetic-routing",
                "object": "chat.completion.chunk",
                "created": 0,
                "model": model,
                "choices": [{"index": 0, "delta": delta, "finish_reason": null}]
            });
            let response = ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_string(format!("data: {frame}\n\ndata: [DONE]\n\n"));
            if delay {
                // The post-round evaluation is detached. Hold the second main
                // response so it can be observed before run finalization.
                response.set_delay(Duration::from_secs(1))
            } else {
                response
            }
        })
        .mount(&account_a)
        .await;
    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&account_b)
        .await;

    let root = tempfile::tempdir().expect("isolated provider data directory");
    let mut config = Config::default();
    config.provider = "chat-a".into();
    config.default_provider_instance = Some("chat-a".into());
    config.http_proxy = "http://127.0.0.1:9".into();
    config.https_proxy.clear();
    config.proxy_auth = None;
    config.defaults = Some(
        serde_json::from_value(json!({
            "chat": {"provider": "chat-a", "model": "main-a"},
            "fast": {"provider": "fast-b", "model": "cheap-b"}
        }))
        .unwrap(),
    );
    for (id, model, endpoint, admitted) in [
        (
            "chat-a",
            "main-a",
            account_a.uri(),
            vec!["main-a", "explicit-gold"],
        ),
        ("fast-b", "cheap-b", account_b.uri(), vec!["cheap-b"]),
    ] {
        config.provider_instances.insert(
            id.into(),
            serde_json::from_value(json!({
                "provider_type": "openai",
                "enabled": true,
                "api_key": "synthetic-only-not-a-credential",
                "base_url": endpoint,
                "model": model,
                "runtime_models": admitted
            }))
            .unwrap(),
        );
    }
    let registry = Arc::new(
        ProviderRegistry::from_config(&config, root.path().to_path_buf())
            .await
            .expect("synthetic managed registry"),
    );
    let main_ref = ProviderModelRef::new("chat-a", "main-a");
    let gold_ref = ProviderModelRef::new("chat-a", "explicit-gold");
    let main = registry
        .provider_for_configured_model(&config, &main_ref)
        .expect("main model is admitted on A");
    assert!(registry
        .provider_for_configured_model(&config, &gold_ref)
        .is_ok());

    // The closure exercises the same shared role resolvers as the Host, while
    // the genuine runner executes both Gold checkpoint consumers.
    let live_config = Arc::new(tokio::sync::RwLock::new(config));
    let resolver_config = live_config.clone();
    let resolver_registry = registry.clone();
    let resolver = Arc::new(move || {
        let config = resolver_config.try_read().unwrap();
        let areas =
            crate::model_areas::resolve_global_area_models(&config, "chat-a", &resolver_registry);
        let (fast_model_name, fast_model_provider) =
            crate::model_config_helper::resolve_fast_model_for_runner(
                Some(&config),
                "chat-a",
                &resolver_registry,
            );
        AuxiliaryModelConfig {
            fast_model_name,
            fast_model_provider,
            background_model_name: areas
                .background
                .as_ref()
                .map(|target| target.model_name.clone()),
            background_model_provider: areas.background.map(|target| target.provider),
            summarization_model_name: areas
                .summarization
                .as_ref()
                .map(|target| target.model_name.clone()),
            summarization_model_provider: areas.summarization.map(|target| target.provider),
            summarization_model_error: areas.summarization_error,
            ..Default::default()
        }
    });
    // Model the Host's per-run binding using the exact same guarded target,
    // leaving SDK runs without this hook unchanged.
    let gold_config_handle = live_config.clone();
    let gold_registry = registry.clone();
    let gold_expected = main.clone();
    let gold_resolver = Arc::new(move |model: &str, delegate: Arc<dyn LLMProvider>| {
        bamboo_llm::gold_admission::guarded_gold_target(
            gold_config_handle.clone(),
            gold_registry.clone(),
            ProviderModelRef::new("chat-a", model),
            gold_expected.clone(),
            delegate,
        )
    });
    let mut request_offset = 0usize;
    for revoked in [false, true] {
        if revoked {
            let mut current = live_config.write().await;
            current
                .provider_instances
                .get_mut("chat-a")
                .unwrap()
                .extra
                .insert("runtime_models".into(), json!(["main-a"]));
            assert!(registry
                .provider_for_configured_model(&current, &main_ref)
                .is_ok());
            assert!(registry
                .provider_for_configured_model(&current, &gold_ref)
                .is_err());
            assert!(Arc::ptr_eq(&main, &registry.get("chat-a").unwrap()));
        }
        let before_main = main_calls.load(Ordering::SeqCst);
        let mut session = Session::new(
            if revoked {
                "gold-revoked"
            } else {
                "gold-admitted"
            },
            "main-a",
        );
        session.model_ref = Some(main_ref.clone());
        let (event_tx, _event_rx) = mpsc::channel(128);
        let loop_config = AgentLoopConfig {
            model_name: Some("main-a".into()),
            provider_name: Some("chat-a".into()),
            gold_config: Some(GoldConfig {
                enabled: true,
                auto_continue_enabled: true,
                goal: Some("synthetic goal".into()),
                model_name: Some("explicit-gold".into()),
                ..Default::default()
            }),
            prompt_memory_flags: PromptMemoryFlags {
                project_prompt_injection: false,
                relevant_recall: false,
                relevant_recall_rerank: false,
                project_first_dream: false,
                ledger_agenda: false,
            },
            auxiliary_model_resolver: Some(resolver.clone()),
            gold_target_resolver: Some(gold_resolver.clone()),
            run_budget: bamboo_config::RunBudgetConfig {
                max_rounds: Some(4),
                ..Default::default()
            },
            ..Default::default()
        };
        tokio::time::timeout(
            Duration::from_secs(20),
            super::run_agent_loop_with_config(
                &mut session,
                "synthetic request".into(),
                event_tx,
                main.clone(),
                Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
                CancellationToken::new(),
                loop_config,
            ),
        )
        .await
        .expect("synthetic real runner must finish")
        .expect("synthetic foreground run must succeed");
        assert_eq!(main_calls.load(Ordering::SeqCst) - before_main, 2);
        let requests = account_a.received_requests().await.unwrap();
        let recent = &requests[request_offset..];
        request_offset = requests.len();
        let gold: Vec<_> = recent
            .iter()
            .filter(|request| {
                serde_json::from_slice::<serde_json::Value>(&request.body).unwrap()["model"]
                    == "explicit-gold"
            })
            .collect();
        assert!(account_b.received_requests().await.unwrap().is_empty());
        if revoked {
            assert!(
                gold.is_empty(),
                "revoked explicit Gold model must not dispatch; got {} requests",
                gold.len()
            );
        } else {
            for checkpoint in ["checkpoint=post_round", "checkpoint=terminal"] {
                assert!(
                    gold.iter().any(|request| {
                        String::from_utf8_lossy(&request.body).contains(checkpoint)
                    }),
                    "admitted explicit Gold must reach {checkpoint} on A"
                );
            }
        }
    }
}

#[tokio::test]
async fn agent_loop_gold_checkpoints_keep_provider_and_model_paired() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    use crate::runtime::config::{AuxiliaryModelConfig, GoldConfig, PromptMemoryFlags};
    use bamboo_domain::ProviderModelRef;
    use bamboo_llm::{LLMRequestOptions, ProviderRegistry};
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct PairProvider {
        account: &'static str,
        main_calls: AtomicUsize,
        evaluations: Arc<std::sync::Mutex<Vec<(String, String, String)>>>,
    }

    #[async_trait]
    impl LLMProvider for PairProvider {
        async fn chat_stream(
            &self,
            messages: &[Message],
            tools: &[bamboo_agent_core::tools::ToolSchema],
            max: Option<u32>,
            model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            self.chat_stream_with_options(messages, tools, max, model, None)
                .await
        }

        async fn chat_stream_with_options(
            &self,
            messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max: Option<u32>,
            model: &str,
            options: Option<&LLMRequestOptions>,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            let purpose = options
                .and_then(|value| value.request_purpose.as_deref())
                .unwrap_or("agent_loop");
            if purpose == "gold_evaluation" {
                let checkpoint = messages
                    .iter()
                    .find_map(|message| {
                        if message.content.contains("checkpoint=post_round") {
                            Some("post_round")
                        } else if message.content.contains("checkpoint=terminal") {
                            Some("terminal")
                        } else {
                            None
                        }
                    })
                    .expect("Gold request has its checkpoint in the synthetic prompt");
                self.evaluations.lock().unwrap().push((
                    self.account.into(),
                    model.into(),
                    checkpoint.into(),
                ));
                let call = bamboo_agent_core::tools::ToolCall {
                    id: "synthetic-gold".into(),
                    tool_type: "function".into(),
                    function: FunctionCall {
                        name: "report_gold_evaluation".into(),
                        arguments: serde_json::json!({
                            "decision": "achieved", "confidence": "high",
                            "reasoning": "synthetic goal verified", "missing_information": []
                        })
                        .to_string(),
                    },
                };
                return Ok(Box::pin(stream::iter([
                    Ok(LLMChunk::ToolCalls(vec![call])),
                    Ok(LLMChunk::Done),
                ])));
            }
            assert_eq!(
                self.account, "chat-a",
                "only A may run the foreground agent"
            );
            assert_eq!(model, "main-a");
            if self.main_calls.fetch_add(1, Ordering::SeqCst) == 0 {
                let call = bamboo_agent_core::tools::ToolCall {
                    id: "synthetic-goal".into(),
                    tool_type: "function".into(),
                    function: FunctionCall {
                        name: "update_goal".into(),
                        arguments: r#"{"status":"complete"}"#.into(),
                    },
                };
                return Ok(Box::pin(stream::iter([
                    Ok(LLMChunk::ToolCalls(vec![call])),
                    Ok(LLMChunk::Done),
                ])));
            }
            // The real post-round evaluator is detached. Keep the foreground
            // turn open until it calls a synthetic provider, so finalization
            // cannot cancel it before this test observes the actual target.
            tokio::time::timeout(std::time::Duration::from_secs(1), async {
                loop {
                    let seen = self
                        .evaluations
                        .lock()
                        .unwrap()
                        .iter()
                        .any(|(_, _, checkpoint)| checkpoint == "post_round");
                    if seen {
                        break;
                    }
                    tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                }
            })
            .await
            .expect("post-round Gold evaluation reaches a synthetic provider");
            Ok(Box::pin(stream::iter([
                Ok(LLMChunk::Token("synthetic done".into())),
                Ok(LLMChunk::Done),
            ])))
        }
    }

    let mut observations = Vec::new();
    for explicit_gold in [false, true] {
        let context = RoutingContext::new(None);
        let snapshot = context.config.read().await.clone();
        let evaluations = Arc::new(std::sync::Mutex::new(Vec::new()));
        let main = Arc::new(PairProvider {
            account: "chat-a",
            main_calls: AtomicUsize::new(0),
            evaluations: evaluations.clone(),
        });
        let fast = Arc::new(PairProvider {
            account: "fast-b",
            main_calls: AtomicUsize::new(0),
            evaluations: evaluations.clone(),
        });
        let providers: HashMap<String, Arc<dyn LLMProvider>> = HashMap::from([
            ("chat-a".into(), main.clone() as Arc<dyn LLMProvider>),
            ("fast-b".into(), fast as Arc<dyn LLMProvider>),
        ]);
        let registry = Arc::new(ProviderRegistry::new(providers, "chat-a".into()));
        registry.set_runtime_models(HashMap::from([
            (
                "chat-a".into(),
                vec!["main-a".into(), "explicit-gold".into()],
            ),
            ("fast-b".into(), vec!["cheap-b".into()]),
        ]));
        let resolver = Arc::new(move || {
            let areas =
                crate::model_areas::resolve_global_area_models(&snapshot, "chat-a", &registry);
            AuxiliaryModelConfig {
                fast_model_name: areas.fast.as_ref().map(|target| target.model_name.clone()),
                fast_model_provider: areas.fast.map(|target| target.provider),
                background_model_name: areas
                    .background
                    .as_ref()
                    .map(|target| target.model_name.clone()),
                background_model_provider: areas.background.map(|target| target.provider),
                summarization_model_name: areas
                    .summarization
                    .as_ref()
                    .map(|target| target.model_name.clone()),
                summarization_model_provider: areas.summarization.map(|target| target.provider),
                summarization_model_error: areas.summarization_error,
                ..Default::default()
            }
        });
        let mut session = Session::new("synthetic-gold-pair-session", "main-a");
        session.model_ref = Some(ProviderModelRef::new("chat-a", "main-a"));
        let (event_tx, _event_rx) = mpsc::channel(128);
        let config = AgentLoopConfig {
            model_name: Some("main-a".into()),
            provider_name: Some("chat-a".into()),
            gold_config: Some(GoldConfig {
                enabled: true,
                auto_continue_enabled: true,
                goal: Some("synthetic goal".into()),
                model_name: explicit_gold.then(|| "explicit-gold".into()),
                ..Default::default()
            }),
            prompt_memory_flags: PromptMemoryFlags {
                project_prompt_injection: false,
                relevant_recall: false,
                relevant_recall_rerank: false,
                project_first_dream: false,
                ledger_agenda: false,
            },
            auxiliary_model_resolver: Some(resolver),
            run_budget: bamboo_config::RunBudgetConfig {
                max_rounds: Some(4),
                ..Default::default()
            },
            ..Default::default()
        };
        super::run_agent_loop_with_config(
            &mut session,
            "synthetic request".into(),
            event_tx,
            main.clone(),
            Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
            CancellationToken::new(),
            config,
        )
        .await
        .expect("synthetic goal loop should complete");
        assert!(main.main_calls.load(Ordering::SeqCst) >= 2);
        let mut observed = evaluations.lock().unwrap().clone();
        observed.sort();
        let (account, model) = if explicit_gold {
            ("chat-a", "explicit-gold")
        } else {
            ("fast-b", "cheap-b")
        };
        let mut expected = vec![
            (
                account.to_string(),
                model.to_string(),
                "post_round".to_string(),
            ),
            (
                account.to_string(),
                model.to_string(),
                "terminal".to_string(),
            ),
        ];
        expected.sort();
        observations.push((explicit_gold, observed, expected));
    }
    assert!(
        observations
            .iter()
            .all(|(_, actual, expected)| actual == expected),
        "each Gold checkpoint must use its configured account/model pair: {observations:#?}"
    );
}

#[tokio::test]
async fn agent_loop_rejects_explicit_invalid_fast_for_task_and_gold_evaluations() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    use crate::runtime::config::{AuxiliaryModelConfig, GoldConfig};
    use bamboo_llm::LLMRequestOptions;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct SyntheticMain {
        main_calls: AtomicUsize,
        evaluations: std::sync::Mutex<Vec<(String, String)>>,
        fast: Arc<crate::app_context::model_routing_test_support::CaptureProvider>,
    }

    #[async_trait]
    impl LLMProvider for SyntheticMain {
        async fn chat_stream(
            &self,
            messages: &[Message],
            tools: &[bamboo_agent_core::tools::ToolSchema],
            max: Option<u32>,
            model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            self.chat_stream_with_options(messages, tools, max, model, None)
                .await
        }

        async fn chat_stream_with_options(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max: Option<u32>,
            model: &str,
            options: Option<&LLMRequestOptions>,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            let purpose = options
                .and_then(|value| value.request_purpose.as_deref())
                .unwrap_or("agent_loop");
            if matches!(purpose, "task_evaluation" | "gold_evaluation") {
                self.evaluations
                    .lock()
                    .unwrap()
                    .push((model.to_string(), purpose.to_string()));
                return Err(LLMError::Api("synthetic evaluation refusal".into()));
            }
            if self.main_calls.fetch_add(1, Ordering::SeqCst) == 0 {
                let call = bamboo_agent_core::tools::ToolCall {
                    id: "task-write".into(),
                    tool_type: "function".into(),
                    function: FunctionCall {
                        name: "Task".into(),
                        arguments: serde_json::json!({
                            "tasks": [{"content": "Synthetic work", "status": "in_progress",
                                "activeForm": "Doing synthetic work"}]
                        })
                        .to_string(),
                    },
                };
                return Ok(Box::pin(stream::iter([
                    Ok(LLMChunk::ToolCalls(vec![call])),
                    Ok(LLMChunk::Done),
                ])));
            }
            // Keep the real foreground loop alive until both post-round tasks
            // have had a chance to reach their fake provider. A correct repair
            // may dispatch neither, so the bounded wait must also expire.
            let _ = tokio::time::timeout(std::time::Duration::from_millis(500), async {
                loop {
                    let main_count = self.evaluations.lock().unwrap().len();
                    let fast_count = self.fast.requests.lock().unwrap().len();
                    if main_count + fast_count >= 2 {
                        break;
                    }
                    tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                }
            })
            .await;
            Ok(Box::pin(stream::iter([
                Ok(LLMChunk::Token("synthetic done".into())),
                Ok(LLMChunk::Done),
            ])))
        }
    }

    for flag in [None, Some(false), Some(true)] {
        for invalid in [false, true] {
            let routing = RoutingContext::new(flag);
            let mut config_snapshot = routing.config.read().await.clone();
            // Preserve the old registry and target while the live config now
            // rejects Fast; the valid run is the actual-consumer positive.
            if invalid {
                config_snapshot
                    .provider_instances
                    .get_mut("fast-b")
                    .unwrap()
                    .enabled = false;
            }
            assert!(routing.registry.get("fast-b").is_some());
            let snapshot = Arc::new(std::sync::Mutex::new(config_snapshot));
            let resolver_snapshot = snapshot.clone();
            let registry = routing.registry.clone();
            let resolver = Arc::new(move || {
                let config = resolver_snapshot.lock().unwrap();
                let areas =
                    crate::model_areas::resolve_global_area_models(&config, "chat-a", &registry);
                let (fast_model_name, fast_model_provider) =
                    crate::model_config_helper::resolve_fast_model_for_runner(
                        Some(&config),
                        "chat-a",
                        &registry,
                    );
                AuxiliaryModelConfig {
                    fast_model_name,
                    fast_model_provider,
                    background_model_name: areas
                        .background
                        .as_ref()
                        .map(|target| target.model_name.clone()),
                    background_model_provider: areas.background.map(|target| target.provider),
                    summarization_model_name: areas
                        .summarization
                        .as_ref()
                        .map(|target| target.model_name.clone()),
                    summarization_model_provider: areas.summarization.map(|target| target.provider),
                    summarization_model_error: areas.summarization_error,
                    ..Default::default()
                }
            });
            let main = Arc::new(SyntheticMain {
                main_calls: AtomicUsize::new(0),
                evaluations: std::sync::Mutex::new(Vec::new()),
                fast: routing.providers["fast-b"].clone(),
            });
            let tools = BuiltinToolExecutorBuilder::new()
                .with_command_tool("Task")
                .expect("register Task tool")
                .build();
            let mut session = Session::new("synthetic-evaluation-session", "main-a");
            session.set_task_list(task_list_with_in_progress_item(
                &session.id,
                "Synthetic work",
            ));
            let (event_tx, _event_rx) = mpsc::channel(128);
            let loop_config = AgentLoopConfig {
                system_prompt: Some("synthetic system".into()),
                model_name: Some("main-a".into()),
                gold_config: Some(GoldConfig {
                    enabled: true,
                    ..Default::default()
                }),
                auxiliary_model_resolver: Some(resolver),
                run_budget: bamboo_config::RunBudgetConfig {
                    max_rounds: Some(3),
                    ..Default::default()
                },
                ..Default::default()
            };
            let outcome = super::run_agent_loop_with_config(
                &mut session,
                "synthetic goal".into(),
                event_tx,
                main.clone(),
                Arc::new(tools),
                CancellationToken::new(),
                loop_config,
            )
            .await;
            // Fail the fixture on unrelated runner errors: without an actual
            // foreground round, a no-dispatch observation would be meaningless.
            outcome.expect("synthetic foreground loop should complete");
            assert!(main.main_calls.load(Ordering::SeqCst) >= 2);
            let on_main = main.evaluations.lock().unwrap().clone();
            let on_fast = routing.requests("fast-b");
            if invalid {
                assert!(on_main.is_empty() && on_fast.is_empty(),
                    "explicit disabled Fast must not dispatch: flag={flag:?}, main={on_main:?}, fast={on_fast:?}");
            } else {
                assert!(
                    on_main.is_empty(),
                    "valid Fast must not use main account: {on_main:?}"
                );
                for purpose in ["task_evaluation", "gold_evaluation"] {
                    assert!(
                        on_fast
                            .iter()
                            .any(|(model, actual)| model == "cheap-b" && actual == purpose),
                        "valid Fast must reach {purpose}: flag={flag:?}, fast={on_fast:?}"
                    );
                }
            }
        }
    }
}

#[tokio::test]
async fn runner_fast_selection_distinguishes_unset_from_rejected_route() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    use crate::model_config_helper::resolve_fast_model_for_runner;

    let routing = RoutingContext::new(None);
    let config = routing.config.read().await.clone();
    let (name, provider) =
        resolve_fast_model_for_runner(Some(&config), "chat-a", &routing.registry);
    let expected_provider: Arc<dyn LLMProvider> = routing.providers["fast-b"].clone();
    assert_eq!(name.as_deref(), Some("cheap-b"));
    assert!(Arc::ptr_eq(&provider.unwrap(), &expected_provider));

    let mut disabled = config.clone();
    disabled
        .provider_instances
        .get_mut("fast-b")
        .unwrap()
        .enabled = false;
    let (name, provider) =
        resolve_fast_model_for_runner(Some(&disabled), "chat-a", &routing.registry);
    assert_eq!(name.as_deref(), Some("cheap-b"));
    let provider = provider.expect("explicit refusal must not become an unset role");
    for _ in 0..2 {
        assert!(matches!(
            provider.chat_stream(&[], &[], None, "cheap-b").await,
            Err(LLMError::Auth(message)) if message.contains("disabled")
        ));
    }
    assert!(matches!(
        provider
            .chat_stream_with_options(&[], &[], None, "cheap-b", None)
            .await,
        Err(LLMError::Auth(_))
    ));
    assert!(!provider.supports_vision("cheap-b").await);
    assert!(provider.list_models().await.is_err());

    let mut unadmitted = config.clone();
    unadmitted
        .provider_instances
        .get_mut("fast-b")
        .unwrap()
        .extra
        .insert(
            "runtime_models".into(),
            serde_json::json!(["different-model"]),
        );
    let (_, provider) =
        resolve_fast_model_for_runner(Some(&unadmitted), "chat-a", &routing.registry);
    assert!(matches!(
        provider
            .unwrap()
            .chat_stream(&[], &[], None, "cheap-b")
            .await,
        Err(LLMError::Api(_))
    ));

    let mut missing = config.clone();
    missing
        .defaults
        .as_mut()
        .unwrap()
        .fast
        .as_mut()
        .unwrap()
        .provider = "missing-b".into();
    let (_, provider) = resolve_fast_model_for_runner(Some(&missing), "chat-a", &routing.registry);
    assert!(matches!(
        provider
            .unwrap()
            .chat_stream(&[], &[], None, "cheap-b")
            .await,
        Err(LLMError::Auth(_))
    ));

    let mut malformed = config.clone();
    malformed
        .defaults
        .as_mut()
        .unwrap()
        .fast
        .as_mut()
        .unwrap()
        .model
        .clear();
    let (_, provider) =
        resolve_fast_model_for_runner(Some(&malformed), "chat-a", &routing.registry);
    assert!(matches!(
        provider.unwrap().chat_stream(&[], &[], None, "").await,
        Err(LLMError::Api(_))
    ));

    let empty = bamboo_llm::Config::default();
    let (name, provider) =
        resolve_fast_model_for_runner(Some(&empty), "no-such-provider", &routing.registry);
    assert!(
        name.is_none() && provider.is_none(),
        "unset preserves legacy fallback"
    );
    let (name, provider) = resolve_fast_model_for_runner(None, "chat-a", &routing.registry);
    assert!(name.is_none());
    assert!(matches!(
        provider
            .unwrap()
            .chat_stream(&[], &[], None, "main-a")
            .await,
        Err(LLMError::Api(_))
    ));
    routing.assert_no_requests();
}

#[tokio::test]
async fn agent_loop_uses_refreshed_fast_model_for_between_round_task_evaluation() {
    struct RecordingRoundProvider {
        queue: Mutex<Vec<Vec<bamboo_llm::provider::Result<LLMChunk>>>>,
        fast_models: Mutex<Vec<String>>,
    }

    #[async_trait]
    impl LLMProvider for RecordingRoundProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            if model.starts_with("fast-") {
                self.fast_models.lock().await.push(model.to_string());
                return Err(LLMError::Api("intentional fast-model failure".to_string()));
            }

            // When the second chat round starts, the first task evaluator has
            // already been spawned but may not have received executor time yet.
            // Wait for that background request to enter the provider so this
            // test observes the between-round refresh deterministically without
            // relying on the finalize path to drain it.
            if self.queue.lock().await.len() == 2 {
                tokio::time::timeout(std::time::Duration::from_secs(1), async {
                    while self.fast_models.lock().await.is_empty() {
                        tokio::task::yield_now().await;
                    }
                })
                .await
                .expect("first between-round task evaluation should start");
            }

            let mut guard = self.queue.lock().await;
            if guard.is_empty() {
                panic!("test provider queue exhausted");
            }
            let items = guard.remove(0);
            Ok(Box::pin(stream::iter(items)))
        }
    }

    struct NoopTool;

    #[async_trait]
    impl Tool for NoopTool {
        fn name(&self) -> &str {
            "noop_tool"
        }

        fn description(&self) -> &str {
            "no-op tool for round boundary testing"
        }

        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {},
                "additionalProperties": false
            })
        }

        async fn invoke(
            &self,
            _args: serde_json::Value,
            _ctx: ToolCtx,
        ) -> Result<ToolOutcome, ToolError> {
            Ok(ToolOutcome::Completed(ToolResult {
                success: true,
                result: "ok".to_string(),
                display_preference: None,
                images: Vec::new(),
            }))
        }
    }

    let tools = BuiltinToolExecutorBuilder::new()
        .with_tool(NoopTool)
        .expect("register test tool")
        .with_command_tool("Task")
        .expect("register Task tool")
        .build();

    // Task evaluation fires only on Task-tool writes. Two writes also exercise
    // coalescing while the first auxiliary request is in flight; normal
    // finalization intentionally cancels the queued final-round snapshot (#593).
    let tool_call = |id: &str| bamboo_agent_core::tools::ToolCall {
        id: id.to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "Task".to_string(),
            arguments: serde_json::json!({
                "tasks": [{
                    "content": "Verify auxiliary refresh",
                    "status": "in_progress",
                    "activeForm": "Verifying auxiliary refresh"
                }]
            })
            .to_string(),
        },
    };

    let provider = Arc::new(RecordingRoundProvider {
        queue: Mutex::new(vec![
            vec![
                Ok(LLMChunk::ToolCalls(vec![tool_call("call-1")])),
                Ok(LLMChunk::Done),
            ],
            vec![
                Ok(LLMChunk::ToolCalls(vec![tool_call("call-2")])),
                Ok(LLMChunk::Done),
            ],
            vec![Ok(LLMChunk::Token("done".to_string())), Ok(LLMChunk::Done)],
        ]),
        fast_models: Mutex::new(Vec::new()),
    });

    let mut session = Session::new("session-fast-refresh", "sticky-chat-model");
    session.set_task_list(task_list_with_in_progress_item(
        &session.id,
        "Verify auxiliary refresh",
    ));

    let fast_counter = Arc::new(std::sync::Mutex::new(0usize));
    let fast_counter_for_resolver = fast_counter.clone();

    let (event_tx, _event_rx) = mpsc::channel(64);
    let config = AgentLoopConfig {
        run_budget: bamboo_config::RunBudgetConfig {
            max_rounds: Some(5),
            ..Default::default()
        },
        system_prompt: Some("sys".to_string()),
        model_name: Some("sticky-chat-model".to_string()),
        auxiliary_model_resolver: Some(Arc::new(move || {
            let mut guard = fast_counter_for_resolver.lock().expect("fast counter lock");
            *guard += 1;
            crate::runtime::config::AuxiliaryModelConfig {
                fast_model_name: Some(format!("fast-{}", *guard)),
                ..Default::default()
            }
        })),
        ..Default::default()
    };

    super::run_agent_loop_with_config(
        &mut session,
        "hello".to_string(),
        event_tx,
        provider.clone(),
        Arc::new(tools),
        CancellationToken::new(),
        config,
    )
    .await
    .expect("agent loop should succeed");

    let fast_models = provider.fast_models.lock().await.clone();
    // `fast-1` was resolved at startup; the between-round refresh must select
    // `fast-2` for the first evaluation. Depending on scheduling, that request
    // may finish before the next round polls it, allowing the second write to
    // launch with `fast-3`; otherwise it remains queued and is cancelled at
    // finalization. Both are valid, and neither requires a finalize-time drain.
    assert!(
        matches!(
            fast_models.as_slice(),
            [first] if first == "fast-2"
        ) || matches!(
            fast_models.as_slice(),
            [first, second] if first == "fast-2" && second == "fast-3"
        ),
        "between-round evaluations must use refreshed fast models in order, got {fast_models:?}"
    );
}

#[tokio::test]
async fn cancelled_pipeline_releases_activation_without_false_completion() {
    let trace = bamboo_infrastructure::telemetry::test_support::TraceTest::default();
    struct NeverCalledProvider;

    #[async_trait]
    impl LLMProvider for NeverCalledProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            panic!("pre-cancelled pipeline must not call the provider")
        }
    }

    let directory = tempfile::tempdir().expect("tempdir");
    let skill_root = directory.path().join("skills/cancel-demo");
    tokio::fs::create_dir_all(&skill_root)
        .await
        .expect("skill root");
    tokio::fs::write(
        skill_root.join("SKILL.md"),
        "---\nname: cancel-demo\ndescription: cancel\n---\ncancel\n",
    )
    .await
    .expect("skill");
    let manager = Arc::new(bamboo_skills::SkillManager::with_config(
        bamboo_skills::SkillStoreConfig {
            skills_dir: directory.path().join("skills"),
            ..Default::default()
        },
    ));
    manager.initialize().await.expect("initialize");
    manager
        .store()
        .pin_current_activation("cancelled-activation", &["cancel-demo".to_string()], None)
        .await
        .expect("pin activation");
    let mut session = Session::new("cancelled-activation", "model");
    session.metadata.insert(
        bamboo_skills::runtime_metadata::SKILL_RUNTIME_SELECTION_SOURCE_KEY.to_string(),
        "auto".to_string(),
    );
    let config = AgentLoopConfig {
        skill_manager: Some(manager.clone()),
        model_name: Some("model".to_string()),
        ..Default::default()
    };
    let cancel = CancellationToken::new();
    cancel.cancel();
    let (event_tx, mut event_rx) = mpsc::channel(16);
    let result = trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "cancel".to_string(),
            event_tx,
            Arc::new(NeverCalledProvider),
            Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
            cancel,
            config,
        ))
        .await;

    assert!(matches!(
        result,
        Err(bamboo_agent_core::AgentError::Cancelled)
    ));
    assert!(manager
        .store()
        .activation_descriptor("cancelled-activation")
        .await
        .is_none());
    assert!(!session.agent_runtime_state.as_ref().is_some_and(|state| {
        matches!(state.status, bamboo_domain::AgentStatusState::Completed)
    }));
    while let Ok(event) = event_rx.try_recv() {
        assert!(
            !matches!(event, bamboo_agent_core::AgentEvent::Complete { .. }),
            "cancelled pipeline must not emit Complete"
        );
    }
    let spans = trace.spans();
    assert_eq!(
        spans.len(),
        1,
        "pre-cancelled invocation must not fabricate provider/tool spans"
    );
    assert_eq!(spans[0].name, "invoke_agent");
    assert!(spans[0]
        .attributes
        .iter()
        .any(|kv| kv.key.as_str() == "error.type" && kv.value.to_string() == "cancelled"));
}

#[tokio::test]
async fn suspended_restart_without_retained_snapshot_continues_degraded() {
    struct CalledProvider {
        called: std::sync::atomic::AtomicBool,
        messages: std::sync::Mutex<Vec<Message>>,
    }

    #[async_trait]
    impl LLMProvider for CalledProvider {
        async fn chat_stream(
            &self,
            messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            self.called.store(true, std::sync::atomic::Ordering::SeqCst);
            self.messages
                .lock()
                .expect("provider messages lock")
                .extend_from_slice(messages);
            Ok(Box::pin(stream::iter(vec![
                Ok(LLMChunk::Token("continued without workflow".to_string())),
                Ok(LLMChunk::Done),
            ])))
        }
    }

    let directory = tempfile::tempdir().expect("tempdir");
    let skill_root = directory.path().join("skills/restart-demo");
    tokio::fs::create_dir_all(&skill_root)
        .await
        .expect("skill root");
    tokio::fs::write(
        skill_root.join("SKILL.md"),
        "---\nname: restart-demo\ndescription: restart\n---\nrestart N+1\n",
    )
    .await
    .expect("skill");
    let manager = Arc::new(bamboo_skills::SkillManager::with_config(
        bamboo_skills::SkillStoreConfig {
            skills_dir: directory.path().join("skills"),
            ..Default::default()
        },
    ));
    manager.initialize().await.expect("initialize");

    let mut session = Session::new("restart-missing-pin", "model");
    let mut suspended = bamboo_domain::AgentRuntimeState::new("restart-missing-pin");
    suspended.status = bamboo_domain::AgentStatusState::Suspended;
    session.agent_runtime_state = Some(suspended);
    session.metadata.insert(
        bamboo_skills::runtime_metadata::SKILL_RUNTIME_ACTIVATION_GENERATION_KEY.to_string(),
        "7".to_string(),
    );
    session.metadata.insert(
        bamboo_skills::runtime_metadata::SKILL_RUNTIME_SELECTION_SOURCE_KEY.to_string(),
        "explicit".to_string(),
    );
    session.metadata.insert(
        bamboo_skills::runtime_metadata::SKILL_RUNTIME_SELECTED_SKILL_REVISIONS_KEY.to_string(),
        r#"{"restart-demo":3}"#.to_string(),
    );
    let config = AgentLoopConfig {
        skill_manager: Some(manager.clone()),
        selected_skill_ids: Some(vec!["restart-demo".to_string()]),
        model_name: Some("model".to_string()),
        ..Default::default()
    };
    let (event_tx, mut event_rx) = mpsc::channel(64);
    let provider = Arc::new(CalledProvider {
        called: std::sync::atomic::AtomicBool::new(false),
        messages: std::sync::Mutex::new(Vec::new()),
    });
    let result = super::run_agent_loop_with_config(
        &mut session,
        "continue".to_string(),
        event_tx,
        provider.clone(),
        Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
        CancellationToken::new(),
        config,
    )
    .await;

    result.expect("missing LKG degrades workflow without killing the main session");
    assert!(provider.called.load(std::sync::atomic::Ordering::SeqCst));
    let (has_degraded_diagnostic, has_workflow_runtime) = {
        let provider_messages = provider.messages.lock().expect("provider messages lock");
        (
            provider_messages
                .iter()
                .any(|message| message.content.contains("Workflow Activation Degraded")),
            provider_messages
                .iter()
                .any(|message| message.content.contains("context_type: workflow_runtime")),
        )
    };
    assert!(has_degraded_diagnostic);
    assert!(!has_workflow_runtime);
    assert!(session
        .metadata
        .get(bamboo_skills::runtime_metadata::SKILL_RUNTIME_ACTIVATION_ERROR_KEY)
        .is_some_and(|message| message.contains("snapshot")));
    assert!(manager
        .store()
        .activation_descriptor("restart-missing-pin")
        .await
        .is_none());
    assert!(!session
        .metadata
        .contains_key(bamboo_skills::ACTIVE_WORKFLOW_METADATA_KEY));
    assert!(!session
        .metadata
        .contains_key(bamboo_skills::ACTIVE_WORKFLOW_SNAPSHOT_METADATA_KEY));
    while let Ok(event) = event_rx.try_recv() {
        assert!(!matches!(
            event,
            bamboo_agent_core::AgentEvent::WorkflowActivated { .. }
        ));
    }
}

#[tokio::test]
async fn suspended_restart_with_empty_selection_does_not_require_snapshot() {
    struct CalledProvider(std::sync::atomic::AtomicBool);

    #[async_trait]
    impl LLMProvider for CalledProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            self.0.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok(Box::pin(stream::iter(vec![
                Ok(LLMChunk::Token("continued".to_string())),
                Ok(LLMChunk::Done),
            ])))
        }
    }

    let directory = tempfile::tempdir().expect("tempdir");
    let manager = Arc::new(bamboo_skills::SkillManager::with_config(
        bamboo_skills::SkillStoreConfig {
            skills_dir: directory.path().join("skills"),
            ..Default::default()
        },
    ));
    manager.initialize().await.expect("initialize");
    let mut session = Session::new("restart-empty-selection", "model");
    let mut suspended = bamboo_domain::AgentRuntimeState::new("restart-empty-selection");
    suspended.status = bamboo_domain::AgentStatusState::Suspended;
    session.agent_runtime_state = Some(suspended);
    session.metadata.insert(
        bamboo_skills::runtime_metadata::SKILL_RUNTIME_ACTIVATION_GENERATION_KEY.to_string(),
        "7".to_string(),
    );
    session.metadata.insert(
        bamboo_skills::runtime_metadata::SKILL_RUNTIME_SELECTED_SKILL_REVISIONS_KEY.to_string(),
        "{}".to_string(),
    );
    let provider = Arc::new(CalledProvider(std::sync::atomic::AtomicBool::new(false)));
    let (event_tx, _event_rx) = mpsc::channel(8);
    super::run_agent_loop_with_config(
        &mut session,
        "continue".to_string(),
        event_tx,
        provider.clone(),
        Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
        CancellationToken::new(),
        AgentLoopConfig {
            skill_manager: Some(manager),
            selected_skill_ids: Some(Vec::new()),
            model_name: Some("model".to_string()),
            run_budget: bamboo_config::RunBudgetConfig {
                max_rounds: Some(1),
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .await
    .expect("empty selection continuation");
    assert!(provider.0.load(std::sync::atomic::Ordering::SeqCst));
}

#[tokio::test]
async fn activation_metadata_persistence_failure_releases_pin_before_provider_call() {
    struct FailingPersistence;
    #[async_trait]
    impl bamboo_domain::RuntimeSessionPersistence for FailingPersistence {
        async fn save_runtime_session(&self, _session: &mut Session) -> std::io::Result<()> {
            Err(std::io::Error::other("injected persistence failure"))
        }
    }
    struct NeverCalledProvider;
    #[async_trait]
    impl LLMProvider for NeverCalledProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            panic!("persistence failure must stop before provider execution")
        }
    }

    let directory = tempfile::tempdir().expect("tempdir");
    let manager = Arc::new(bamboo_skills::SkillManager::with_config(
        bamboo_skills::SkillStoreConfig {
            skills_dir: directory.path().join("skills"),
            ..Default::default()
        },
    ));
    manager.initialize().await.expect("initialize");
    let mut session = Session::new("persistence-failure", "model");
    let (event_tx, _event_rx) = mpsc::channel(4);
    let result = super::run_agent_loop_with_config(
        &mut session,
        "review".to_string(),
        event_tx,
        Arc::new(NeverCalledProvider),
        Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
        CancellationToken::new(),
        AgentLoopConfig {
            skill_manager: Some(manager.clone()),
            selected_skill_ids: Some(vec!["review".to_string()]),
            persistence: Some(Arc::new(FailingPersistence)),
            model_name: Some("model".to_string()),
            ..Default::default()
        },
    )
    .await;
    assert!(result
        .expect_err("setup must fail closed")
        .to_string()
        .contains("could not be published before tool/model execution"));
    assert!(manager
        .store()
        .activation_descriptor("persistence-failure")
        .await
        .is_none());
}

#[tokio::test]
async fn activation_tool_call_checkpoint_failure_stops_before_tool_and_releases_pin() {
    struct FailAssistantToolCallSave(Arc<std::sync::atomic::AtomicUsize>);
    #[async_trait]
    impl bamboo_domain::RuntimeSessionPersistence for FailAssistantToolCallSave {
        async fn save_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
            let is_assistant_tool_call_boundary = session.messages.iter().rev().any(|message| {
                matches!(message.role, bamboo_agent_core::Role::Assistant)
                    && message.tool_calls.as_ref().is_some_and(|calls| {
                        calls.iter().any(|call| call.function.name == "load_skill")
                    })
            });
            if is_assistant_tool_call_boundary {
                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Err(std::io::Error::other(
                    "assistant tool-call checkpoint failed",
                ))
            } else {
                Ok(())
            }
        }
    }
    struct NeverExecutedLoad;
    #[async_trait]
    impl bamboo_agent_core::tools::ToolExecutor for NeverExecutedLoad {
        async fn execute(
            &self,
            _call: &bamboo_agent_core::tools::ToolCall,
        ) -> bamboo_agent_core::tools::executor::Result<ToolResult> {
            panic!("assistant tool-call checkpoint must persist before load_skill executes")
        }
        fn list_tools(&self) -> Vec<bamboo_agent_core::tools::ToolSchema> {
            vec![bamboo_agent_core::tools::ToolSchema {
                schema_type: "function".to_string(),
                function: bamboo_agent_core::tools::FunctionSchema {
                    name: "load_skill".to_string(),
                    description: "load".to_string(),
                    parameters: serde_json::json!({"type":"object"}),
                },
            }]
        }
    }
    struct ActivationProvider;
    #[async_trait]
    impl LLMProvider for ActivationProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            let call = bamboo_agent_core::tools::ToolCall {
                id: "load-review".to_string(),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: "load_skill".to_string(),
                    arguments: r#"{"skill_id":"review"}"#.to_string(),
                },
            };
            Ok(Box::pin(stream::iter(vec![
                Ok(LLMChunk::ToolCalls(vec![call])),
                Ok(LLMChunk::Done),
            ])))
        }
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let manager = Arc::new(bamboo_skills::SkillManager::with_config(
        bamboo_skills::SkillStoreConfig {
            skills_dir: directory.path().join("skills"),
            ..Default::default()
        },
    ));
    manager.initialize().await.expect("initialize");
    let mut session = Session::new("activation-checkpoint-failure", "model");
    let save_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let (event_tx, _event_rx) = mpsc::channel(4);
    let result = super::run_agent_loop_with_config(
        &mut session,
        "review".to_string(),
        event_tx,
        Arc::new(ActivationProvider),
        Arc::new(NeverExecutedLoad),
        CancellationToken::new(),
        AgentLoopConfig {
            skill_manager: Some(manager.clone()),
            selected_skill_ids: Some(vec!["review".to_string()]),
            persistence: Some(Arc::new(FailAssistantToolCallSave(save_count.clone()))),
            model_name: Some("model".to_string()),
            ..Default::default()
        },
    )
    .await;
    assert!(result
        .expect_err("activation tool-call checkpoint must fail")
        .to_string()
        .contains("assistant tool-call checkpoint could not be persisted"));
    assert_eq!(save_count.load(std::sync::atomic::Ordering::SeqCst), 1);
    assert!(manager
        .store()
        .activation_descriptor("activation-checkpoint-failure")
        .await
        .is_none());
    assert!(!session
        .metadata
        .contains_key(bamboo_skills::ACTIVE_WORKFLOW_METADATA_KEY));
    assert!(!session
        .metadata
        .contains_key(bamboo_skills::ACTIVE_WORKFLOW_SNAPSHOT_METADATA_KEY));
}

#[tokio::test]
async fn unsuccessful_model_issued_explicit_activation_stops_before_answer_and_releases_pin() {
    struct UnsuccessfulLoad;
    #[async_trait]
    impl bamboo_agent_core::tools::ToolExecutor for UnsuccessfulLoad {
        async fn execute(
            &self,
            _call: &bamboo_agent_core::tools::ToolCall,
        ) -> bamboo_agent_core::tools::executor::Result<ToolResult> {
            Ok(ToolResult {
                success: false,
                result: "injected activation failure".to_string(),
                display_preference: None,
                images: Vec::new(),
            })
        }
        fn list_tools(&self) -> Vec<bamboo_agent_core::tools::ToolSchema> {
            vec![bamboo_agent_core::tools::ToolSchema {
                schema_type: "function".to_string(),
                function: bamboo_agent_core::tools::FunctionSchema {
                    name: "load_skill".to_string(),
                    description: "load".to_string(),
                    parameters: serde_json::json!({"type":"object"}),
                },
            }]
        }
    }
    struct ActivationProvider;
    #[async_trait]
    impl LLMProvider for ActivationProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<LLMStream> {
            let call = bamboo_agent_core::tools::ToolCall {
                id: "load-review".to_string(),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: "load_skill".to_string(),
                    arguments: r#"{"skill_id":"review"}"#.to_string(),
                },
            };
            Ok(Box::pin(stream::iter(vec![
                Ok(LLMChunk::ToolCalls(vec![call])),
                Ok(LLMChunk::Done),
            ])))
        }
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let manager = Arc::new(bamboo_skills::SkillManager::with_config(
        bamboo_skills::SkillStoreConfig {
            skills_dir: directory.path().join("skills"),
            ..Default::default()
        },
    ));
    manager.initialize().await.expect("initialize");
    let mut session = Session::new("unsuccessful-model-activation", "model");
    let (event_tx, _event_rx) = mpsc::channel(64);
    let result = super::run_agent_loop_with_config(
        &mut session,
        "review".to_string(),
        event_tx,
        Arc::new(ActivationProvider),
        Arc::new(UnsuccessfulLoad),
        CancellationToken::new(),
        AgentLoopConfig {
            skill_manager: Some(manager.clone()),
            selected_skill_ids: Some(vec!["review".to_string()]),
            model_name: Some("model".to_string()),
            ..Default::default()
        },
    )
    .await;
    assert!(result
        .expect_err("model-issued activation must fail closed")
        .to_string()
        .contains("failed to activate; refusing to continue"));
    assert!(manager
        .store()
        .activation_descriptor("unsuccessful-model-activation")
        .await
        .is_none());
}

struct MetricsQueueProvider {
    queue: Mutex<Vec<Vec<bamboo_llm::provider::Result<LLMChunk>>>>,
    requested_messages: Mutex<Vec<Vec<Message>>>,
}

#[async_trait]
impl LLMProvider for MetricsQueueProvider {
    async fn chat_stream(
        &self,
        messages: &[Message],
        _tools: &[bamboo_agent_core::tools::ToolSchema],
        _max_output_tokens: Option<u32>,
        _model: &str,
    ) -> bamboo_llm::provider::Result<LLMStream> {
        self.requested_messages.lock().await.push(messages.to_vec());
        let mut queue = self.queue.lock().await;
        assert!(!queue.is_empty(), "metrics provider queue exhausted");
        Ok(Box::pin(stream::iter(queue.remove(0))))
    }
}

fn provider_usage(prompt: u64, completion: u64) -> LLMChunk {
    LLMChunk::ProviderUsage {
        input_tokens: Some(prompt),
        output_tokens: Some(completion),
        total_tokens: Some(prompt.saturating_add(completion)),
        reasoning_tokens: None,
        cache_creation_input_tokens: None,
        cache_read_input_tokens: None,
        cache_write_input_tokens: None,
    }
}

fn metric_execution_prefix(round_id: &str) -> &str {
    round_id
        .rsplit_once("-round-")
        .map(|(prefix, _)| prefix)
        .expect("round id suffix")
}

async fn create_runner_metrics() -> (
    tempfile::TempDir,
    bamboo_metrics::MetricsCollector,
    Arc<bamboo_metrics::SqliteMetricsStorage>,
) {
    let directory = tempfile::tempdir().expect("metrics tempdir");
    let storage = Arc::new(bamboo_metrics::SqliteMetricsStorage::new(
        directory.path().join("metrics.db"),
    ));
    storage.init().await.expect("initialize metrics storage");
    let collector = bamboo_metrics::MetricsCollector::spawn(storage.clone(), 7);
    (directory, collector, storage)
}

fn runner_metrics_config(collector: &bamboo_metrics::MetricsCollector) -> AgentLoopConfig {
    AgentLoopConfig {
        run_budget: bamboo_config::RunBudgetConfig {
            max_rounds: Some(2),
            ..Default::default()
        },
        system_prompt: Some("metrics regression test".to_string()),
        model_name: Some("test-model".to_string()),
        metrics_collector: Some(collector.clone()),
        prompt_memory_flags: crate::runtime::config::PromptMemoryFlags {
            project_prompt_injection: false,
            relevant_recall: false,
            relevant_recall_rerank: false,
            project_first_dream: false,
            ledger_agenda: false,
        },
        ..AgentLoopConfig::default()
    }
}

async fn wait_for_runner_metrics(
    storage: &bamboo_metrics::SqliteMetricsStorage,
    session_id: &str,
    expected_rounds: usize,
    expected_usage: bamboo_metrics::types::TokenUsage,
) -> bamboo_metrics::types::SessionDetail {
    for _ in 0..100 {
        if let Some(detail) = storage
            .session_detail(session_id)
            .await
            .expect("session metrics query")
        {
            if detail.rounds.len() == expected_rounds
                && detail
                    .rounds
                    .iter()
                    .all(|round| round.completed_at.is_some())
                && detail.session.total_token_usage == expected_usage
            {
                return detail;
            }
        }
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
    panic!(
        "session {session_id} did not persist {expected_rounds} completed rounds with usage {expected_usage:?}"
    );
}

#[tokio::test]
async fn repeated_execution_of_one_session_keeps_both_metric_rounds() {
    let trace = bamboo_infrastructure::telemetry::test_support::TraceTest::default();
    let session_id = "metrics-repeated-execution";
    let (_directory, collector, storage) = create_runner_metrics().await;
    let provider = Arc::new(MetricsQueueProvider {
        queue: Mutex::new(vec![
            vec![
                Ok(provider_usage(10, 2)),
                Ok(LLMChunk::Token("first answer".to_string())),
                Ok(LLMChunk::Done),
            ],
            vec![
                Ok(provider_usage(20, 3)),
                Ok(LLMChunk::Token("second answer".to_string())),
                Ok(LLMChunk::Done),
            ],
        ]),
        requested_messages: Mutex::new(Vec::new()),
    });
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
        Arc::new(bamboo_tools::BuiltinToolExecutor::new());
    let mut session = Session::new(session_id, "test-model");

    let (first_tx, _first_rx) = mpsc::channel(64);
    trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "first request".to_string(),
            first_tx,
            provider.clone(),
            tools.clone(),
            CancellationToken::new(),
            runner_metrics_config(&collector),
        ))
        .await
        .expect("first execution");

    let first_detail = wait_for_runner_metrics(
        storage.as_ref(),
        session_id,
        1,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 10,
            completion_tokens: 2,
            total_tokens: 12,
        },
    )
    .await;
    let first_round_id = first_detail.rounds[0].round_id.clone();
    assert_eq!(
        first_detail.rounds[0].status,
        bamboo_metrics::types::RoundStatus::Success
    );

    let (second_tx, _second_rx) = mpsc::channel(64);
    trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "second request".to_string(),
            second_tx,
            provider,
            tools,
            CancellationToken::new(),
            runner_metrics_config(&collector),
        ))
        .await
        .expect("second execution");

    let detail = wait_for_runner_metrics(
        storage.as_ref(),
        session_id,
        2,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 30,
            completion_tokens: 5,
            total_tokens: 35,
        },
    )
    .await;
    let first = detail
        .rounds
        .iter()
        .find(|round| round.round_id == first_round_id)
        .expect("first execution round remains present");
    assert_eq!(
        first.token_usage,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 10,
            completion_tokens: 2,
            total_tokens: 12,
        }
    );

    let second = detail
        .rounds
        .iter()
        .find(|round| round.round_id != first_round_id)
        .expect("second execution has a distinct round");
    assert_ne!(first.round_id, second.round_id);
    assert!(first.round_id.starts_with(&format!("{session_id}-run-")));
    assert!(second.round_id.starts_with(&format!("{session_id}-run-")));
    assert_eq!(
        second.token_usage,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 20,
            completion_tokens: 3,
            total_tokens: 23,
        }
    );
    assert!(storage
        .prompt_memory_exposure(&first.round_id)
        .await
        .expect("query first execution exposure")
        .is_some());
    assert!(storage
        .prompt_memory_exposure(&second.round_id)
        .await
        .expect("query second execution exposure")
        .is_some());
    assert_eq!(
        session
            .agent_runtime_state
            .as_ref()
            .and_then(|state| state.round.last_round_id.as_deref()),
        Some(second.round_id.as_str())
    );
    let spans = trace.spans();
    let agents: Vec<_> = spans.iter().filter(|s| s.name == "invoke_agent").collect();
    let calls: Vec<_> = spans
        .iter()
        .filter(|s| s.name == "chat test-model")
        .collect();
    assert_eq!(agents.len(), 2);
    assert_eq!(calls.len(), 2);
    assert_ne!(
        agents[0].span_context.trace_id(),
        agents[1].span_context.trace_id()
    );
    for ((agent, call), (input, output)) in agents.iter().zip(&calls).zip([(10, 2), (20, 3)]) {
        assert_eq!(call.parent_span_id, agent.span_context.span_id());
        assert!(call
            .attributes
            .iter()
            .any(|kv| kv.key.as_str() == "gen_ai.usage.input_tokens"
                && kv.value.to_string() == input.to_string()));
        assert!(call
            .attributes
            .iter()
            .any(|kv| kv.key.as_str() == "gen_ai.usage.output_tokens"
                && kv.value.to_string() == output.to_string()));
        assert!(agent
            .attributes
            .iter()
            .any(|kv| kv.key.as_str() == "bamboo.execution.id"));
        assert!(agent
            .attributes
            .iter()
            .any(|kv| kv.key.as_str() == "bamboo.run.id"));
    }
    assert!(!format!("{spans:?}").contains("first request"));
    assert!(!format!("{spans:?}").contains("first answer"));
}

#[tokio::test]
async fn provider_bootstrap_persists_exact_project_ids_and_redacts_global_ids() {
    let session_id = "metrics-prompt-memory-exposure";
    let (_directory, collector, storage) = create_runner_metrics().await;
    let memory_directory = tempfile::tempdir().expect("memory tempdir");
    let memory_store = bamboo_memory::memory_store::MemoryStore::new(memory_directory.path());
    let project_a =
        bamboo_domain::ProjectId::parse("prompt-memory-project-a").expect("valid Project A id");
    let project_b =
        bamboo_domain::ProjectId::parse("prompt-memory-project-b").expect("valid Project B id");
    let project_c = bamboo_domain::ProjectId::parse("prompt-memory-project-c").expect("Project C");
    let project_a_store = memory_store.for_project(&project_a);
    let project_b_store = memory_store.for_project(&project_b);
    let query = "exposuretoken1077";
    let first = project_a_store
        .write_memory(
            bamboo_memory::memory_store::MemoryScope::Project,
            Some(project_a.as_str()),
            bamboo_memory::memory_store::DurableMemoryType::Project,
            "Exposuretoken1077 canonical Project A decision",
            &format!(
                "Project A compact summary. {} FULL_PRIVATE_BODY_A_MUST_NOT_RENDER",
                "a".repeat(300)
            ),
            &[query.to_string()],
            Some(session_id),
            "test-model",
            false,
            Some(bamboo_memory::memory_store::TemporalGranularity::Year),
        )
        .await
        .expect("write Project A memory");
    let mut project_a_ids = vec![first.frontmatter.id];
    for (index, granularity) in [
        bamboo_memory::memory_store::TemporalGranularity::Day,
        bamboo_memory::memory_store::TemporalGranularity::Quarter,
        bamboo_memory::memory_store::TemporalGranularity::Week,
    ]
    .into_iter()
    .enumerate()
    {
        let written = project_a_store
            .write_memory(
                bamboo_memory::memory_store::MemoryScope::Project,
                Some(project_a.as_str()),
                bamboo_memory::memory_store::DurableMemoryType::Project,
                &format!("Exposuretoken1077 Project A decision {}", index + 2),
                &format!(
                    "Project A compact summary {}. {} FULL_PRIVATE_BODY_A_MUST_NOT_RENDER",
                    index + 2,
                    "a".repeat(300)
                ),
                &[query.to_string()],
                Some(session_id),
                "test-model",
                false,
                Some(granularity),
            )
            .await
            .expect("write another Project A memory");
        project_a_ids.push(written.frontmatter.id);
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    let excluded = project_b_store
        .write_memory(
            bamboo_memory::memory_store::MemoryScope::Project,
            Some(project_b.as_str()),
            bamboo_memory::memory_store::DurableMemoryType::Project,
            "Exposuretoken1077 other Project decision",
            &format!(
                "Project B compact summary. {} FULL_PRIVATE_BODY_B_MUST_NOT_RENDER",
                "b".repeat(300)
            ),
            &[query.to_string()],
            Some("other-session"),
            "test-model",
            false,
            Some(bamboo_memory::memory_store::TemporalGranularity::Day),
        )
        .await
        .expect("write Project B memory");
    let global = memory_store
        .write_memory(
            bamboo_memory::memory_store::MemoryScope::Global,
            None,
            bamboo_memory::memory_store::DurableMemoryType::Reference,
            "Exposuretoken1077 global fallback",
            &format!(
                "Global compact summary. {} FULL_PRIVATE_GLOBAL_BODY_MUST_NOT_RENDER",
                "g".repeat(300)
            ),
            &[query.to_string()],
            Some("global-session"),
            "test-model",
            false,
            None,
        )
        .await
        .expect("write Global fallback memory");

    let provider = Arc::new(MetricsQueueProvider {
        queue: Mutex::new(vec![
            vec![
                Ok(provider_usage(17, 3)),
                Ok(LLMChunk::Token("observed answer".to_string())),
                Ok(LLMChunk::Done),
            ],
            vec![
                Ok(provider_usage(5, 1)),
                Ok(LLMChunk::Token("global answer".to_string())),
                Ok(LLMChunk::Done),
            ],
        ]),
        requested_messages: Mutex::new(Vec::new()),
    });
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
        Arc::new(bamboo_tools::BuiltinToolExecutor::new());
    let mut session = Session::new(session_id, "test-model");
    session.set_project_id_meta(project_a.to_string());
    session.metadata.insert(
        "runtime_prompt_memory_observability".to_string(),
        serde_json::json!({"relevant_memory_ids":["forged-metadata-id"]}).to_string(),
    );
    session.metadata.insert(
        "external_memory_rendered".to_string(),
        "If selected: `memory` action=get id=forged-rendered-id".to_string(),
    );
    let mut config = runner_metrics_config(&collector);
    config.memory_store = memory_store.clone();
    config.prompt_memory_flags.relevant_recall = true;

    let (event_tx, _event_rx) = mpsc::channel(64);
    super::run_agent_loop_with_config(
        &mut session,
        format!("recall {query}"),
        event_tx,
        provider.clone(),
        tools,
        CancellationToken::new(),
        config,
    )
    .await
    .expect("provider-backed execution");

    let detail = wait_for_runner_metrics(
        storage.as_ref(),
        session_id,
        1,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 17,
            completion_tokens: 3,
            total_tokens: 20,
        },
    )
    .await;
    let observation = storage
        .prompt_memory_exposure(&detail.rounds[0].round_id)
        .await
        .expect("query prompt-memory observation")
        .expect("successful bootstrap persists an observation");
    assert_eq!(observation.project_id.as_deref(), Some(project_a.as_str()));
    assert_eq!(
        observation.recall_outcome,
        bamboo_metrics::types::PromptMemoryRecallOutcome::Lexical
    );
    assert_eq!(observation.all_compact_exposed_count, 3);
    assert_eq!(observation.project_exposed_count, 3);
    assert!(!observation.out_of_project_only);
    assert_eq!(observation.project_items.len(), 3);

    let requests = provider.requested_messages.lock().await;
    assert_eq!(requests.len(), 1);
    let provider_text = requests[0]
        .iter()
        .map(|message| message.content.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    let mut provider_ids = project_a_ids
        .iter()
        .filter(|id| provider_text.contains(id.as_str()))
        .map(String::as_str)
        .collect::<Vec<_>>();
    provider_ids.sort_by_key(|id| provider_text.find(*id).expect("provider-visible id"));
    assert_eq!(
        provider_ids.len(),
        3,
        "one of four candidates stays outside top-k"
    );
    assert_eq!(
        observation
            .project_items
            .iter()
            .map(|item| item.memory_id.as_str())
            .collect::<Vec<_>>(),
        provider_ids,
        "persisted IDs and ranks must match final provider-visible order"
    );
    assert!(observation
        .project_items
        .iter()
        .enumerate()
        .all(|(index, item)| item.rank == index as u32 + 1));
    assert!(!provider_text.contains(&excluded.frontmatter.id));
    assert!(!provider_text.contains("forged-metadata-id"));
    assert!(!provider_text.contains("forged-rendered-id"));
    assert!(!provider_text.contains("FULL_PRIVATE_BODY_A_MUST_NOT_RENDER"));
    assert!(!provider_text.contains("FULL_PRIVATE_BODY_B_MUST_NOT_RENDER"));
    assert!(!provider_text.contains(&global.frontmatter.id));
    drop(requests);

    let global_session_id = "metrics-prompt-memory-global-fallback";
    let mut global_session = Session::new(global_session_id, "test-model");
    global_session.set_project_id_meta(project_c.to_string());
    let mut global_config = runner_metrics_config(&collector);
    global_config.memory_store = memory_store;
    global_config.prompt_memory_flags.relevant_recall = true;
    let (global_tx, _global_rx) = mpsc::channel(64);
    super::run_agent_loop_with_config(
        &mut global_session,
        format!("recall {query}"),
        global_tx,
        provider.clone(),
        Arc::new(bamboo_tools::BuiltinToolExecutor::new()),
        CancellationToken::new(),
        global_config,
    )
    .await
    .expect("Global-fallback provider execution");
    let global_detail = wait_for_runner_metrics(
        storage.as_ref(),
        global_session_id,
        1,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 5,
            completion_tokens: 1,
            total_tokens: 6,
        },
    )
    .await;
    let global_observation = storage
        .prompt_memory_exposure(&global_detail.rounds[0].round_id)
        .await
        .expect("query Global-only observation")
        .expect("Global-only provider bootstrap persists a header");
    assert_eq!(
        global_observation.project_id.as_deref(),
        Some(project_c.as_str())
    );
    assert_eq!(global_observation.all_compact_exposed_count, 1);
    assert_eq!(global_observation.project_exposed_count, 0);
    assert!(global_observation.out_of_project_only);
    assert!(global_observation.project_items.is_empty());
    let requests = provider.requested_messages.lock().await;
    let global_text = requests[1]
        .iter()
        .map(|message| message.content.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(global_text.contains(&global.frontmatter.id));
    assert!(!global_text.contains("FULL_PRIVATE_GLOBAL_BODY_MUST_NOT_RENDER"));
}

struct PauseForHumanTool;

#[async_trait]
impl Tool for PauseForHumanTool {
    fn name(&self) -> &str {
        "pause_for_human"
    }

    fn description(&self) -> &str {
        "pause this execution until a human responds"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        })
    }

    async fn invoke(
        &self,
        _args: serde_json::Value,
        ctx: ToolCtx,
    ) -> Result<ToolOutcome, ToolError> {
        Ok(ToolOutcome::NeedsHuman {
            question: bamboo_agent_core::PendingQuestion {
                tool_call_id: ctx.tool_call_id.to_string(),
                tool_name: self.name().to_string(),
                question: "Continue?".to_string(),
                options: vec!["yes".to_string(), "no".to_string()],
                allow_custom: false,
                source: bamboo_agent_core::PendingQuestionSource::PauseTool,
            },
            result: ToolResult::text(false, "waiting for a response"),
        })
    }
}

struct ResumeCompleteTool;

#[async_trait]
impl Tool for ResumeCompleteTool {
    fn name(&self) -> &str {
        "complete_after_resume"
    }

    fn description(&self) -> &str {
        "complete one tool call after the suspended execution resumes"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        })
    }

    async fn invoke(
        &self,
        _args: serde_json::Value,
        _ctx: ToolCtx,
    ) -> Result<ToolOutcome, ToolError> {
        Ok(ToolOutcome::Completed(ToolResult::text(
            true,
            "resume tool completed",
        )))
    }
}

#[tokio::test]
async fn suspended_session_resume_uses_a_new_metric_round_and_preserves_tool_link() {
    let session_id = "metrics-suspend-resume";
    let (_directory, collector, storage) = create_runner_metrics().await;
    let pause_call = bamboo_agent_core::tools::ToolCall {
        id: "pause-call".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "pause_for_human".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let resume_call = bamboo_agent_core::tools::ToolCall {
        id: "resume-call".to_string(),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: "complete_after_resume".to_string(),
            arguments: "{}".to_string(),
        },
    };
    let provider = Arc::new(MetricsQueueProvider {
        queue: Mutex::new(vec![
            vec![
                Ok(provider_usage(7, 2)),
                Ok(LLMChunk::ToolCalls(vec![pause_call])),
                Ok(LLMChunk::Done),
            ],
            vec![
                Ok(provider_usage(13, 4)),
                Ok(LLMChunk::ToolCalls(vec![resume_call])),
                Ok(LLMChunk::Done),
            ],
            vec![
                Ok(provider_usage(5, 1)),
                Ok(LLMChunk::Token("resumed answer".to_string())),
                Ok(LLMChunk::Done),
            ],
        ]),
        requested_messages: Mutex::new(Vec::new()),
    });
    let tools = BuiltinToolExecutorBuilder::new()
        .with_tool(PauseForHumanTool)
        .expect("register pause tool")
        .with_tool(ResumeCompleteTool)
        .expect("register resume tool")
        .build();
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> = Arc::new(tools);
    let mut session = Session::new(session_id, "test-model");

    let (first_tx, _first_rx) = mpsc::channel(64);
    super::run_agent_loop_with_config(
        &mut session,
        "need a decision".to_string(),
        first_tx,
        provider.clone(),
        tools.clone(),
        CancellationToken::new(),
        runner_metrics_config(&collector),
    )
    .await
    .expect("suspending execution");

    assert!(session.has_pending_question());
    assert_eq!(
        session
            .metadata
            .get("runtime.suspend_reason")
            .map(String::as_str),
        Some("awaiting_clarification")
    );
    assert!(session.agent_runtime_state.as_ref().is_some_and(|state| {
        matches!(state.status, bamboo_domain::AgentStatusState::Suspended)
    }));

    let first_detail = wait_for_runner_metrics(
        storage.as_ref(),
        session_id,
        1,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 7,
            completion_tokens: 2,
            total_tokens: 9,
        },
    )
    .await;
    let first_round_id = first_detail.rounds[0].round_id.clone();
    assert_eq!(first_detail.rounds[0].tool_calls.len(), 1);
    assert_eq!(
        first_detail.rounds[0].tool_calls[0].tool_call_id,
        "pause-call"
    );

    // Mirror the response boundary: the resolved question and suspend marker
    // are cleared, while the persisted Suspended control-plane state lets the
    // next invocation take the real resume path.
    session.clear_pending_question();
    session.metadata.remove("runtime.suspend_reason");

    let (second_tx, _second_rx) = mpsc::channel(64);
    super::run_agent_loop_with_config(
        &mut session,
        "yes".to_string(),
        second_tx,
        provider,
        tools,
        CancellationToken::new(),
        runner_metrics_config(&collector),
    )
    .await
    .expect("resumed execution");

    let detail = wait_for_runner_metrics(
        storage.as_ref(),
        session_id,
        3,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 25,
            completion_tokens: 7,
            total_tokens: 32,
        },
    )
    .await;
    let first = detail
        .rounds
        .iter()
        .find(|round| round.round_id == first_round_id)
        .expect("suspended round remains present");
    assert_eq!(first.tool_calls.len(), 1);
    assert_eq!(first.tool_calls[0].tool_call_id, "pause-call");
    assert_eq!(
        first.token_usage,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 7,
            completion_tokens: 2,
            total_tokens: 9,
        }
    );

    let resumed_tool_round = detail
        .rounds
        .iter()
        .find(|round| {
            round
                .tool_calls
                .iter()
                .any(|tool| tool.tool_call_id == "resume-call")
        })
        .expect("resume tool remains linked to its new round");
    assert_ne!(first.round_id, resumed_tool_round.round_id);
    assert_eq!(
        resumed_tool_round.token_usage,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 13,
            completion_tokens: 4,
            total_tokens: 17,
        }
    );
    assert_eq!(resumed_tool_round.tool_calls.len(), 1);
    assert_eq!(resumed_tool_round.tool_calls[0].tool_call_id, "resume-call");

    let final_round_id = session
        .agent_runtime_state
        .as_ref()
        .and_then(|state| state.round.last_round_id.as_deref())
        .expect("resumed final round id");
    let final_round = detail
        .rounds
        .iter()
        .find(|round| round.round_id == final_round_id)
        .expect("resumed final round remains present");
    assert_eq!(
        final_round.token_usage,
        bamboo_metrics::types::TokenUsage {
            prompt_tokens: 5,
            completion_tokens: 1,
            total_tokens: 6,
        }
    );
    assert!(final_round.tool_calls.is_empty());

    assert_eq!(
        metric_execution_prefix(&resumed_tool_round.round_id),
        metric_execution_prefix(&final_round.round_id),
        "all rounds in one resumed execution share the namespace"
    );
    assert_ne!(
        metric_execution_prefix(&first.round_id),
        metric_execution_prefix(&resumed_tool_round.round_id),
        "the resume receives a fresh execution namespace"
    );
    assert_eq!(
        session
            .agent_runtime_state
            .as_ref()
            .and_then(|state| state.round.last_round_id.as_deref()),
        Some(final_round.round_id.as_str())
    );
}

#[tokio::test]
async fn synthetic_provider_usage_reaches_read_only_hook_and_same_local_span() {
    use bamboo_agent_core::AgentHook;
    use bamboo_domain::{AgentHookPoint, HookPayload, HookResult, ModelCallStatus};
    struct Capture {
        sender: mpsc::UnboundedSender<bamboo_domain::ModelCallUsage>,
        birth: chrono::DateTime<Utc>,
    }
    #[async_trait]
    impl AgentHook for Capture {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterModelCallUsage
        }
        async fn run(
            &self,
            _: AgentHookPoint,
            payload: &HookPayload,
            session: &Session,
        ) -> HookResult {
            assert!(session.messages.is_empty());
            assert!(session.workspace.is_none());
            assert_eq!(session.created_at, self.birth);
            assert_eq!(session.root_session_id, "synthetic-usage-hook");
            if let HookPayload::ModelCallUsage { observation } = payload {
                self.sender.send(observation.clone()).unwrap();
            }
            HookResult::Abort {
                reason: "observer must not affect the call".into(),
            }
        }
    }
    let trace = bamboo_infrastructure::telemetry::test_support::LocalTraceTest::isolated();
    let mut session = Session::new("synthetic-usage-hook", "synthetic-model");
    let birth = session.created_at;
    let (observed_tx, mut observed_rx) = mpsc::unbounded_channel();
    let mut hooks = crate::runtime::hooks::HookRunner::new();
    hooks.register(Arc::new(Capture {
        sender: observed_tx,
        birth,
    }));
    let config = AgentLoopConfig {
        hook_runner: Arc::new(hooks),
        model_name: Some("synthetic-model".into()),
        system_prompt: Some("synthetic system prompt".into()),
        ..Default::default()
    };
    let provider = Arc::new(MetricsQueueProvider {
        queue: Mutex::new(vec![vec![
            Ok(LLMChunk::ProviderUsage {
                input_tokens: Some(100),
                output_tokens: Some(20),
                total_tokens: Some(120),
                reasoning_tokens: Some(3),
                cache_creation_input_tokens: None,
                cache_read_input_tokens: Some(0),
                cache_write_input_tokens: Some(12),
            }),
            Ok(LLMChunk::Token("synthetic answer".into())),
            Ok(LLMChunk::Done),
        ]]),
        requested_messages: Mutex::new(Vec::new()),
    });
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
        Arc::new(bamboo_tools::BuiltinToolExecutor::new());
    let (events, _receiver) = mpsc::channel(128);
    trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "PRIVATE_PROMPT_SENTINEL".into(),
            events,
            provider,
            tools,
            CancellationToken::new(),
            config,
        ))
        .await
        .expect("observer abort cannot reject the model call");
    let event = tokio::time::timeout(std::time::Duration::from_secs(2), observed_rx.recv())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(event.status, ModelCallStatus::Success);
    let usage = event.usage.unwrap();
    assert_eq!(usage.cache_read_input_tokens, Some(0));
    assert_eq!(usage.cache_creation_input_tokens, None);
    assert_eq!(usage.cache_write_input_tokens, Some(12));
    assert_eq!(usage.reasoning_tokens, Some(3));
    let page = trace.store.page(&session.id, birth, 10, None);
    let trace_id = event.trace_id.unwrap();
    assert_eq!(page.traces.len(), 1);
    assert_eq!(page.traces[0].trace_id, trace_id);
    let detail = trace.store.detail(&session.id, birth, &trace_id).unwrap();
    let span = detail
        .spans
        .iter()
        .find(|span| span.span_id == event.span_id.as_deref().unwrap())
        .unwrap();
    assert_eq!(span.call_id.as_deref(), Some(event.call_id.as_str()));
    assert_eq!(span.usage.as_ref(), Some(&usage));
    assert!(!serde_json::to_string(&detail)
        .unwrap()
        .contains("PRIVATE_PROMPT_SENTINEL"));
}

#[tokio::test]
async fn unsafe_session_id_keeps_usage_hook_and_local_span_correlated() {
    use bamboo_agent_core::AgentHook;
    use bamboo_domain::{AgentHookPoint, HookPayload, HookResult, ModelCallStatus};

    struct Capture(mpsc::UnboundedSender<bamboo_domain::ModelCallUsage>);
    #[async_trait]
    impl AgentHook for Capture {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterModelCallUsage
        }
        async fn run(
            &self,
            _: AgentHookPoint,
            payload: &HookPayload,
            session: &Session,
        ) -> HookResult {
            if let HookPayload::ModelCallUsage { observation } = payload {
                assert_eq!(session.id, observation.session_id);
                self.0.send(observation.clone()).unwrap();
            }
            HookResult::Continue
        }
    }

    let trace = bamboo_infrastructure::telemetry::test_support::LocalTraceTest::isolated();
    let mut session = Session::new("用户 会话", "synthetic-model");
    let birth = session.created_at;
    let (observed_tx, mut observed_rx) = mpsc::unbounded_channel();
    let mut hooks = crate::runtime::hooks::HookRunner::new();
    hooks.register(Arc::new(Capture(observed_tx)));
    let config = AgentLoopConfig {
        hook_runner: Arc::new(hooks),
        model_name: Some("synthetic-model".into()),
        system_prompt: Some("synthetic system".into()),
        ..Default::default()
    };
    let provider = Arc::new(MetricsQueueProvider {
        queue: Mutex::new(vec![vec![
            Ok(LLMChunk::ProviderUsage {
                input_tokens: Some(100),
                output_tokens: Some(7),
                total_tokens: Some(107),
                reasoning_tokens: None,
                cache_creation_input_tokens: None,
                cache_read_input_tokens: Some(0),
                cache_write_input_tokens: None,
            }),
            Ok(LLMChunk::Token("synthetic answer".into())),
            Ok(LLMChunk::Done),
        ]]),
        requested_messages: Mutex::new(Vec::new()),
    });
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
        Arc::new(bamboo_tools::BuiltinToolExecutor::new());
    let (events, _receiver) = mpsc::channel(128);
    trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "synthetic prompt".into(),
            events,
            provider,
            tools,
            CancellationToken::new(),
            config,
        ))
        .await
        .unwrap();
    let event = tokio::time::timeout(std::time::Duration::from_secs(2), observed_rx.recv())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(event.status, ModelCallStatus::Success);
    assert_eq!(
        event.session_id,
        bamboo_infrastructure::telemetry::session_reference(&session.id).unwrap()
    );
    assert!(event.session_id.starts_with('~'));
    let detail = trace
        .store
        .detail(&session.id, birth, event.trace_id.as_deref().unwrap())
        .unwrap();
    let span = detail
        .spans
        .iter()
        .find(|span| span.span_id == event.span_id.as_deref().unwrap())
        .unwrap();
    assert_eq!(span.call_id.as_deref(), Some(event.call_id.as_str()));
    // This synthetic ordinary run uses the raw session ID as its run ID.
    // It is omitted because it does not meet the telemetry identifier policy.
    assert!(event.run_id.is_none());
    assert_eq!(span.run_id, event.run_id);
    assert_eq!(span.usage, event.usage);
    assert!(!serde_json::to_string(&event).unwrap().contains(&session.id));
    assert!(!serde_json::to_string(&detail)
        .unwrap()
        .contains(&session.id));
}

#[tokio::test]
async fn partial_provider_failure_reports_one_usage_event_and_matching_error_span() {
    use bamboo_agent_core::AgentHook;
    use bamboo_domain::{AgentHookPoint, HookPayload, HookResult, ModelCallStatus};

    struct Capture(mpsc::UnboundedSender<bamboo_domain::ModelCallUsage>);
    #[async_trait]
    impl AgentHook for Capture {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterModelCallUsage
        }
        async fn run(&self, _: AgentHookPoint, payload: &HookPayload, _: &Session) -> HookResult {
            if let HookPayload::ModelCallUsage { observation } = payload {
                self.0.send(observation.clone()).unwrap();
            }
            HookResult::Continue
        }
    }

    let trace = bamboo_infrastructure::telemetry::test_support::LocalTraceTest::isolated();
    let mut session = Session::new("synthetic-partial-usage", "synthetic-model");
    let birth = session.created_at;
    let (observed_tx, mut observed_rx) = mpsc::unbounded_channel();
    // Keep the channel open after the dispatched observer finishes so that a
    // timeout proves no duplicate event arrived, rather than channel closure.
    let observer_sender_guard = observed_tx.clone();
    let mut hooks = crate::runtime::hooks::HookRunner::new();
    hooks.register(Arc::new(Capture(observed_tx)));
    let config = AgentLoopConfig {
        hook_runner: Arc::new(hooks),
        model_name: Some("synthetic-model".into()),
        system_prompt: Some("synthetic system".into()),
        ..Default::default()
    };
    let usage = LLMChunk::ProviderUsage {
        input_tokens: Some(100),
        output_tokens: Some(7),
        total_tokens: Some(107),
        reasoning_tokens: Some(2),
        cache_creation_input_tokens: None,
        cache_read_input_tokens: Some(0),
        cache_write_input_tokens: Some(12),
    };
    let provider = Arc::new(MetricsQueueProvider {
        queue: Mutex::new(vec![vec![
            Ok(LLMChunk::Token("synthetic partial answer".into())),
            Ok(usage.clone()),
            Ok(usage),
            Err(bamboo_llm::provider::LLMError::Stream(
                "synthetic interruption".into(),
            )),
        ]]),
        requested_messages: Mutex::new(Vec::new()),
    });
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
        Arc::new(bamboo_tools::BuiltinToolExecutor::new());
    let (events, _receiver) = mpsc::channel(128);
    let result = trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "PRIVATE_PROMPT_SENTINEL".into(),
            events,
            provider,
            tools,
            CancellationToken::new(),
            config,
        ))
        .await;
    assert!(result.is_err(), "partial stream failure must be surfaced");
    let event = tokio::time::timeout(std::time::Duration::from_secs(2), observed_rx.recv())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(event.status, ModelCallStatus::Error);
    let usage = event.usage.expect("observed partial provider usage");
    assert_eq!(usage.input_tokens, Some(100));
    assert_eq!(usage.output_tokens, Some(7));
    assert_eq!(usage.reasoning_tokens, Some(2));
    assert_eq!(usage.cache_read_input_tokens, Some(0));
    let detail = trace
        .store
        .detail(&session.id, birth, &event.trace_id.unwrap())
        .unwrap();
    let span = detail
        .spans
        .iter()
        .find(|span| span.span_id == event.span_id.as_deref().unwrap())
        .unwrap();
    assert_eq!(span.call_id.as_deref(), Some(event.call_id.as_str()));
    assert_eq!(span.status, "error");
    assert_eq!(span.usage.as_ref(), Some(&usage));
    assert!(!serde_json::to_string(&detail)
        .unwrap()
        .contains("PRIVATE_PROMPT_SENTINEL"));
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(100), observed_rx.recv())
            .await
            .is_err()
    );
    drop(observer_sender_guard);
}

#[tokio::test]
async fn anthropic_sse_error_preserves_reported_partial_usage() {
    use bamboo_agent_core::AgentHook;
    use bamboo_domain::{AgentHookPoint, HookPayload, HookResult, ModelCallStatus};
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};

    struct Capture(mpsc::UnboundedSender<bamboo_domain::ModelCallUsage>);
    #[async_trait]
    impl AgentHook for Capture {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterModelCallUsage
        }
        async fn run(&self, _: AgentHookPoint, payload: &HookPayload, _: &Session) -> HookResult {
            if let HookPayload::ModelCallUsage { observation } = payload {
                self.0.send(observation.clone()).unwrap();
            }
            HookResult::Continue
        }
    }

    for (start, delta, expected_input, expected_creation, expected_read) in [
        (
            r#"{"message":{"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_read_input_tokens":3}}}"#,
            r#"{"usage":{"output_tokens":7}}"#,
            Some(13),
            Some(0),
            Some(3),
        ),
        (
            r#"{"message":{"usage":{"input_tokens":10,"cache_creation_input_tokens":2,"cache_read_input_tokens":3}}}"#,
            r#"{"usage":{"output_tokens":7,"cache_read_input_tokens":-1}}"#,
            None,
            Some(2),
            None,
        ),
    ] {
        let body = format!(
            "event: message_start\ndata: {start}\n\n\
             event: content_block_start\ndata: {{\"index\":0,\"content_block\":{{\"type\":\"text\",\"text\":\"\"}}}}\n\n\
             event: content_block_delta\ndata: {{\"index\":0,\"delta\":{{\"type\":\"text_delta\",\"text\":\"synthetic partial\"}}}}\n\n\
             event: message_delta\ndata: {delta}\n\n\
             event: message_delta\ndata: {delta}\n\n\
             event: error\ndata: {{\"type\":\"error\",\"error\":{{\"type\":\"synthetic_error\"}}}}\n\n"
        );
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/event-stream")
                    .set_body_string(body),
            )
            .mount(&server)
            .await;
        let provider: Arc<dyn LLMProvider> = Arc::new(
            bamboo_llm::providers::anthropic::AnthropicProvider::new("synthetic-key")
                .with_base_url(server.uri()),
        );
        let trace = bamboo_infrastructure::telemetry::test_support::LocalTraceTest::isolated();
        let mut session = Session::new("synthetic-anthropic-interruption", "synthetic-model");
        let birth = session.created_at;
        let (sender, mut receiver) = mpsc::unbounded_channel();
        let sender_guard = sender.clone();
        let mut hooks = crate::runtime::hooks::HookRunner::new();
        hooks.register(Arc::new(Capture(sender)));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(hooks),
            provider_type: Some("anthropic".into()),
            model_name: Some("synthetic-model".into()),
            system_prompt: Some("synthetic system".into()),
            ..Default::default()
        };
        let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
            Arc::new(bamboo_tools::BuiltinToolExecutor::new());
        let (events, _receiver) = mpsc::channel(128);
        let result = trace
            .scope(super::run_agent_loop_with_config(
                &mut session,
                "PRIVATE_PROMPT_SENTINEL".into(),
                events,
                provider,
                tools,
                CancellationToken::new(),
                config,
            ))
            .await;
        assert!(matches!(
            result,
            Err(bamboo_agent_core::AgentError::LLMNonRetryable(message))
                if message.contains("synthetic_error")
        ));
        let event = tokio::time::timeout(std::time::Duration::from_secs(2), receiver.recv())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(event.status, ModelCallStatus::Error);
        let usage = event.usage.as_ref().expect("reported partial usage");
        assert_eq!(usage.input_tokens, expected_input);
        assert_eq!(usage.output_tokens, Some(7));
        assert_eq!(usage.cache_creation_input_tokens, expected_creation);
        assert_eq!(usage.cache_read_input_tokens, expected_read);
        let detail = trace
            .store
            .detail(&session.id, birth, event.trace_id.as_deref().unwrap())
            .unwrap();
        let span = detail
            .spans
            .iter()
            .find(|span| span.span_id == event.span_id.as_deref().unwrap())
            .unwrap();
        assert_eq!(span.status, "error");
        assert_eq!(span.usage.as_ref(), Some(usage));
        assert!(!serde_json::to_string(&detail)
            .unwrap()
            .contains("PRIVATE_PROMPT_SENTINEL"));
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(100), receiver.recv())
                .await
                .is_err()
        );
        drop(sender_guard);
    }
}

async fn gemini_usage_after_frames(
    frames: &[&str],
) -> (
    bamboo_domain::ModelTokenUsage,
    Option<bamboo_agent_core::ProviderPromptUsage>,
) {
    gemini_usage_after_frames_inner(frames, false).await
}

async fn gemini_usage_after_frames_inner(
    frames: &[&str],
    content_frames: bool,
) -> (
    bamboo_domain::ModelTokenUsage,
    Option<bamboo_agent_core::ProviderPromptUsage>,
) {
    use bamboo_agent_core::AgentHook;
    use bamboo_domain::{AgentHookPoint, HookPayload, HookResult, ModelCallStatus};
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};

    struct Capture(mpsc::UnboundedSender<bamboo_domain::ModelCallUsage>);
    #[async_trait]
    impl AgentHook for Capture {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterModelCallUsage
        }
        async fn run(&self, _: AgentHookPoint, payload: &HookPayload, _: &Session) -> HookResult {
            if let HookPayload::ModelCallUsage { observation } = payload {
                self.0.send(observation.clone()).unwrap();
            }
            HookResult::Continue
        }
    }

    let mut body = concat!(
        "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"synthetic answer\"}]},\"finishReason\":\"STOP\"}],",
        "\"usageMetadata\":{\"promptTokenCount\":100,\"cachedContentTokenCount\":25,",
        "\"candidatesTokenCount\":20,\"thoughtsTokenCount\":3,\"totalTokenCount\":123}}\n\n"
    ).to_string();
    if content_frames {
        body = body.replace(",\"finishReason\":\"STOP\"", "");
    }
    for usage in frames {
        if content_frames {
            body.push_str(&format!(
                "data: {{\"candidates\":[{{\"content\":{{\"parts\":[{{\"text\":\"continuing\"}}]}}}}],\"usageMetadata\":{usage}}}\n\n"
            ));
        } else {
            body.push_str(&format!(
                "data: {{\"candidates\":[],\"usageMetadata\":{usage}}}\n\n"
            ));
        }
    }
    if content_frames {
        body.push_str("data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"done\"}]},\"finishReason\":\"STOP\"}]}\n\n");
    }
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_string(body),
        )
        .mount(&server)
        .await;
    let provider: Arc<dyn LLMProvider> = Arc::new(
        bamboo_llm::providers::gemini::GeminiProvider::new("synthetic-key")
            .with_base_url(server.uri()),
    );
    let trace = bamboo_infrastructure::telemetry::test_support::LocalTraceTest::isolated();
    let mut session = Session::new("synthetic-gemini-repeated-usage", "synthetic-model");
    let birth = session.created_at;
    let (sender, mut receiver) = mpsc::unbounded_channel();
    let sender_guard = sender.clone();
    let mut hooks = crate::runtime::hooks::HookRunner::new();
    hooks.register(Arc::new(Capture(sender)));
    let config = AgentLoopConfig {
        hook_runner: Arc::new(hooks),
        provider_type: Some("gemini".into()),
        model_name: Some("synthetic-model".into()),
        system_prompt: Some("synthetic system".into()),
        ..Default::default()
    };
    let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
        Arc::new(bamboo_tools::BuiltinToolExecutor::new());
    let (events, mut event_receiver) = mpsc::channel(128);
    trace
        .scope(super::run_agent_loop_with_config(
            &mut session,
            "PRIVATE_PROMPT_SENTINEL".into(),
            events,
            provider,
            tools,
            CancellationToken::new(),
            config,
        ))
        .await
        .expect("synthetic Gemini call");
    let event = tokio::time::timeout(std::time::Duration::from_secs(2), receiver.recv())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(event.status, ModelCallStatus::Success);
    let usage = event.usage.expect("other provider counters remain known");
    let detail = trace
        .store
        .detail(&session.id, birth, event.trace_id.as_deref().unwrap())
        .unwrap();
    let span = detail
        .spans
        .iter()
        .find(|span| span.span_id == event.span_id.as_deref().unwrap())
        .unwrap();
    assert_eq!(span.usage.as_ref(), Some(&usage));
    assert!(!serde_json::to_string(&detail)
        .unwrap()
        .contains("PRIVATE_PROMPT_SENTINEL"));
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(100), receiver.recv())
            .await
            .is_err()
    );
    drop(sender_guard);
    let mut final_prompt = None;
    while let Ok(event) = event_receiver.try_recv() {
        if let bamboo_agent_core::AgentEvent::TokenBudgetUpdated { usage } = event {
            final_prompt = Some(usage.provider_prompt_usage);
        }
    }
    (usage, final_prompt.expect("final token budget event"))
}

#[tokio::test]
async fn gemini_nonterminal_content_frames_update_hook_and_span_usage() {
    let (invalid, prompt) =
        gemini_usage_after_frames_inner(&[r#"{"cachedContentTokenCount":-1}"#], true).await;
    assert_eq!(invalid.input_tokens, Some(100));
    assert_eq!(invalid.output_tokens, Some(23));
    assert_eq!(invalid.cache_read_input_tokens, None);
    assert!(prompt.is_none());
    let (recovered, prompt) = gemini_usage_after_frames_inner(
        &[
            r#"{"cachedContentTokenCount":-1}"#,
            r#"{"cachedContentTokenCount":0}"#,
        ],
        true,
    )
    .await;
    assert_eq!(recovered.cache_read_input_tokens, Some(0));
    assert_eq!(prompt.unwrap().cache_read_input_tokens, 0);
}

#[tokio::test]
async fn gemini_malformed_repeated_cache_is_unknown_in_hook_and_span() {
    let (usage, prompt) = gemini_usage_after_frames(&[r#"{"cachedContentTokenCount":-1}"#]).await;
    assert_eq!(usage.input_tokens, Some(100));
    assert_eq!(usage.output_tokens, Some(23));
    assert_eq!(usage.reasoning_tokens, Some(3));
    assert_eq!(usage.cache_read_input_tokens, None);
    assert!(
        prompt.is_none(),
        "unknown cache must not look like a zero-percent ratio"
    );
}

#[tokio::test]
async fn gemini_malformed_repeated_reasoning_invalidates_output_in_hook_and_span() {
    let (usage, _) = gemini_usage_after_frames(&[r#"{"thoughtsTokenCount":null}"#]).await;
    assert_eq!(usage.input_tokens, Some(100));
    assert_eq!(usage.cache_read_input_tokens, Some(25));
    assert_eq!(usage.reasoning_tokens, None);
    assert_eq!(usage.output_tokens, None);
}

#[tokio::test]
async fn gemini_malformed_repeated_input_is_unknown_in_hook_and_span() {
    let (usage, prompt) = gemini_usage_after_frames(&[r#"{"promptTokenCount":"invalid"}"#]).await;
    assert_eq!(usage.input_tokens, None);
    assert_eq!(usage.output_tokens, Some(23));
    assert_eq!(usage.cache_read_input_tokens, Some(25));
    assert!(
        prompt.is_none(),
        "unknown input must not be an exact prompt"
    );
}

#[tokio::test]
async fn gemini_later_zero_restores_invalid_cache_without_erasing_omitted_fields() {
    let (usage, prompt) = gemini_usage_after_frames(&[
        r#"{"cachedContentTokenCount":-1}"#,
        r#"{"cachedContentTokenCount":0}"#,
    ])
    .await;
    assert_eq!(usage.input_tokens, Some(100));
    assert_eq!(usage.output_tokens, Some(23));
    assert_eq!(usage.reasoning_tokens, Some(3));
    assert_eq!(usage.cache_read_input_tokens, Some(0));
    assert_eq!(prompt.unwrap().cache_read_input_tokens, 0);
}

#[tokio::test]
async fn synthetic_anthropic_and_gemini_streams_reach_usage_hook_and_local_span() {
    use bamboo_agent_core::AgentHook;
    use bamboo_domain::{AgentHookPoint, HookPayload, HookResult};
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};

    struct Capture(mpsc::UnboundedSender<bamboo_domain::ModelCallUsage>);
    #[async_trait]
    impl AgentHook for Capture {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterModelCallUsage
        }
        async fn run(&self, _: AgentHookPoint, payload: &HookPayload, _: &Session) -> HookResult {
            if let HookPayload::ModelCallUsage { observation } = payload {
                self.0.send(observation.clone()).unwrap();
            }
            HookResult::Continue
        }
    }

    let anthropic = concat!(
        "event: message_start\ndata: {\"message\":{\"usage\":{\"input_tokens\":10,\"cache_creation_input_tokens\":2,\"cache_read_input_tokens\":3}}}\n\n",
        "event: content_block_start\ndata: {\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
        "event: content_block_delta\ndata: {\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"synthetic answer\"}}\n\n",
        "event: content_block_stop\ndata: {\"index\":0}\n\n",
        "event: message_delta\ndata: {\"usage\":{\"output_tokens\":7}}\n\n",
        "event: message_stop\ndata: {}\n\n",
    );
    let gemini = "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"synthetic answer\"}]},\"finishReason\":\"STOP\"}],\"usageMetadata\":{\"promptTokenCount\":100,\"cachedContentTokenCount\":25,\"candidatesTokenCount\":20,\"thoughtsTokenCount\":3,\"totalTokenCount\":123}}\n\n";
    for (
        family,
        body,
        expected_input,
        expected_output,
        expected_read,
        expected_creation,
        expected_reasoning,
    ) in [
        ("anthropic", anthropic, 15, 7, 3, Some(2), None),
        ("gemini", gemini, 100, 23, 25, None, Some(3)),
    ] {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/event-stream")
                    .set_body_string(body),
            )
            .mount(&server)
            .await;
        let provider: Arc<dyn LLMProvider> = match family {
            "anthropic" => Arc::new(
                bamboo_llm::providers::anthropic::AnthropicProvider::new("synthetic-key")
                    .with_base_url(server.uri()),
            ),
            _ => Arc::new(
                bamboo_llm::providers::gemini::GeminiProvider::new("synthetic-key")
                    .with_base_url(server.uri()),
            ),
        };
        let trace = bamboo_infrastructure::telemetry::test_support::LocalTraceTest::isolated();
        let mut session = Session::new(&format!("synthetic-{family}"), "synthetic-model");
        let birth = session.created_at;
        let (observed_tx, mut observed_rx) = mpsc::unbounded_channel();
        let mut hooks = crate::runtime::hooks::HookRunner::new();
        hooks.register(Arc::new(Capture(observed_tx)));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(hooks),
            provider_type: Some(family.into()),
            model_name: Some("synthetic-model".into()),
            system_prompt: Some("synthetic system".into()),
            ..Default::default()
        };
        let tools: Arc<dyn bamboo_agent_core::tools::ToolExecutor> =
            Arc::new(bamboo_tools::BuiltinToolExecutor::new());
        let (events, _receiver) = mpsc::channel(128);
        trace
            .scope(super::run_agent_loop_with_config(
                &mut session,
                "PRIVATE_PROMPT_SENTINEL".into(),
                events,
                provider,
                tools,
                CancellationToken::new(),
                config,
            ))
            .await
            .expect("synthetic provider call");
        let event = tokio::time::timeout(std::time::Duration::from_secs(2), observed_rx.recv())
            .await
            .unwrap()
            .unwrap();
        let usage = event.usage.expect("provider snapshot");
        assert_eq!(usage.input_tokens, Some(expected_input));
        assert_eq!(usage.output_tokens, Some(expected_output));
        assert_eq!(usage.cache_read_input_tokens, Some(expected_read));
        assert_eq!(usage.cache_creation_input_tokens, expected_creation);
        assert_eq!(usage.reasoning_tokens, expected_reasoning);
        let detail = trace
            .store
            .detail(&session.id, birth, &event.trace_id.unwrap())
            .unwrap();
        let span = detail
            .spans
            .iter()
            .find(|span| span.call_id.as_deref() == Some(event.call_id.as_str()))
            .unwrap();
        assert_eq!(span.usage.as_ref(), Some(&usage));
        assert!(!serde_json::to_string(&detail)
            .unwrap()
            .contains("PRIVATE_PROMPT_SENTINEL"));
        assert!(observed_rx.try_recv().is_err(), "one event per model call");
    }
}