bamboo-engine 2026.10.13

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
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
use std::sync::Arc;

use tokio::sync::mpsc;

use crate::runtime::config::AgentLoopConfig;
use crate::runtime::task_context::TaskLoopContext;
use bamboo_agent_core::tools::{
    parse_tool_args_best_effort, tool_start_arguments_for_display, ExecutingSupervisorObservation,
    ToolCall, ToolExecutionContext, ToolExecutionSessionFlags, ToolExecutor, ToolOutcome,
    ToolResult, ToolSchema,
};
use bamboo_agent_core::{AgentError, AgentEvent, Session};
use bamboo_domain::{
    AgentHookPoint, AgentRuntimeState, EffectiveCallableSet, HookPayload, HookResult,
    HookToolOutcome,
};
use bamboo_metrics::MetricsCollector;

use super::execution_paths;
use super::loop_state::RoundExecutionState;
use super::policy;
use crate::session_app::approval_replay::PermissionReplayOrigin;

fn preview_for_log(value: &str, max_chars: usize) -> String {
    let mut iter = value.chars();
    let mut preview = String::new();
    for _ in 0..max_chars {
        match iter.next() {
            Some(ch) => preview.push(ch),
            None => break,
        }
    }
    if iter.next().is_some() {
        preview.push_str("...");
    }
    preview.replace('\n', "\\n").replace('\r', "\\r")
}

fn parse_warning_log_details<'a>(
    execution_name: &str,
    raw_arguments: &str,
    warning: &'a str,
) -> (String, &'a str) {
    if execution_name.eq_ignore_ascii_case("browser")
        || execution_name.eq_ignore_ascii_case("browser_eval")
        || execution_name.eq_ignore_ascii_case("session_message")
        || [
            "work_overview",
            "work_search",
            "work_inspect",
            "work_changes",
            "work_update",
            "work_dispatch",
        ]
        .iter()
        .any(|name| execution_name.eq_ignore_ascii_case(name))
    {
        ("[redacted]".to_string(), "[redacted]")
    } else {
        (preview_for_log(raw_arguments, 180), warning)
    }
}

fn tool_start_name_for_display(tool_name: &str) -> String {
    if tool_name
        .trim()
        .rsplit("::")
        .next()
        .is_some_and(|name| name.eq_ignore_ascii_case("browser"))
    {
        "browser".to_string()
    } else {
        tool_name.to_string()
    }
}

pub(super) struct ToolExecutionOnlyContext<'a> {
    pub vision_support: bool,
    pub tool_call: &'a ToolCall,
    pub event_tx: &'a mpsc::Sender<AgentEvent>,
    pub metrics_collector: Option<&'a MetricsCollector>,
    pub session_id: &'a str,
    /// Immutable parallel-window projection, used only without a hook Session.
    /// Sequential calls reread the actual Session after all continuing hooks.
    pub output_cap: Option<u32>,
    /// Snapshotted from the durable Root authority at this dispatch boundary.
    /// A parallel batch shares one snapshot across its already-admitted calls.
    pub root_orchestration_only: bool,
    /// Root-session identity snapshotted from the executing Session before any
    /// parallel dispatch borrow begins.
    pub root_session_id: &'a str,
    /// Original executing lifetime captured before this call is handed off.
    pub executing_supervisor: Option<ExecutingSupervisorObservation>,
    pub round_id: &'a str,
    pub round: usize,
    pub tools: &'a Arc<dyn ToolExecutor>,
    pub config: &'a AgentLoopConfig,
    /// Always present on the sequential path, including when portable hooks
    /// are enabled after admission. Parallel-safe calls cannot borrow mutable
    /// session state and fail closed if hooks become active before execution.
    pub hook_session: Option<&'a mut Session>,
    pub hook_runtime_state: Option<&'a mut AgentRuntimeState>,
    /// Per-session execution flags (e.g. bypass permissions), derived from the
    /// session via `ToolExecutionSessionFlags::from_session` at the call site
    /// and threaded through so this (parallel-safe) path can apply them without
    /// borrowing the session.
    pub session_flags: ToolExecutionSessionFlags,
    /// Snapshot of every tool schema the executor exposes for THIS round, built
    /// once per round (in `execute_round_tool_calls`) rather than re-cloned on
    /// every single tool call. Passed straight into the dispatch context's
    /// `available_tool_schemas`. Scoped to the round — never global/static — so
    /// one session's tool set can't leak into another. ASSUMPTION: the
    /// executor's tool set is stable for the duration of a round (the agent loop
    /// only registers hooks mid-round, never tools), so the snapshot equals what
    /// a fresh `list_tools()` would return on every call. It is consumed only by
    /// `for_dispatch`, which threads it into the dispatch context's
    /// `available_tool_schemas` — a metadata field no builtin tool currently
    /// inspects — so even a hypothetical divergence would be unobservable today.
    pub available_tool_schemas: &'a [ToolSchema],
}

pub(super) struct ToolExecutionApplyContext<'a> {
    pub policy_guard: &'a mut policy::ToolPolicyGuard,
    pub admitted_execution_name: Option<&'a str>,
    pub tool_call: &'a ToolCall,
    pub event_tx: &'a mpsc::Sender<AgentEvent>,
    pub metrics_collector: Option<&'a MetricsCollector>,
    pub session_id: &'a str,
    pub round_id: &'a str,
    pub round: usize,
    pub session: &'a mut Session,
    pub tools: &'a Arc<dyn ToolExecutor>,
    pub session_flags: ToolExecutionSessionFlags,
    pub config: &'a AgentLoopConfig,
    pub runtime_state: &'a mut AgentRuntimeState,
    pub task_context: &'a mut Option<TaskLoopContext>,
    pub state: &'a mut RoundExecutionState,
}

pub(super) struct PortableToolExecution {
    name: String,
    input: serde_json::Value,
}

impl PortableToolExecution {
    pub(super) fn execution_name(&self) -> &str {
        &self.name
    }
}

#[cfg(test)]
impl PortableToolExecution {
    /// Declare an already-selected executor identity for result-contract tests.
    /// Model catalog admission is covered separately by the promotion tests.
    pub(super) fn selected_identity_fixture(execution_name: &str) -> Self {
        Self {
            name: execution_name.to_owned(),
            input: serde_json::json!({}),
        }
    }
}

pub(super) fn portable_tool_for_admitted_call(
    callable: &EffectiveCallableSet,
    call: &ToolCall,
) -> Option<PortableToolExecution> {
    // Timeout synthesis uses the same immutable admission snapshot as dispatch,
    // never a later catalog or a generic name normalizer.
    callable
        .resolve_callable_reference(&call.function.name)
        .map(|name| PortableToolExecution {
            name,
            input: parse_tool_args_best_effort(&call.function.arguments).0,
        })
}

pub(super) struct ToolExecutionOutcome {
    /// Exact dispatch observation for the original compressor. None means no
    /// retained capture (also synthesized timeout), not proof of non-execution.
    /// Some(None) is a real dispatch with an unknown cap; zero remains known.
    pub output_cap: Option<Option<u32>>,
    /// The exact selected executor and arguments supplied to it, carried through
    /// result application without resolving model-controlled aliases a second time.
    pub portable_tool: Option<PortableToolExecution>,
    pub permission_replay_origin: Option<PermissionReplayOrigin>,
    pub result: Result<ToolResult, String>,
    /// Set when the tool returned [`ToolOutcome::NeedsHuman`] — the structured
    /// pending question the loop suspends on (its display `result` is carried in
    /// `result` above, so the compressor/policy path is unchanged). Handled in
    /// [`apply_tool_execution_outcome`] before the normal success path.
    pub needs_human: Option<bamboo_agent_core::PendingQuestion>,
    /// True only after a terminal executor outcome (`Completed` or an execution
    /// error). Pre-dispatch blocks, `Running`, and `NeedsHuman` do not represent
    /// a completed tool and must not fire `PostToolUse`.
    pub post_tool_hook_eligible: bool,
    /// Host-only typed fault; never inferred from a model/tool result string.
    pub managed_running_violation: bool,
    pub tool_duration: std::time::Duration,
}

pub(super) enum ShellAccountingOutcome {
    Ordinary,
    Pending,
    Terminal(bool),
}

pub(super) fn shell_accounting_outcome(
    outcome: &ToolExecutionOutcome,
    admitted_execution_name: Option<&str>,
) -> ShellAccountingOutcome {
    if !matches!(
        outcome
            .portable_tool
            .as_ref()
            .map(|tool| tool.execution_name())
            .or(admitted_execution_name),
        Some("exec_command" | "write_stdin")
    ) {
        return ShellAccountingOutcome::Ordinary;
    }
    if outcome.needs_human.is_some() {
        return ShellAccountingOutcome::Pending;
    }
    let Ok(result) = &outcome.result else {
        // Infrastructure/argument errors retain ordinary failure accounting.
        return ShellAccountingOutcome::Ordinary;
    };
    // The permission gate uses a Completed acknowledgement while the command
    // remains unexecuted. Its pause marker survives output compression, unlike
    // the JSON body; use the same success/marker contract as clarification.
    if result.success && result.display_preference.as_deref() == Some("request_permissions") {
        return ShellAccountingOutcome::Pending;
    }
    let envelope = serde_json::from_str::<serde_json::Value>(&result.result).ok();
    let status = envelope.as_ref().and_then(|value| value["status"].as_str());
    if status == Some("running") {
        return ShellAccountingOutcome::Pending;
    }
    ShellAccountingOutcome::Terminal(
        result.success
            && status == Some("completed")
            && envelope
                .as_ref()
                .and_then(|value| value["exit_code"].as_i64())
                == Some(0),
    )
}

fn task_progress_result_for_outcome(
    outcome: &ToolExecutionOutcome,
) -> execution_paths::TaskProgressResult {
    use execution_paths::TaskProgressResult;

    match shell_accounting_outcome(outcome, None) {
        ShellAccountingOutcome::Ordinary => TaskProgressResult::Ordinary,
        ShellAccountingOutcome::Pending => TaskProgressResult::Skip,
        ShellAccountingOutcome::Terminal(success) => {
            let mut result = outcome
                .result
                .as_ref()
                .expect("terminal shell result")
                .clone();
            result.success = success;
            TaskProgressResult::CommandOutcome(result)
        }
    }
}

/// Admit one model-requested function call before it enters Bamboo's existing
/// tool execution pipeline.
///
/// Capability loading changes availability only: an admitted call retains its
/// original spelling and continues through the exact same argument, event,
/// hook, permission, and executor path below. A rejected call is represented as
/// an ordinary per-call outcome so sibling calls in a parallel batch keep
/// running and the normal result-application path can append the corresponding
/// tool error without emitting `ToolStart` or entering downstream hooks.
pub(super) async fn execute_model_requested_tool_call_only(
    effective_callable_set: &EffectiveCallableSet,
    ctx: ToolExecutionOnlyContext<'_>,
) -> Result<ToolExecutionOutcome, AgentError> {
    let Some(execution_name) =
        effective_callable_set.resolve_callable_reference(&ctx.tool_call.function.name)
    else {
        let message = format!(
            "Tool '{}' is not callable at the current conversation position",
            ctx.tool_call.function.name
        );
        tracing::warn!(
            "[{}][round:{}] Tool call rejected by capability loading before ToolStart: tool_call_id={}, tool_name={}",
            ctx.session_id,
            ctx.round,
            ctx.tool_call.id,
            ctx.tool_call.function.name,
        );
        return Ok(ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Err(message),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: false,
            managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        });
    };

    execute_tool_call_only_with_execution_name(&execution_name, ctx).await
}

#[cfg(test)]
pub(super) async fn execute_tool_call_only(
    ctx: ToolExecutionOnlyContext<'_>,
) -> Result<ToolExecutionOutcome, AgentError> {
    let execution_name = ctx.tool_call.function.name.clone();
    execute_tool_call_only_with_execution_name(&execution_name, ctx).await
}

async fn execute_tool_call_only_with_execution_name(
    execution_name: &str,
    ctx: ToolExecutionOnlyContext<'_>,
) -> Result<ToolExecutionOutcome, AgentError> {
    let noninteractive = crate::runtime::loop_control::suspension::active(ctx.config);
    let control = ctx.config.loop_control.as_ref();
    let dispatch = execute_tool_call_only_with_execution_name_inner(execution_name, ctx);
    if let Some(control) = control {
        let (outcome, observation) =
            bamboo_agent_core::tools::observe_tool_suspension(noninteractive, dispatch).await;
        if observation.running_seen {
            control.record_running_observed();
        }
        let mut outcome = outcome?;
        if observation.forbidden_running_seen {
            if let Some(resources) = bamboo_tools::LocalTaskResources::current() {
                resources
                    .record_unconfirmed(crate::runtime::loop_control::suspension::RUNNING_REFUSAL);
            }
            outcome.result = Err(crate::runtime::loop_control::suspension::RUNNING_REFUSAL.into());
            outcome.needs_human = None;
            outcome.post_tool_hook_eligible = false;
            outcome.managed_running_violation = true;
        }
        Ok(outcome)
    } else {
        dispatch.await
    }
}

async fn execute_tool_call_only_with_execution_name_inner(
    execution_name: &str,
    mut ctx: ToolExecutionOnlyContext<'_>,
) -> Result<ToolExecutionOutcome, AgentError> {
    // Recheck the resolved exact executor identity even if the provider cites a
    // stale schema or the round's EffectiveCallableSet predates live tightening.
    // Reject before ToolStart, hooks, replay handling, and executor entry.
    let executing_supervisor = ctx.executing_supervisor.is_some()
        && ctx.session_id == bamboo_domain::DEFAULT_SUPERVISOR_SESSION_ID
        && ctx.root_session_id == ctx.session_id;
    // Filtering a registered exact identity out of the model catalog must
    // not turn its spelling into a compatibility alias for another owner.
    let reference = ctx.tool_call.function.name.trim();
    let exact_owner_shadowed = reference != execution_name && ctx.tools.owns_exact_tool(reference);
    if (ctx.root_orchestration_only || executing_supervisor)
        && (exact_owner_shadowed
            || !bamboo_domain::orchestration_only_allows_execution_name_for_supervisor(
                execution_name,
                executing_supervisor,
            ))
    {
        tracing::warn!(
            "[{}][round:{}] Tool call rejected by Root authority before ToolStart: tool_call_id={}, tool_name={}, execution_name={}",
            ctx.session_id,
            ctx.round,
            ctx.tool_call.id,
            ctx.tool_call.function.name,
            execution_name,
        );
        return Ok(ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: false,
            managed_running_violation: false,
            result: Err(if executing_supervisor {
                format!("supervisor_delegation_required: Tool '{}' is outside Supervisor orchestration authority. Delegate execution to an authorized worker. If unavailable or denied, report the actual recoverable blocker; do not self-execute or retry unchanged delegation indefinitely.", ctx.tool_call.function.name)
            } else {
                format!(
                    "Tool '{}' is outside orchestration-only Root authority",
                    ctx.tool_call.function.name
                )
            }),
            tool_duration: std::time::Duration::ZERO,
        });
    }

    if let Err(policy_error) =
        policy::validate_tool_call_arguments_for_execution(ctx.tool_call, execution_name)
    {
        tracing::warn!(
            "[{}][round:{}] Tool call blocked by strict argument policy before ToolStart: tool_call_id={}, tool_name={}, error={}",
            ctx.session_id,
            ctx.round,
            ctx.tool_call.id,
            ctx.tool_call.function.name,
            policy_error
        );
        return Ok(ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: false,
            managed_running_violation: false,
            result: Err(policy_error),
            tool_duration: std::time::Duration::ZERO,
        });
    }

    let vision_target = if execution_name == "ViewImage" && !ctx.vision_support {
        match crate::runtime::runner::image_fallback::resolve_vision_target(ctx.config).await {
            Ok(target) => Some(target),
            Err(error) => {
                return Ok(ToolExecutionOutcome {
                    output_cap: None,
                    permission_replay_origin: None,
                    result: Err(error.to_string()),
                    needs_human: None,
                    portable_tool: None,
                    post_tool_hook_eligible: false,
                    managed_running_violation: false,
                    tool_duration: std::time::Duration::ZERO,
                })
            }
        }
    } else {
        None
    };

    let raw_arguments = ctx.tool_call.function.arguments.trim();
    let (args, parse_warning) = parse_tool_args_best_effort(&ctx.tool_call.function.arguments);
    if let Some(warning) = parse_warning {
        let (args_preview, warning) =
            parse_warning_log_details(execution_name, raw_arguments, &warning);
        tracing::warn!(
            "[{}][round:{}] Tool call arguments required fallback before ToolStart: tool_call_id={}, tool_name={}, args_len={}, args_preview=\"{}\", warning={}",
            ctx.session_id,
            ctx.round,
            ctx.tool_call.id,
            ctx.tool_call.function.name,
            raw_arguments.len(),
            args_preview,
            warning
        );
    }

    tracing::debug!(
        "[{}][round:{}] Starting tool execution: tool_call_id={}, tool_name={}, raw_args_len={}",
        ctx.session_id,
        ctx.round,
        ctx.tool_call.id,
        tool_start_name_for_display(&ctx.tool_call.function.name),
        raw_arguments.len()
    );

    super::events::send_event_with_metrics(
        ctx.event_tx,
        ctx.metrics_collector,
        ctx.session_id,
        ctx.round_id,
        AgentEvent::ToolStart {
            tool_call_id: ctx.tool_call.id.clone(),
            tool_name: tool_start_name_for_display(&ctx.tool_call.function.name),
            arguments: tool_start_arguments_for_display(execution_name, &args),
        },
    )
    .await;

    // ── ToolEmitter: track lifecycle events ─────────────────────────────
    let tool_name = ctx.tool_call.function.name.trim();
    let is_mutating = bamboo_tools::orchestrator::classify_tool(tool_name)
        == bamboo_tools::orchestrator::ToolMutability::Mutating;
    let mut emitter =
        bamboo_tools::events::ToolEmitter::new(&ctx.tool_call.id, tool_name, is_mutating);
    emitter.set_auto_approved(!is_mutating);
    let begin_event = emitter.begin().clone();
    // Push lifecycle "begin" through the AgentEvent channel for UI visibility
    if let Err(e) = ctx.event_tx.send(begin_event.into_agent_event()).await {
        tracing::warn!(
            "[{}] tool lifecycle begin event send failed: {}",
            ctx.session_id,
            e
        );
    }

    let tool_timer = std::time::Instant::now();
    let mut permission_override = None;

    if ctx
        .config
        .hook_runner
        .has_hooks_for(AgentHookPoint::BeforeToolExecution)
    {
        let (Some(session), Some(runtime_state)) = (
            ctx.hook_session.as_deref_mut(),
            ctx.hook_runtime_state.as_deref_mut(),
        ) else {
            // A review can enable portable hooks after this parallel batch was
            // admitted without mutable hook state. Do not panic or bypass the
            // newly active policy; the next admission can run sequentially.
            let reason = "Tool hooks became active after parallel admission; retry the tool call"
                .to_string();
            let end_event = emitter.error(reason.clone()).clone();
            let _ = ctx.event_tx.send(end_event.into_agent_event()).await;
            return Ok(ToolExecutionOutcome {
                output_cap: None,
                permission_replay_origin: None,
                result: Err(reason),
                needs_human: None,
                portable_tool: None,
                post_tool_hook_eligible: false,
                managed_running_violation: false,
                tool_duration: tool_timer.elapsed(),
            });
        };
        let payload = HookPayload::ToolExecution {
            tool_name: ctx.tool_call.function.name.clone(),
            tool_call_id: ctx.tool_call.id.clone(),
            parsed_args: args.clone(),
        };
        let mut hook_outcome = ctx
            .config
            .hook_runner
            .run_hooks_with_inputs(
                AgentHookPoint::BeforeToolExecution,
                &payload,
                session,
                runtime_state,
                Some(ctx.event_tx),
                bamboo_hooks::portable::PortableInputs {
                    resolved_tool_name: Some(execution_name),
                    original_tool_input: Some(&args),
                    ..Default::default()
                },
            )
            .await;

        crate::runtime::hooks::inject_plugin_contexts(
            session,
            std::mem::take(&mut hook_outcome.plugin_contexts),
        );
        match hook_outcome.decision.clone() {
            HookResult::Deny { reason } => {
                crate::runtime::hooks::inject_contexts(
                    session,
                    AgentHookPoint::BeforeToolExecution,
                    hook_outcome.injected_contexts,
                );
                let elapsed = tool_timer.elapsed();
                let end_event = emitter.error(reason.clone()).clone();
                let _ = ctx.event_tx.send(end_event.into_agent_event()).await;
                return Ok(ToolExecutionOutcome {
                    output_cap: None,
                    permission_replay_origin: None,
                    result: Err(format!("Tool execution denied by hook: {reason}")),
                    needs_human: None,
                    portable_tool: None,
                    post_tool_hook_eligible: false,
                    managed_running_violation: false,
                    tool_duration: elapsed,
                });
            }
            HookResult::Ask => {
                crate::runtime::hooks::inject_contexts(
                    session,
                    AgentHookPoint::BeforeToolExecution,
                    hook_outcome.injected_contexts,
                );
                if ctx.session_flags.auto_approve_permissions {
                    permission_override = Some(bamboo_tools::HookPermissionOverride::Allow);
                } else if let Some(outcome) = hook_ask_outcome(
                    ctx.tool_call,
                    execution_name,
                    ctx.config,
                    session,
                    runtime_state,
                    &args,
                )
                .await
                {
                    let end_event = match &outcome.result {
                        Ok(_) => emitter
                            .finish(Some("waiting for parent review".to_string()))
                            .clone(),
                        Err(error) => emitter.error(error.clone()).clone(),
                    };
                    let _ = ctx.event_tx.send(end_event.into_agent_event()).await;
                    return Ok(outcome);
                }
            }
            HookResult::Allow => {
                crate::runtime::hooks::apply_hook_outcome(
                    AgentHookPoint::BeforeToolExecution,
                    hook_outcome,
                    session,
                    runtime_state,
                )?;
                permission_override = Some(bamboo_tools::HookPermissionOverride::Allow);
            }
            _ => {
                if let Err(error) = crate::runtime::hooks::apply_hook_outcome(
                    AgentHookPoint::BeforeToolExecution,
                    hook_outcome,
                    session,
                    runtime_state,
                ) {
                    let end_event = emitter.error(error.to_string()).clone();
                    let _ = ctx.event_tx.send(end_event.into_agent_event()).await;
                    return Err(error);
                }
            }
        }
    }

    // Hooks take an immutable Session and may inject context/control. Observe
    // its current scalar only after they allow dispatch; a cleared value must
    // not fall back to the earlier parallel-window projection.
    let output_cap = ctx
        .hook_session
        .as_deref()
        .map_or(ctx.output_cap, |session| {
            session
                .effective_token_budget()
                .map(|budget| budget.max_tool_output_tokens)
        });

    // THIS is the live server tool-dispatch path (engine runtime). Build via
    // `for_dispatch` so per-session flags stay in sync with the other loop
    // (bamboo-agent-core's `result_handler.rs`). The schema slice is the
    // per-round snapshot threaded in via `ctx.available_tool_schemas` (built
    // once in `execute_round_tool_calls`) instead of re-cloning every call.
    let tool_ctx = ToolExecutionContext::for_dispatch(
        ctx.session_id,
        ctx.root_session_id,
        &ctx.tool_call.id,
        ctx.event_tx,
        ctx.available_tool_schemas,
        ctx.session_flags,
        // Only let the Bash auto path promote to background when this loop can
        // actually suspend for and self-resume the shell — i.e. a
        // `bash_resume_hook` AND persistence are both wired (issue #84, phase
        // 2d). On hook-less paths (e.g. the schedule loop) this is false, so the
        // auto path stays synchronous and never orphans a promoted shell.
        bamboo_agent_core::tools::suspension_allowed()
            && ctx.config.bash_resume_hook.is_some()
            && ctx.config.persistence.is_some(),
        // Loop-facing background-Bash completion sink (issue #84 Phase 2b
        // follow-up). Threaded from the loop config so the Bash tool can push a
        // shell's result into this loop on completion. `None` on loops without
        // it wired, leaving the push inert (the poll backstop still runs).
        ctx.config
            .bash_completion_sink
            .as_ref()
            .filter(|_| bamboo_agent_core::tools::suspension_allowed()),
        // Reuse the args parsed above (for the `ToolStart` event) instead of
        // re-parsing the raw JSON string downstream in the executor (issue #106).
        // `args` came from `parse_tool_args_best_effort`, the same parser the
        // executor would call, so reuse is byte-for-byte equivalent.
        Some(&args),
    )
    .with_executing_supervisor(ctx.executing_supervisor);

    // Outcome-aware dispatch. Extract a NeedsHuman pending question (handled in
    // apply before the success path) and collapse the rest to a ToolResult so the
    // compressor / policy / transcript path is unchanged. Completed -> its result,
    // Running -> its synthetic ack, NeedsHuman -> its rich display result.
    // Dispatch through the exact identity already selected by the effective
    // callable-set resolver. Portable policies receive this identity; native
    // hooks, events, and permission handling above keep
    // the model's original call spelling, while the executor cannot re-resolve
    // that spelling to a different (possibly excluded) exact owner.
    let dispatch =
        ctx.tools
            .execute_exact_with_context_outcome(ctx.tool_call, execution_name, tool_ctx);
    let dispatch = bamboo_agent_core::tools::context::with_root_actor_tool_writer(
        ctx.config
            .persistence
            .as_ref()
            .and_then(|persistence| persistence.root_actor_writer()),
        dispatch,
    );
    let dispatch = bamboo_agent_core::tools::scope_tool_output_cap(
        ctx.session_id,
        &ctx.tool_call.id,
        output_cap,
        dispatch,
    );
    let observation = bamboo_infrastructure::telemetry::Observation::tool(
        execution_name,
        &ctx.tool_call.id,
        ctx.session_id,
        ctx.round_id,
    );
    let observed_dispatch = observation
        .scope(bamboo_tools::with_hook_permission_override(
            permission_override,
            &ctx.tool_call.id,
            dispatch,
        ))
        .await
        .map(ToolOutcome::enforce_suspension_restriction);
    use bamboo_infrastructure::telemetry::Outcome as TraceOutcome;
    let trace_outcome = match &observed_dispatch {
        Ok(ToolOutcome::Completed(result)) if !result.success => TraceOutcome::ToolError,
        Err(_) => TraceOutcome::ToolError,
        _ => TraceOutcome::Success,
    };
    observation.finish(trace_outcome);
    let (needs_human, mut result, post_tool_hook_eligible) = match observed_dispatch {
        Ok(ToolOutcome::Completed(result)) => (None, Ok(result), true),
        Ok(ToolOutcome::Running(handle)) => (None, Ok(handle.ack), false),
        Ok(ToolOutcome::NeedsHuman { question, result }) => (Some(question), Ok(result), false),
        Err(error) => (None, Err(error), true),
    };

    // Keep the auxiliary request inside the existing tool timeout/cancellation
    // scope, after successful permission/file checks and before terminal events.
    // Never spawn it into detached work or forward pixels to the main model.
    if let Some(target) = vision_target {
        if let Ok(tool_result) = result.as_mut() {
            if tool_result.success && !tool_result.images.is_empty() {
                if let Err(error) = crate::runtime::runner::image_fallback::describe_tool_images(
                    &target,
                    tool_result,
                )
                .await
                {
                    result = Err(bamboo_agent_core::ToolError::Execution(error.to_string()));
                }
            }
        }
    }

    let tool_duration = tool_timer.elapsed();

    // Emit lifecycle event based on result and push through AgentEvent channel
    let end_event = match &result {
        Ok(_) => emitter
            .finish(Some(format!("completed in {:?}", tool_duration)))
            .clone(),
        Err(err) => emitter.error(format!("{}", err)).clone(),
    };
    if let Err(e) = ctx.event_tx.send(end_event.into_agent_event()).await {
        tracing::warn!(
            "[{}] tool lifecycle end event send failed: {}",
            ctx.session_id,
            e
        );
    }

    tracing::trace!(
        "[{}][round:{}] ToolEmitter: call_id={}, tool={}, events={}",
        ctx.session_id,
        ctx.round,
        ctx.tool_call.id,
        tool_name,
        emitter.events().len()
    );

    Ok(ToolExecutionOutcome {
        output_cap: Some(output_cap),
        permission_replay_origin: ctx.executing_supervisor.map(|observation| {
            PermissionReplayOrigin::new(observation, ctx.session_id, ctx.tool_call, execution_name)
        }),
        result: result.map_err(|error| error.to_string()),
        needs_human,
        post_tool_hook_eligible,
        managed_running_violation: false,
        portable_tool: Some(PortableToolExecution {
            name: execution_name.to_owned(),
            input: args,
        }),
        tool_duration,
    })
}

/// Resolve `HookResult::Ask` without ever opening an unowned/manual approval.
/// External workers use their ambient parent proxy inline. Missing or failed
/// parent routes fail closed; this path never reuses the interactive
/// clarification/approval flow.
async fn hook_ask_outcome(
    tool_call: &ToolCall,
    execution_name: &str,
    config: &AgentLoopConfig,
    session: &Session,
    runtime_state: &AgentRuntimeState,
    args: &serde_json::Value,
) -> Option<ToolExecutionOutcome> {
    if !bamboo_agent_core::tools::suspension_allowed() {
        return Some(ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Err("managed loop cannot wait for hook approval; finish the loop before requesting interactive work".into()),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: false, managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        });
    }
    let tool_name = tool_call.function.name.trim().to_string();
    let browser_execution = execution_name.trim().eq_ignore_ascii_case("browser");
    let focused_browser_input =
        bamboo_tools::permission::is_focused_browser_input(execution_name, args);
    let native_browser_select =
        bamboo_tools::permission::is_native_browser_select(execution_name, args);
    let browser_eval = execution_name.trim().eq_ignore_ascii_case("browser_eval");
    let private_browser_file_input =
        bamboo_tools::permission::is_private_browser_file_input(execution_name, args);
    let private_browser_download = browser_execution
        && args
            .get("action")
            .and_then(serde_json::Value::as_str)
            .is_some_and(|action| action.eq_ignore_ascii_case("download"));
    let private_browser_approval = focused_browser_input
        || native_browser_select
        || browser_eval
        || private_browser_file_input
        || private_browser_download;
    let private_check_error = if browser_eval {
        "Browser page script permission check failed"
    } else if private_browser_download {
        "Browser download permission check failed"
    } else if private_browser_file_input {
        "Browser file input permission check failed"
    } else if native_browser_select {
        "Browser selection permission check failed"
    } else if focused_browser_input {
        "Focused browser input permission check failed"
    } else {
        "Browser permission check failed"
    };
    let permission_context = match bamboo_tools::permission::check_permissions(execution_name, args)
    {
        Ok(contexts) => contexts.and_then(|contexts| contexts.into_iter().next()),
        Err(_) if browser_execution || private_browser_approval => {
            return Some(ToolExecutionOutcome {
                output_cap: None,
                permission_replay_origin: None,
                result: Err(private_check_error.to_string()),
                needs_human: None,
                portable_tool: None,
                post_tool_hook_eligible: false,
                managed_running_violation: false,
                tool_duration: std::time::Duration::ZERO,
            });
        }
        Err(_) => None,
    };
    if private_browser_approval && permission_context.is_none() {
        return Some(ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Err(private_check_error.to_string()),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: false,
            managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        });
    }
    // Read-only browser actions can legitimately have no permission context.
    // A hook Ask for those actions still reaches the parent, but arbitrary
    // extra fields must never become its fallback approval resource.
    let browser_without_context = browser_execution && permission_context.is_none();
    let (permission_type, resource, operation_summary, risk_level) =
        if let Some(permission) = permission_context {
            let risk_level = permission.risk_level();
            (
                permission.permission_type,
                permission.resource,
                permission.operation_description,
                risk_level,
            )
        } else {
            let permission_type = bamboo_tools::permission::PermissionType::ExecuteCommand;
            (
                permission_type,
                if browser_without_context {
                    "[redacted]".to_string()
                } else {
                    args.to_string()
                },
                format!("Hook-requested review for {tool_name}"),
                permission_type.risk_level(),
            )
        };

    let requested_mode = runtime_state.effective_permission_mode();
    let resolution = bamboo_domain::resolve_permission_mode(
        requested_mode,
        config.permission_mode.unwrap_or_default(),
    );
    let approval_resource = if private_browser_approval || browser_without_context {
        "[redacted]".to_string()
    } else {
        resource.clone()
    };
    // A namespace is model-supplied text. Keep the private download's outward
    // tool identity fixed as well as its resource and matcher.
    let approval_tool_name = if private_browser_download {
        "browser".to_string()
    } else {
        tool_name.clone()
    };
    let request = bamboo_tools::permission::PermissionRequest {
        request_id: tool_call.id.clone(),
        request_generation: bamboo_tools::permission::PermissionRequest::fresh_generation(),
        session_id: session.id.clone(),
        workspace_path: session.workspace_path_meta(),
        tool_name: approval_tool_name.clone(),
        permission_type,
        resource: approval_resource.clone(),
        operation_summary,
        risk_level,
        reason_code: bamboo_tools::permission::PermissionReasonCode::ConfiguredAlwaysAsk,
        effective_mode: resolution.effective,
        bypass_requested: resolution.bypass_permissions(),
        auto_approve_requested: requested_mode == bamboo_domain::SessionPermissionMode::Auto,
        policy_revision: 0,
        matched_rule: None,
        allowed_decisions: bamboo_tools::permission::PermissionRequest::forced_decisions(),
        suggested_matchers: if private_browser_approval || browser_without_context {
            Vec::new()
        } else {
            bamboo_tools::permission::conservative_matchers(permission_type, &resource)
        },
    };

    if let Some(proxy) = bamboo_tools::current_approval_proxy() {
        let approved = proxy
            .request_approval(bamboo_tools::ApprovalAsk {
                tool_name: approval_tool_name,
                permission: permission_type.description().to_string(),
                resource: approval_resource,
                permission_request: Some(request),
            })
            .await;
        return (!approved).then(|| ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Err("Tool execution denied by parent agent review".to_string()),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: false,
            managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        });
    }

    Some(ToolExecutionOutcome {
        output_cap: None,
        permission_replay_origin: None,
        result: Err(
            "Hook requested approval, but no parent-agent reviewer is available; denied"
                .to_string(),
        ),
        needs_human: None,
        portable_tool: None,
        post_tool_hook_eligible: false,
        managed_running_violation: false,
        tool_duration: std::time::Duration::ZERO,
    })
}

fn append_post_tool_feedback(
    result: &mut Result<ToolResult, String>,
    feedback: Vec<String>,
    execution_name: Option<&str>,
    max_tool_output_tokens: u32,
) {
    let feedback = feedback
        .into_iter()
        .filter_map(|text| {
            let text = text.trim();
            (!text.is_empty()).then(|| text.to_string())
        })
        .collect::<Vec<_>>();
    if feedback.is_empty() {
        return;
    }

    if matches!(execution_name, Some("exec_command" | "write_stdin")) {
        if let Ok(result) = result {
            if let Ok(mut envelope) = serde_json::from_str::<serde_json::Value>(&result.result) {
                if let Some(object) = envelope.as_object_mut() {
                    // Native hooks have no aggregate context cap. Bound only
                    // this optional shell-result metadata before preserving it.
                    let mut remaining = bamboo_hooks::portable::PORTABLE_CONTEXT_BYTES;
                    let total = feedback.iter().map(String::len).sum::<usize>();
                    let mut bounded = Vec::new();
                    for mut text in feedback {
                        if remaining == 0 {
                            break;
                        }
                        let mut end = text.len().min(remaining);
                        while !text.is_char_boundary(end) {
                            end -= 1;
                        }
                        text.truncate(end);
                        remaining -= end;
                        if !text.is_empty() {
                            bounded.push(text);
                        }
                    }
                    let kept = bounded.iter().map(String::len).sum::<usize>();
                    object.insert("hook_feedback".into(), serde_json::json!(bounded));
                    if total > kept {
                        object.insert(
                            "hook_feedback_omitted_bytes".into(),
                            serde_json::json!(total - kept),
                        );
                    }
                    result.result = serde_json::to_string(&envelope)
                        .expect("shell feedback envelope is serializable");
                    if max_tool_output_tokens > 0 {
                        use bamboo_compression::TokenCounter;
                        let counter = bamboo_compression::TiktokenTokenCounter::default();
                        if counter.count_text(&result.result) > max_tool_output_tokens {
                            if let Some(truncated) =
                                super::output_compressor::truncate_exec_session_output(
                                    &result.result,
                                    max_tool_output_tokens,
                                    &counter,
                                )
                            {
                                result.result = truncated;
                            }
                        }
                    }
                    return;
                }
            }
        }
    }

    let block = format!(
        "\n\n<post_tool_use_feedback>\n{}\n</post_tool_use_feedback>",
        feedback.join("\n")
    );
    match result {
        Ok(result) => result.result.push_str(&block),
        Err(error) => error.push_str(&block),
    }
}

async fn apply_without_suspension<F>(apply: F) -> Result<bool, AgentError>
where
    F: std::future::Future<Output = Result<bool, AgentError>>,
{
    let (result, observation) =
        bamboo_agent_core::tools::observe_tool_suspension(true, apply).await;
    if observation.forbidden_running_seen {
        if let Some(resources) = bamboo_tools::LocalTaskResources::current() {
            resources.record_unconfirmed(crate::runtime::loop_control::suspension::RUNNING_REFUSAL);
        }
        result?;
        return Err(AgentError::Tool(
            crate::runtime::loop_control::suspension::RUNNING_REFUSAL.into(),
        ));
    }
    result
}

pub(super) async fn apply_tool_execution_outcome(
    ctx: ToolExecutionApplyContext<'_>,
    outcome: ToolExecutionOutcome,
) -> Result<bool, AgentError> {
    let noninteractive = crate::runtime::loop_control::suspension::active(ctx.config);
    let control = ctx.config.loop_control.as_ref();
    let apply = apply_tool_execution_outcome_inner(ctx, outcome);
    if let Some(control) = control {
        let (result, observation) =
            bamboo_agent_core::tools::observe_tool_suspension(noninteractive, apply).await;
        if observation.running_seen {
            control.record_running_observed();
        }
        if observation.forbidden_running_seen {
            if let Some(resources) = bamboo_tools::LocalTaskResources::current() {
                resources
                    .record_unconfirmed(crate::runtime::loop_control::suspension::RUNNING_REFUSAL);
            }
            result?;
            return Err(AgentError::Tool(
                crate::runtime::loop_control::suspension::RUNNING_REFUSAL.into(),
            ));
        }
        result
    } else {
        apply.await
    }
}

async fn apply_tool_execution_outcome_inner(
    ctx: ToolExecutionApplyContext<'_>,
    mut outcome: ToolExecutionOutcome,
) -> Result<bool, AgentError> {
    // Normalize before post hooks, policy accounting or any question/wait write.
    // An already checkpointed loop receipt never has a waiting result shape.
    if !bamboo_agent_core::tools::suspension_allowed()
        && (outcome.needs_human.is_some()
            || outcome.result.as_ref().is_ok_and(|result| {
                bamboo_agent_core::tools::tool_result_requires_suspension(result)
                    || super::clarification::requires_suspension(ctx.tool_call, result)
            }))
    {
        outcome.needs_human = None;
        outcome.result = Err("managed loop cannot wait for a question, approval or child; finish or stop the loop before interactive work".into());
        outcome.post_tool_hook_eligible = false;
    }
    // Capture the exact dispatch budget once, before owner projection or hooks.
    let feedback_cap = outcome
        .output_cap
        .unwrap_or_else(|| {
            ctx.session
                .effective_token_budget()
                .map(|budget| budget.max_tool_output_tokens)
        })
        .unwrap_or(0);
    let mut loop_result_checkpointed = false;
    if outcome.portable_tool.as_ref().is_some_and(|tool| {
        tool.execution_name() == bamboo_tools::tools::loop_control::LOOP_CONTROL_TOOL_NAME
    }) && outcome.result.as_ref().is_ok_and(|result| result.success)
        && outcome.needs_human.is_none()
    {
        let command = bamboo_tools::tools::loop_control::parse_loop_control_request(
            &ctx.tool_call.function.arguments,
        )
        .map_err(AgentError::Tool)?;
        crate::runtime::runner::state_bridge::write_runtime_state(ctx.session, ctx.runtime_state);
        let read_only = ctx.runtime_state.plan_mode.is_some()
            || ctx.config.permission_mode == Some(bamboo_config::PermissionMode::Plan);
        outcome.result = Ok(crate::runtime::loop_control::apply_current(
            ctx.session,
            ctx.config,
            &command,
            &ctx.tool_call.id,
            ctx.round,
            outcome.permission_replay_origin.is_some(),
            read_only,
            feedback_cap,
        )
        .await?);
        loop_result_checkpointed = true;
    }
    // Start can install its generation during owner apply above. Re-enter
    // the restriction now, before even its own native AfterTool hook runs.
    let noninteractive = crate::runtime::loop_control::suspension::active(ctx.config);
    let apply = apply_completed_tool_execution_outcome(
        ctx,
        outcome,
        feedback_cap,
        loop_result_checkpointed,
    );
    if noninteractive {
        apply_without_suspension(apply).await
    } else {
        apply.await
    }
}

async fn apply_completed_tool_execution_outcome(
    ctx: ToolExecutionApplyContext<'_>,
    mut outcome: ToolExecutionOutcome,
    feedback_cap: u32,
    loop_result_checkpointed: bool,
) -> Result<bool, AgentError> {
    let mut post_tool_feedback = Vec::new();
    let mut deferred_hook_control = None;
    if outcome.post_tool_hook_eligible
        && ctx
            .config
            .hook_runner
            .has_hooks_for(AgentHookPoint::AfterToolExecution)
    {
        let hook_payload = HookPayload::ToolResult {
            tool_name: ctx.tool_call.function.name.clone(),
            tool_call_id: ctx.tool_call.id.clone(),
            outcome: match &outcome.result {
                Ok(result) => HookToolOutcome {
                    success: result.success,
                    result: Some(result.result.clone()),
                    error: None,
                    needs_human: outcome.needs_human.is_some(),
                    duration_ms: outcome.tool_duration.as_millis() as u64,
                },
                Err(error) => HookToolOutcome {
                    success: false,
                    result: None,
                    error: Some(error.clone()),
                    needs_human: false,
                    duration_ms: outcome.tool_duration.as_millis() as u64,
                },
            },
        };
        let original_tool_input = serde_json::from_str(&ctx.tool_call.function.arguments).ok();
        let mut hook_outcome = ctx
            .config
            .hook_runner
            .run_hooks_with_inputs(
                AgentHookPoint::AfterToolExecution,
                &hook_payload,
                ctx.session,
                ctx.runtime_state,
                Some(ctx.event_tx),
                bamboo_hooks::portable::PortableInputs {
                    resolved_tool_name: outcome
                        .portable_tool
                        .as_ref()
                        .map(|tool| tool.name.as_str()),
                    original_tool_input: outcome
                        .portable_tool
                        .as_ref()
                        .map(|tool| &tool.input)
                        .or(original_tool_input.as_ref()),
                    ..Default::default()
                },
            )
            .await;
        crate::runtime::hooks::inject_plugin_contexts(
            ctx.session,
            std::mem::take(&mut hook_outcome.plugin_contexts),
        );
        post_tool_feedback = std::mem::take(&mut hook_outcome.injected_contexts);
        if let HookResult::Deny { reason } = hook_outcome.decision.clone() {
            post_tool_feedback.push(format!("Blocked by PostToolUse hook: {reason}"));
            hook_outcome.decision = HookResult::Continue;
        }
        if matches!(
            hook_outcome.decision,
            HookResult::Suspend { .. } | HookResult::Abort { .. } | HookResult::Ask
        ) {
            deferred_hook_control = Some(hook_outcome);
        } else {
            crate::runtime::hooks::apply_hook_outcome(
                AgentHookPoint::AfterToolExecution,
                hook_outcome,
                ctx.session,
                ctx.runtime_state,
            )?;
        }
    }
    // Read the shell envelope before post-hook feedback appends prose. Only
    // the admitted exact identity selects command-specific task accounting.
    let task_progress_result = task_progress_result_for_outcome(&outcome);
    if loop_result_checkpointed {
        let result = outcome.result.as_ref().expect("checkpointed owner result");
        let feedback = crate::runtime::loop_control::output_limits::feedback_context(
            result,
            &ctx.tool_call.id,
            post_tool_feedback,
            feedback_cap,
        );
        crate::runtime::loop_control::finish_checkpointed_result(
            ctx.session,
            ctx.config,
            &ctx.tool_call.id,
            result,
            ctx.runtime_state,
            feedback,
        )
        .await?;
    } else {
        append_post_tool_feedback(
            &mut outcome.result,
            post_tool_feedback,
            outcome
                .portable_tool
                .as_ref()
                .map(|tool| tool.execution_name()),
            feedback_cap,
        );
    }
    // Exactly one common observation sees the final owner/compression result.
    // Raw observation remains at dispatch, before compression and owner apply.
    ctx.policy_guard.observe_execution_outcome(
        ctx.tool_call,
        &outcome,
        ctx.admitted_execution_name,
    );

    let running_violation = outcome.managed_running_violation;
    // Capture tool lifecycle metadata before the borrow-splitting match.
    let tool_name_for_meta = ctx.tool_call.function.name.clone();
    let tool_call_id_for_meta = ctx.tool_call.id.clone();
    let tool_duration_ms = outcome.tool_duration.as_millis() as u64;
    let is_success = outcome.result.as_ref().is_ok_and(|result| result.success);

    let is_mutating = bamboo_tools::orchestrator::classify_tool(&tool_name_for_meta)
        == bamboo_tools::orchestrator::ToolMutability::Mutating;

    // The tool asked for a human decision (Phase B): suspend directly on the
    // returned PendingQuestion — no marker sniff. Its rich display result is the
    // `Ok` value in `outcome.result`.
    let result = if let Some(pending_question) = outcome.needs_human {
        let display_result = outcome.result.unwrap_or_else(|_| ToolResult {
            success: true,
            result: String::new(),
            display_preference: None,
            images: Vec::new(),
        });
        // Preserve the per-tool task-progress accounting that the success path
        // runs for every tool. An interactive tool that suspends (e.g.
        // conclusion_with_options) must still record its call against the active
        // task item — parity with the pre-Phase-B Completed+sniff path, which ran
        // handle_successful_tool_result (→ track_task_progress) before the sniff
        // suspended. The other success-path steps (taskwrite/workspace/goal/
        // agentic) are tool-specific no-ops here, and suspend_for_pending_question
        // already emits the ToolComplete event.
        if let Some(progress_result) = task_progress_result.result(&display_result) {
            super::task::track_task_progress(
                ctx.task_context,
                ctx.event_tx,
                ctx.session_id,
                ctx.tool_call,
                progress_result,
                ctx.round,
            )
            .await;
        }
        super::clarification::suspend_for_pending_question(
            ctx.tool_call,
            outcome.permission_replay_origin.as_ref(),
            pending_question,
            display_result,
            ctx.session,
            ctx.event_tx,
            ctx.metrics_collector,
            ctx.session_id,
            ctx.round_id,
            ctx.config,
        )
        .await;
        ctx.state.mark_awaiting_clarification();
        true
    } else {
        match outcome.result {
            Ok(result) => {
                let loop_cancel = if loop_result_checkpointed {
                    Some(
                        ctx.config
                            .loop_control
                            .as_ref()
                            .expect("checkpointed owner capability")
                            .execution_cancel()?
                            .clone(),
                    )
                } else {
                    None
                };
                let apply_success = execution_paths::handle_successful_tool_result(
                    execution_paths::SuccessPathContext {
                        tool_call: ctx.tool_call,
                        permission_replay_origin: outcome.permission_replay_origin.as_ref(),
                        result: &result,
                        task_progress_result,
                        loop_result_checkpointed,
                        event_tx: ctx.event_tx,
                        metrics_collector: ctx.metrics_collector,
                        session_id: ctx.session_id,
                        round_id: ctx.round_id,
                        round: ctx.round,
                        session: ctx.session,
                        tools: ctx.tools,
                        session_flags: ctx.session_flags,
                        config: ctx.config,
                        task_context: ctx.task_context,
                        state: ctx.state,
                        tool_duration: outcome.tool_duration,
                    },
                );
                if let Some(cancel) = loop_cancel {
                    // A blocked ToolComplete publisher must not outlive this
                    // execution's cancellation. Ordinary tools keep their path.
                    tokio::select! {
                        biased;
                        _ = cancel.cancelled() => return Err(AgentError::Cancelled),
                        result = apply_success => result,
                    }
                } else {
                    apply_success.await
                }
            }
            Err(error_message) => {
                execution_paths::handle_tool_execution_error(
                    ctx.tool_call,
                    &error_message,
                    ctx.event_tx,
                    ctx.metrics_collector,
                    ctx.session_id,
                    ctx.round_id,
                    ctx.round,
                    ctx.session,
                    ctx.state,
                )
                .await;
                false
            }
        }
    };

    // ── Persist lifecycle metadata on the tool result message ──────────
    // Find the last tool-result message matching this tool_call_id and
    // attach execution metadata so it is persisted in session.json and
    // available when the frontend reloads the session later.
    let metadata_value = serde_json::json!({
        "elapsed_ms": tool_duration_ms,
        "is_mutating": is_mutating,
        "auto_approved": !is_mutating,
        "tool_name": tool_name_for_meta,
        "success": is_success,
    });
    if let Some(msg) = ctx
        .session
        .messages
        .iter_mut()
        .rev()
        .find(|m| m.tool_call_id.as_deref() == Some(&tool_call_id_for_meta))
    {
        let metadata = msg.metadata.get_or_insert_with(|| serde_json::json!({}));
        if let Some(object) = metadata.as_object_mut() {
            object.extend(
                metadata_value
                    .as_object()
                    .expect("lifecycle metadata object")
                    .clone(),
            );
        }
    }

    if let Some(hook_outcome) = deferred_hook_control {
        crate::runtime::hooks::apply_hook_outcome(
            AgentHookPoint::AfterToolExecution,
            hook_outcome,
            ctx.session,
            ctx.runtime_state,
        )?;
    }

    if running_violation {
        return Err(AgentError::Tool(
            crate::runtime::loop_control::suspension::RUNNING_REFUSAL.into(),
        ));
    }
    Ok(result)
}

#[cfg(test)]
mod task_progress_tests {
    use super::*;
    use crate::runtime::task_context::{TaskLoopItem, ToolCallRecord};
    use bamboo_agent_core::tools::FunctionCall;
    use bamboo_domain::TaskItemStatus;
    use chrono::Utc;

    fn active_task(history: &[bool]) -> TaskLoopContext {
        let now = Utc::now();
        TaskLoopContext {
            session_id: "shell-progress".into(),
            items: vec![TaskLoopItem {
                id: "verify".into(),
                description: "Run verification".into(),
                status: TaskItemStatus::InProgress,
                tool_calls: history
                    .iter()
                    .map(|success| ToolCallRecord {
                        round: 0,
                        tool_name: "prior".into(),
                        success: *success,
                        timestamp: now,
                    })
                    .collect(),
                ..Default::default()
            }],
            active_item_id: Some("verify".into()),
            current_round: 0,
            max_rounds: None,
            created_at: now,
            updated_at: now,
            version: 0,
            task_list_dirty: false,
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn apply_result(
        task: TaskLoopContext,
        requested_name: &str,
        execution_name: &str,
        status: &str,
        exit_code: Option<i32>,
        needs_human: bool,
        round: usize,
    ) -> TaskLoopContext {
        let call = ToolCall {
            id: format!("shell-progress-{round}"),
            tool_type: "function".into(),
            function: FunctionCall {
                name: requested_name.into(),
                arguments: "{}".into(),
            },
        };
        let result = ToolResult::text(
            true,
            serde_json::json!({"status":status,"output":"","exit_code":exit_code}).to_string(),
        );
        let expected_result = result.result.clone();
        let outcome = ToolExecutionOutcome {
            output_cap: None,
            portable_tool: Some(PortableToolExecution {
                name: execution_name.into(),
                input: serde_json::json!({}),
            }),
            permission_replay_origin: None,
            result: Ok(result),
            needs_human: needs_human.then(|| bamboo_agent_core::PendingQuestion {
                tool_call_id: call.id.clone(),
                tool_name: requested_name.into(),
                question: "Approve command?".into(),
                options: vec!["yes".into(), "no".into()],
                allow_custom: false,
                source: bamboo_agent_core::PendingQuestionSource::PauseTool,
            }),
            post_tool_hook_eligible: true,
            managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        };
        let mut session = Session::new("shell-progress", "model");
        let flags = ToolExecutionSessionFlags::from_session(&session);
        let tools: Arc<dyn ToolExecutor> = Arc::new(
            bamboo_tools::BuiltinToolExecutor::with_registry(bamboo_tools::ToolRegistry::new()),
        );
        let (event_tx, mut event_rx) = mpsc::channel(64);
        let mut context = Some(task);
        apply_tool_execution_outcome(
            ToolExecutionApplyContext {
                policy_guard: &mut policy::ToolPolicyGuard::default(),
                admitted_execution_name: Some(execution_name),
                tool_call: &call,
                event_tx: &event_tx,
                metrics_collector: None,
                session_id: "shell-progress",
                round_id: "round",
                round,
                session: &mut session,
                tools: &tools,
                session_flags: flags,
                config: &AgentLoopConfig::default(),
                runtime_state: &mut AgentRuntimeState::new("shell-progress"),
                task_context: &mut context,
                state: &mut RoundExecutionState::default(),
            },
            outcome,
        )
        .await
        .unwrap();
        let completed = std::iter::from_fn(|| event_rx.try_recv().ok())
            .find_map(|event| match event {
                AgentEvent::ToolComplete { result, .. } => Some(result),
                _ => None,
            })
            .expect("tool completion remains visible");
        assert!(
            completed.success,
            "public transport success must be unchanged"
        );
        assert_eq!(completed.result, expected_result);
        context.unwrap()
    }

    #[tokio::test]
    async fn running_shell_polls_neither_complete_nor_block_active_tasks() {
        for execution_name in ["exec_command", "write_stdin"] {
            for history in [&[][..], &[true, true, true][..], &[false, false][..]] {
                let mut task = active_task(history);
                for round in 0..4 {
                    task = apply_result(
                        task,
                        &format!("default::{execution_name}"),
                        execution_name,
                        "running",
                        None,
                        false,
                        round,
                    )
                    .await;
                }
                assert_eq!(task.items[0].status, TaskItemStatus::InProgress);
                assert_eq!(task.items[0].tool_calls.len(), history.len());
                assert!(task.items[0].evidence.is_empty());
                assert_eq!(task.version, 0);
            }
        }
    }

    #[tokio::test]
    async fn terminal_shell_results_follow_existing_task_success_and_failure_rules() {
        for execution_name in ["exec_command", "write_stdin"] {
            for (status, exit_code, expected, successful) in [
                ("completed", Some(0), TaskItemStatus::Completed, true),
                ("completed", Some(7), TaskItemStatus::Blocked, false),
                ("error", None, TaskItemStatus::Blocked, false),
                ("killed", None, TaskItemStatus::Blocked, false),
            ] {
                let mut task = active_task(&[]);
                for round in 0..4 {
                    task = apply_result(
                        task,
                        execution_name,
                        execution_name,
                        status,
                        exit_code,
                        false,
                        round,
                    )
                    .await;
                }
                assert_eq!(task.items[0].status, expected, "{execution_name}:{status}");
                assert!(task.items[0]
                    .tool_calls
                    .iter()
                    .all(|record| record.success == successful));
                assert!(task.items[0]
                    .evidence
                    .iter()
                    .all(|evidence| evidence.success == Some(successful)));
            }
        }
    }

    async fn real_shell_permission_ack_is_neutral(cap: u32) {
        for (requested, execution_name) in [
            ("exec_command", "exec_command"),
            ("default::exec_command", "exec_command"),
            ("write_stdin", "write_stdin"),
            ("default::write_stdin", "write_stdin"),
        ] {
            let home = tempfile::tempdir().unwrap();
            let sentinel = home.path().join("must-not-execute");
            let permission = Arc::new(bamboo_tools::permission::PermissionConfig::new());
            permission.set_ask_rules(["exec_command".into(), "write_stdin".into()]);
            let checker = Arc::new(bamboo_tools::permission::ConfigPermissionChecker::new(
                permission,
            ));
            let tools: Arc<dyn ToolExecutor> = Arc::new(
                bamboo_tools::BuiltinToolExecutor::new_with_permissions(checker),
            );
            let schemas = tools.list_tools();
            let args = if execution_name == "exec_command" {
                serde_json::json!({"cmd":format!("printf forbidden > '{}'", sentinel.display())})
            } else {
                // The gate must pause before the actual tool rejects this unknown handle.
                serde_json::json!({"session_id":"00000000-0000-0000-0000-000000000000", "chars":""})
            };
            let call = ToolCall {
                id: format!("real-pending-{cap}-{requested}"),
                tool_type: "function".into(),
                function: FunctionCall {
                    name: requested.into(),
                    arguments: args.to_string(),
                },
            };
            let mut session = Session::new("shell-progress", "model");
            session.token_budget = Some(bamboo_domain::TokenBudget {
                max_tool_output_tokens: cap,
                ..Default::default()
            });
            let flags = ToolExecutionSessionFlags::from_session(&session);
            assert!(!flags.bypass_permissions && !flags.auto_approve_permissions);
            let config = AgentLoopConfig::default();
            let mut runtime = AgentRuntimeState::new("shell-progress");
            let (event_tx, mut event_rx) = mpsc::channel(64);
            let outcome = bamboo_tools::with_approval_proxy(
                None,
                // Exercise the real gate for an explicitly selected executor;
                // model admission is covered by the strict-argument test.
                execute_tool_call_only_with_execution_name(
                    execution_name,
                    ToolExecutionOnlyContext {
                        vision_support: true,
                        output_cap: None,
                        executing_supervisor: None,
                        tool_call: &call,
                        event_tx: &event_tx,
                        metrics_collector: None,
                        session_id: "shell-progress",
                        root_orchestration_only: false,
                        root_session_id: "shell-progress",
                        round_id: "round",
                        round: 0,
                        tools: &tools,
                        config: &config,
                        hook_session: Some(&mut session),
                        hook_runtime_state: Some(&mut runtime),
                        session_flags: flags,
                        available_tool_schemas: &schemas,
                    },
                ),
            )
            .await
            .unwrap();
            assert!(
                outcome.needs_human.is_none(),
                "real gate uses the legacy Completed adapter"
            );
            let result = outcome.result.as_ref().unwrap();
            assert!(result.success);
            assert_eq!(
                result.display_preference.as_deref(),
                Some("request_permissions")
            );
            assert_eq!(
                serde_json::from_str::<serde_json::Value>(&result.result).unwrap()["status"],
                "awaiting_permission_approval"
            );
            assert!(!sentinel.exists());
            assert!(std::iter::from_fn(|| event_rx.try_recv().ok())
                .any(|event| matches!(event, AgentEvent::ToolApprovalRequested { .. })));
            let outcome = super::super::output_compressor::maybe_compress(
                requested,
                &call.function.arguments,
                "shell-progress",
                outcome,
                cap,
                None,
                None,
            )
            .await;
            assert!(outcome.needs_human.is_none());
            assert_eq!(
                outcome.portable_tool.as_ref().unwrap().execution_name(),
                execution_name
            );
            assert_eq!(
                outcome
                    .result
                    .as_ref()
                    .unwrap()
                    .display_preference
                    .as_deref(),
                Some("request_permissions")
            );
            if cap == 1 {
                assert!(outcome
                    .result
                    .as_ref()
                    .unwrap()
                    .result
                    .contains("tool output truncated"));
            }
            assert!(matches!(shell_accounting_outcome(&outcome, Some(execution_name)), ShellAccountingOutcome::Pending),
                "{requested}, cap={cap}: an unexecuted permission acknowledgment is not command failure");

            let mut canonical_call = call.clone();
            canonical_call.function.name = execution_name.into();
            let prior_error = Err("prior command failure".into());
            let mut guard = policy::ToolPolicyGuard::new(80, 3);
            for _ in 0..2 {
                guard.observe_outcome(&canonical_call, &prior_error);
            }
            guard.observe_execution_outcome(&call, &outcome, Some(execution_name));
            assert!(
                guard
                    .check_before_execution_for_name(&call, 0, Some(execution_name))
                    .is_ok(),
                "approval must not add a third failure"
            );
            guard.observe_outcome(&canonical_call, &prior_error);
            assert!(
                matches!(
                    guard.check_before_execution_for_name(&call, 0, Some(execution_name)),
                    Err(policy::ToolPolicyPrecheckViolation::ToolCircuitOpen {
                        consecutive_failures: 3,
                        ..
                    })
                ),
                "approval must not reset the existing two failures"
            );

            let mut task = Some(active_task(&[false, false]));
            apply_tool_execution_outcome(
                ToolExecutionApplyContext {
                    policy_guard: &mut policy::ToolPolicyGuard::default(),
                    admitted_execution_name: Some(execution_name),
                    tool_call: &call,
                    event_tx: &event_tx,
                    metrics_collector: None,
                    session_id: "shell-progress",
                    round_id: "round",
                    round: 0,
                    session: &mut session,
                    tools: &tools,
                    session_flags: flags,
                    config: &config,
                    runtime_state: &mut runtime,
                    task_context: &mut task,
                    state: &mut RoundExecutionState::default(),
                },
                outcome,
            )
            .await
            .unwrap();
            if cap == 0 {
                let question = session
                    .pending_question
                    .as_ref()
                    .expect("real gate must pause for approval");
                assert_eq!(question.tool_call_id, call.id);
                assert_eq!(question.tool_name, requested);
            }
            let task = task.unwrap();
            assert_eq!(task.items[0].status, TaskItemStatus::InProgress);
            assert_eq!(task.items[0].tool_calls.len(), 2);
            assert!(task.items[0]
                .tool_calls
                .iter()
                .all(|record| !record.success));
            assert!(task.items[0].evidence.is_empty());
            assert_eq!(task.version, 0);
            assert!(!sentinel.exists());
        }
    }

    #[tokio::test]
    async fn real_shell_permission_gate_completed_ack_does_not_record_command_outcome() {
        real_shell_permission_ack_is_neutral(0).await;
    }

    #[tokio::test]
    async fn compressed_real_shell_permission_ack_remains_neutral_without_json() {
        real_shell_permission_ack_is_neutral(1).await;
    }

    #[tokio::test]
    async fn pending_shell_approval_and_exact_foreign_tools_keep_their_own_semantics() {
        let task = apply_result(
            active_task(&[true, true, true]),
            "default::exec_command",
            "exec_command",
            "completed",
            Some(0),
            true,
            0,
        )
        .await;
        assert_eq!(task.items[0].status, TaskItemStatus::InProgress);
        assert_eq!(task.items[0].tool_calls.len(), 3);
        for name in ["vendor::exec_command", "vendor::write_stdin"] {
            let mut task = active_task(&[]);
            for round in 0..4 {
                task = apply_result(task, name, name, "completed", Some(7), false, round).await;
            }
            assert_eq!(task.items[0].status, TaskItemStatus::Completed);
            assert!(task.items[0].tool_calls.iter().all(|record| record.success));
        }
    }
}

#[cfg(test)]
mod hook_tests {
    use super::*;
    use async_trait::async_trait;
    use bamboo_agent_core::tools::{
        AsyncWaitKind, FunctionCall, FunctionSchema, RunningCompletion, RunningHandle, ToolError,
    };
    use bamboo_agent_core::AgentHook;
    use bamboo_config::{LifecycleHookGroup, LifecycleHookHandler, LifecycleHooksConfig};
    use bamboo_domain::{CapabilityLoadingMode, ClassifiedToolSchema};
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::Mutex;

    #[derive(Default)]
    struct BlockingPendingPersistence {
        saved: std::sync::Mutex<Vec<Session>>,
        entered: tokio::sync::Notify,
        release: tokio::sync::Notify,
    }

    #[async_trait]
    impl bamboo_domain::RuntimeSessionPersistence for BlockingPendingPersistence {
        async fn save_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
            self.saved
                .lock()
                .expect("pending persistence lock")
                .push(session.clone());
            self.entered.notify_one();
            self.release.notified().await;
            Ok(())
        }
    }

    struct DenyToolHook;

    #[async_trait]
    impl AgentHook for DenyToolHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::BeforeToolExecution
        }

        async fn run(
            &self,
            _point: AgentHookPoint,
            payload: &HookPayload,
            _session: &Session,
        ) -> HookResult {
            assert!(matches!(
                payload,
                HookPayload::ToolExecution {
                    tool_name,
                    parsed_args,
                    ..
                } if tool_name == "probe" && parsed_args["value"] == 7
            ));
            HookResult::Deny {
                reason: "policy hook blocked probe".to_string(),
            }
        }

        fn name(&self) -> &str {
            "deny_probe"
        }
    }

    struct AskToolHook;

    #[async_trait]
    impl AgentHook for AskToolHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::BeforeToolExecution
        }

        async fn run(
            &self,
            _point: AgentHookPoint,
            _payload: &HookPayload,
            _session: &Session,
        ) -> HookResult {
            HookResult::Ask
        }
    }

    struct AllowToolHook;

    #[async_trait]
    impl AgentHook for AllowToolHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::BeforeToolExecution
        }

        async fn run(
            &self,
            _point: AgentHookPoint,
            _payload: &HookPayload,
            _session: &Session,
        ) -> HookResult {
            HookResult::Allow
        }
    }

    struct PostFeedbackHook;

    #[async_trait]
    impl AgentHook for PostFeedbackHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterToolExecution
        }

        async fn run(
            &self,
            _point: AgentHookPoint,
            payload: &HookPayload,
            _session: &Session,
        ) -> HookResult {
            assert!(matches!(
                payload,
                HookPayload::ToolResult {
                    tool_name,
                    outcome: HookToolOutcome { success: true, .. },
                    ..
                } if tool_name == "probe"
            ));
            HookResult::WithContext {
                result: Box::new(HookResult::Deny {
                    reason: "generated output violates policy".to_string(),
                }),
                text: "lint: replace the generated token".to_string(),
            }
        }
    }

    struct ErrorPostFeedbackHook;

    #[async_trait]
    impl AgentHook for ErrorPostFeedbackHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterToolExecution
        }

        async fn run(
            &self,
            _point: AgentHookPoint,
            payload: &HookPayload,
            _session: &Session,
        ) -> HookResult {
            assert!(matches!(
                payload,
                HookPayload::ToolResult {
                    outcome: HookToolOutcome {
                        success: false,
                        error: Some(error),
                        ..
                    },
                    ..
                } if error == "executor exploded"
            ));
            HookResult::InjectContext {
                text: "error diagnostic from PostToolUse".to_string(),
            }
        }
    }

    struct CountingPostHook(Arc<AtomicUsize>);

    #[async_trait]
    impl AgentHook for CountingPostHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterToolExecution
        }

        async fn run(
            &self,
            _point: AgentHookPoint,
            _payload: &HookPayload,
            _session: &Session,
        ) -> HookResult {
            self.0.fetch_add(1, Ordering::SeqCst);
            HookResult::Continue
        }
    }

    struct RecordingParentReviewer {
        seen: AtomicBool,
        approve: bool,
    }

    #[derive(Default)]
    struct BrowserApprovalRecorder(Mutex<Vec<bamboo_tools::ApprovalAsk>>);

    #[async_trait]
    impl bamboo_tools::ApprovalProxy for BrowserApprovalRecorder {
        async fn request_approval(&self, ask: bamboo_tools::ApprovalAsk) -> bool {
            self.0
                .lock()
                .expect("browser approval record lock")
                .push(ask);
            false
        }
    }

    #[async_trait]
    impl bamboo_tools::ApprovalProxy for RecordingParentReviewer {
        async fn request_approval(&self, ask: bamboo_tools::ApprovalAsk) -> bool {
            assert_eq!(ask.tool_name, "probe");
            assert_eq!(
                ask.permission_request
                    .as_ref()
                    .map(|request| request.reason_code),
                Some(bamboo_tools::permission::PermissionReasonCode::ConfiguredAlwaysAsk)
            );
            assert_eq!(
                ask.permission_request
                    .as_ref()
                    .map(|request| request.bypass_requested),
                Some(true),
                "hook ask must reach the parent reviewer even under bypass"
            );
            self.seen.store(true, Ordering::SeqCst);
            self.approve
        }
    }

    struct RecordingExecutor(AtomicBool);

    #[async_trait]
    impl ToolExecutor for RecordingExecutor {
        async fn execute(&self, _call: &ToolCall) -> Result<ToolResult, ToolError> {
            self.0.store(true, Ordering::SeqCst);
            Ok(ToolResult {
                success: true,
                result: "executed".to_string(),
                display_preference: None,
                images: Vec::new(),
            })
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            Vec::new()
        }
    }

    struct NameRecordingExecutor {
        entered: Mutex<Vec<String>>,
        schemas: Vec<ToolSchema>,
    }

    impl NameRecordingExecutor {
        fn new(schema_names: &[&str]) -> Self {
            Self {
                entered: Mutex::new(Vec::new()),
                schemas: schema_names.iter().copied().map(tool_schema).collect(),
            }
        }

        fn entered(&self) -> Vec<String> {
            self.entered
                .lock()
                .expect("capability gate probe lock")
                .clone()
        }
    }

    #[async_trait]
    impl ToolExecutor for NameRecordingExecutor {
        async fn execute(&self, call: &ToolCall) -> Result<ToolResult, ToolError> {
            self.entered
                .lock()
                .expect("capability gate probe lock")
                .push(call.function.name.clone());
            Ok(ToolResult::text(true, "executed"))
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            self.schemas.clone()
        }
    }

    #[derive(Default)]
    struct ExactOwnerRecordingExecutor {
        ordinary_dispatches: Mutex<Vec<String>>,
        exact_dispatches: Mutex<Vec<(String, String)>>,
        output_caps: Mutex<Vec<Option<u32>>>,
    }

    #[async_trait]
    impl ToolExecutor for ExactOwnerRecordingExecutor {
        async fn execute(&self, call: &ToolCall) -> Result<ToolResult, ToolError> {
            self.ordinary_dispatches
                .lock()
                .expect("ordinary dispatch probe lock")
                .push(call.function.name.clone());
            Ok(ToolResult::text(true, "ordinary dispatch"))
        }

        async fn execute_exact_with_context_outcome(
            &self,
            call: &ToolCall,
            execution_name: &str,
            ctx: ToolExecutionContext<'_>,
        ) -> Result<ToolOutcome, ToolError> {
            let cap = bamboo_agent_core::tools::observed_tool_output_cap(&ctx.to_tool_ctx());
            self.output_caps.lock().unwrap().push(cap);
            tokio::task::yield_now().await;
            assert_eq!(
                bamboo_agent_core::tools::observed_tool_output_cap(&ctx.to_tool_ctx()),
                cap
            );
            self.exact_dispatches
                .lock()
                .expect("exact dispatch probe lock")
                .push((call.function.name.clone(), execution_name.to_string()));
            Ok(ToolOutcome::Completed(ToolResult::text(
                true,
                "exact dispatch",
            )))
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            ["Edit", "apply_patch"]
                .into_iter()
                .map(tool_schema)
                .collect()
        }
    }

    enum NonTerminalOutcome {
        Running,
        NeedsHuman,
    }

    struct NonTerminalExecutor(NonTerminalOutcome);

    #[async_trait]
    impl ToolExecutor for NonTerminalExecutor {
        async fn execute(&self, _call: &ToolCall) -> Result<ToolResult, ToolError> {
            unreachable!("the outcome-aware path must be used")
        }

        async fn execute_with_context_outcome(
            &self,
            call: &ToolCall,
            ctx: bamboo_agent_core::tools::ToolExecutionContext<'_>,
        ) -> Result<ToolOutcome, ToolError> {
            assert_eq!(
                bamboo_agent_core::tools::observed_tool_output_cap(&ctx.to_tool_ctx()),
                Some(97)
            );
            match self.0 {
                NonTerminalOutcome::Running => Ok(ToolOutcome::Running(RunningHandle {
                    tool_call_id: call.id.clone(),
                    ack: ToolResult::text(true, "running"),
                    completion: RunningCompletion::Detached,
                    wait_kind: AsyncWaitKind::AsyncTools,
                    kill: Box::new(|| {}),
                })),
                NonTerminalOutcome::NeedsHuman => Ok(ToolOutcome::NeedsHuman {
                    question: bamboo_agent_core::PendingQuestion {
                        tool_call_id: call.id.clone(),
                        tool_name: call.function.name.clone(),
                        question: "Choose?".to_string(),
                        options: vec!["yes".to_string(), "no".to_string()],
                        allow_custom: false,
                        source: bamboo_agent_core::PendingQuestionSource::PauseTool,
                    },
                    result: ToolResult::text(false, "decision pending"),
                }),
            }
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            Vec::new()
        }
    }

    struct PanicLegacyApprovalDelegate;

    #[async_trait]
    impl crate::runtime::config::ApprovalDelegate for PanicLegacyApprovalDelegate {
        async fn delegate_child_approval(
            &self,
            _request: crate::runtime::config::ChildApprovalRequest,
        ) -> Result<crate::runtime::config::ChildApprovalOutcome, String> {
            panic!("Hook Ask must not enter the legacy interactive approval path")
        }
    }

    fn probe_call(name: &str) -> ToolCall {
        ToolCall {
            id: format!("call-{name}"),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: serde_json::json!({"value": 7}).to_string(),
            },
        }
    }

    struct ShellFeedbackHook(String);

    #[async_trait]
    impl AgentHook for ShellFeedbackHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::AfterToolExecution
        }

        async fn run(&self, _: AgentHookPoint, _: &HookPayload, _: &Session) -> HookResult {
            HookResult::InjectContext {
                text: self.0.clone(),
            }
        }
    }

    #[tokio::test]
    async fn shell_post_hook_feedback_keeps_json_protocol_and_respects_output_caps() {
        use bamboo_compression::{TiktokenTokenCounter, TokenCounter};

        let feedback = "review 界🦀\\\"\n".repeat(1_000);
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(ShellFeedbackHook(feedback.clone())));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let tools: Arc<dyn ToolExecutor> = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        for (requested, execution_name) in [
            ("exec_command", "exec_command"),
            ("default::write_stdin", "write_stdin"),
        ] {
            for status in ["running", "completed"] {
                for cap in [0, 1, 256] {
                    let call = probe_call(requested);
                    let mut payload = serde_json::json!({"status":status,"output":"captured output ".repeat(100)});
                    if status == "running" {
                        payload["session_id"] = "retained-handle".into();
                    } else {
                        payload["exit_code"] = 7.into();
                    }
                    let original_output = payload["output"].as_str().unwrap().to_owned();
                    let outcome = ToolExecutionOutcome {
                        output_cap: Some(Some(cap)),
                        portable_tool: Some(PortableToolExecution {
                            name: execution_name.into(),
                            input: serde_json::json!({}),
                        }),
                        permission_replay_origin: None,
                        result: Ok(ToolResult::text(true, payload.to_string())),
                        needs_human: None,
                        post_tool_hook_eligible: true,
                        managed_running_violation: false,
                        tool_duration: std::time::Duration::ZERO,
                    };
                    let (event_tx, _event_rx) = mpsc::channel(64);
                    let mut session = Session::new("shell-feedback", "model");
                    apply_test_outcome(&config, &tools, &call, &mut session, &event_tx, outcome)
                        .await
                        .unwrap();
                    let message = session
                        .messages
                        .iter()
                        .find(|message| message.tool_call_id.as_deref() == Some(call.id.as_str()))
                        .unwrap();
                    assert_eq!(message.tool_success, Some(true));
                    let received: serde_json::Value =
                        serde_json::from_str(&message.content).unwrap();
                    assert_eq!(received["status"], status);
                    if status == "running" {
                        assert_eq!(received["session_id"], "retained-handle");
                    } else {
                        assert_eq!(received["exit_code"], 7);
                    }
                    let retained_feedback = received["hook_feedback"]
                        .as_array()
                        .into_iter()
                        .flatten()
                        .map(|text| text.as_str().unwrap().len())
                        .sum::<usize>();
                    assert!(retained_feedback <= bamboo_hooks::portable::PORTABLE_CONTEXT_BYTES);
                    assert_eq!(
                        received["hook_feedback_omitted_bytes"].as_u64().unwrap() as usize
                            + retained_feedback,
                        feedback.trim().len(),
                    );
                    if cap > 0 {
                        assert!(received.get("hook_feedback").is_none());
                        let kept = received["output"].as_str().unwrap();
                        assert_eq!(
                            received["output_omitted_bytes"],
                            original_output.len() - kept.len()
                        );
                        if cap == 1 {
                            assert!(kept.is_empty());
                        } else {
                            assert!(
                                TiktokenTokenCounter::default().count_text(&message.content) <= cap
                            );
                        }
                    }
                }
            }
        }

        for name in ["Read", "vendor::exec_command", "vendor::write_stdin"] {
            let mut result = Ok(ToolResult::text(
                true,
                "{\"status\":\"running\",\"output\":\"\"}",
            ));
            append_post_tool_feedback(&mut result, vec!["ordinary feedback".into()], Some(name), 1);
            let content = result.unwrap().result;
            assert!(content.contains("<post_tool_use_feedback>"));
            assert!(serde_json::from_str::<serde_json::Value>(&content).is_err());
        }
    }

    fn tool_schema(name: &str) -> ToolSchema {
        ToolSchema {
            schema_type: "function".to_string(),
            function: FunctionSchema {
                name: name.to_string(),
                description: format!("{name} capability gate probe"),
                parameters: serde_json::json!({"type": "object"}),
            },
        }
    }

    fn effective_callable_set(
        catalog_names: &[&str],
        mode: CapabilityLoadingMode,
        loaded_names: &[&str],
    ) -> EffectiveCallableSet {
        let catalog = catalog_names
            .iter()
            .copied()
            .map(tool_schema)
            .filter_map(ClassifiedToolSchema::new)
            .collect::<Vec<_>>();
        EffectiveCallableSet::from_catalog(&catalog, mode, loaded_names.iter().copied())
    }

    struct OriginalToolNameRecorder(Mutex<Vec<String>>);
    #[async_trait]
    impl AgentHook for OriginalToolNameRecorder {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::BeforeToolExecution
        }
        async fn run(&self, _: AgentHookPoint, payload: &HookPayload, _: &Session) -> HookResult {
            if let HookPayload::ToolExecution { tool_name, .. } = payload {
                self.0.lock().unwrap().push(tool_name.clone());
            }
            HookResult::Continue
        }
    }

    async fn portable_alias_policy(
        pre_command: &str,
        canonical: &str,
    ) -> (tempfile::TempDir, AgentLoopConfig) {
        use bamboo_plugin::{
            InstalledPlugin, InstalledPlugins, PluginInstallStatus, PluginManifest, PluginSource,
            RegisteredCapabilities,
        };
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("plugins");
        let bundle = root.join("alias-policy");
        std::fs::create_dir_all(&bundle).unwrap();
        let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
            "id":"alias-policy", "name":"Alias policy", "version":"0.1.0",
            "provides":{"hooks":[{"config":"hooks.json","scripts":["policy.sh"]}]}
        }))
        .unwrap();
        std::fs::write(
            bundle.join("plugin.json"),
            serde_json::to_vec(&manifest).unwrap(),
        )
        .unwrap();
        std::fs::write(bundle.join("policy.sh"), "# reviewed fixture").unwrap();
        let post_command = r#"payload=$(cat); case "$payload" in *'"tool_name":"Bash"'*'"tool_response":"exact dispatch"'*) printf '%s' '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"resolved Bash result"}}' ;; *) exit 1 ;; esac"#.replace("Bash", canonical);
        std::fs::write(bundle.join("hooks.json"), serde_json::to_vec(&serde_json::json!({"hooks":{
            "PreToolUse":[{"matcher":format!("^{canonical}$"),"hooks":[{"type":"command","command":pre_command,"timeout":1}]}],
            "PostToolUse":[{"matcher":format!("^{canonical}$"),"hooks":[{"type":"command","command":post_command,"timeout":1}]}]
        }})).unwrap()).unwrap();
        let mut hooks = bamboo_plugin::hooks::registrations(&manifest, &bundle).unwrap();
        let digest = hooks[0].digest.clone();
        hooks[0].confirm_review(&digest).unwrap();
        InstalledPlugins {
            plugins: vec![InstalledPlugin {
                id: manifest.id,
                version: manifest.version,
                source: PluginSource::LocalDir {
                    path: bundle.clone(),
                },
                plugin_dir: bundle,
                installed_at: chrono::Utc::now(),
                status: PluginInstallStatus::Installed,
                registered: RegisteredCapabilities {
                    hooks,
                    ..Default::default()
                },
            }],
        }
        .save(&root.join("installed.json"))
        .await
        .unwrap();
        let runner = crate::runtime::hooks::HookRunner::new().with_lifecycle_config(
            &LifecycleHooksConfig::default(),
            Some(temp.path().to_owned()),
        );
        (
            temp,
            AgentLoopConfig {
                hook_runner: Arc::new(runner),
                ..Default::default()
            },
        )
    }

    async fn execute_portable_alias_call(
        config: &AgentLoopConfig,
        tools: &Arc<dyn ToolExecutor>,
        callable: &EffectiveCallableSet,
        call: &ToolCall,
        event_tx: &mpsc::Sender<AgentEvent>,
    ) -> (ToolExecutionOutcome, Session) {
        let mut session = Session::new("portable-alias", "model");
        let flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime = AgentRuntimeState::new(&session.id);
        let outcome = execute_model_requested_tool_call_only(
            callable,
            ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: None,
                executing_supervisor: None,
                tool_call: call,
                event_tx,
                metrics_collector: None,
                session_id: "portable-alias",
                root_session_id: "portable-alias",
                root_orchestration_only: false,
                round_id: "round-1",
                round: 0,
                tools,
                config,
                hook_session: Some(&mut session),
                hook_runtime_state: Some(&mut runtime),
                session_flags: flags,
                available_tool_schemas: &[],
            },
        )
        .await
        .unwrap();
        (outcome, session)
    }

    #[tokio::test]
    async fn portable_hook_denies_resolved_aliases_but_preserves_exact_shadow_and_native_spelling()
    {
        // Legacy Bash policy still governs canonical shell calls; an exact
        // foreign tool with the same suffix keeps its own identity.
        let (_temp, mut config) = portable_alias_policy(r#"printf '%s' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Bash blocked"}}'"#, "Bash").await;
        let recorder = Arc::new(OriginalToolNameRecorder(Mutex::new(vec![])));
        Arc::make_mut(&mut config.hook_runner).register(recorder.clone());
        let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
        let tools: Arc<dyn ToolExecutor> = concrete.clone();
        let (event_tx, _event_rx) = mpsc::channel(64);
        let callable = effective_callable_set(
            &["exec_command"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        for name in ["exec_command", "default::exec_command"] {
            let mut call = probe_call(name);
            call.function.arguments = serde_json::json!({"cmd":"printf fixture"}).to_string();
            assert_eq!(
                callable.resolve_callable_reference(name).as_deref(),
                Some("exec_command")
            );
            let (outcome, _) =
                execute_portable_alias_call(&config, &tools, &callable, &call, &event_tx).await;
            assert!(
                matches!(outcome.result, Err(ref error) if error.contains("Bash blocked")),
                "{name}"
            );
            assert!(!outcome.post_tool_hook_eligible);
        }
        assert!(concrete.exact_dispatches.lock().unwrap().is_empty());
        let shadow = effective_callable_set(
            &["exec_command", "vendor::exec_command"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        let call = probe_call("vendor::exec_command");
        assert_eq!(
            shadow
                .resolve_callable_reference(&call.function.name)
                .as_deref(),
            Some("vendor::exec_command")
        );
        let (outcome, _) =
            execute_portable_alias_call(&config, &tools, &shadow, &call, &event_tx).await;
        assert!(outcome.result.is_ok());
        assert_eq!(
            *concrete.exact_dispatches.lock().unwrap(),
            vec![("vendor::exec_command".into(), "vendor::exec_command".into())]
        );
        assert_eq!(
            *recorder.0.lock().unwrap(),
            vec![
                "exec_command",
                "default::exec_command",
                "vendor::exec_command"
            ]
        );
    }

    #[tokio::test]
    async fn portable_hook_post_uses_selected_identity_and_original_executor_input() {
        let (_temp, config) = portable_alias_policy("true", "Bash").await;
        let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
        let tools: Arc<dyn ToolExecutor> = concrete;
        let (event_tx, _event_rx) = mpsc::channel(64);
        let callable = effective_callable_set(
            &["exec_command"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        let mut call = probe_call("default::exec_command");
        let input = serde_json::json!({"cmd":"printf fixture"});
        call.function.arguments = input.to_string();
        let (outcome, mut session) =
            execute_portable_alias_call(&config, &tools, &callable, &call, &event_tx).await;
        assert!(outcome.result.is_ok());
        assert_eq!(outcome.portable_tool.as_ref().unwrap().name, "exec_command");
        assert_eq!(outcome.portable_tool.as_ref().unwrap().input, input);
        apply_test_outcome(&config, &tools, &call, &mut session, &event_tx, outcome)
            .await
            .unwrap();
        assert!(session
            .metadata
            .get("runtime.plugin_hook_contexts")
            .unwrap()
            .contains("resolved Bash result"));
    }

    #[tokio::test]
    async fn portable_hook_post_observes_repaired_non_strict_arguments() {
        let (_temp, config) = portable_alias_policy("true", "Read").await;
        let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
        let tools: Arc<dyn ToolExecutor> = concrete;
        let (event_tx, _event_rx) = mpsc::channel(64);
        let callable =
            effective_callable_set(&["Read"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
        let mut call = probe_call("Read");
        call.function.arguments = "{\"file_path\":\"/fixture\"".into();
        assert!(serde_json::from_str::<serde_json::Value>(&call.function.arguments).is_err());
        let (outcome, mut session) =
            execute_portable_alias_call(&config, &tools, &callable, &call, &event_tx).await;
        assert!(outcome.result.is_ok());
        assert_eq!(
            outcome.portable_tool.as_ref().unwrap().input,
            serde_json::json!({"file_path":"/fixture"})
        );
        apply_test_outcome(&config, &tools, &call, &mut session, &event_tx, outcome)
            .await
            .unwrap();
        assert!(session
            .metadata
            .get("runtime.plugin_hook_contexts")
            .unwrap()
            .contains("resolved Read result"));
    }

    async fn check_cap_live_portable_activation(sequential: bool, cap: Option<u32>, allow: bool) {
        let command = if allow {
            r#"printf '%s' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"portable cap truth"}}'"#
        } else {
            r#"printf '%s' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Bash blocked"}}'"#
        };
        let (temp, config) = portable_alias_policy(command, "Bash").await;
        let registry = temp.path().join("plugins/installed.json");
        let mut store = bamboo_plugin::InstalledPlugins::load(&registry)
            .await
            .unwrap();
        store.plugins[0].registered.hooks[0].enabled = false;
        store.save(&registry).await.unwrap();
        assert!(!config
            .hook_runner
            .has_hooks_for(AgentHookPoint::BeforeToolExecution));

        let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
        let tools: Arc<dyn ToolExecutor> = concrete.clone();
        let callable = effective_callable_set(
            &["exec_command"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        let mut call = probe_call("exec_command");
        call.function.arguments = serde_json::json!({"cmd":"printf fixture"}).to_string();
        let mut session = Session::new("live-hook-review", "model");
        session.token_budget = cap.map(|n| bamboo_domain::TokenBudget {
            max_tool_output_tokens: n,
            ..Default::default()
        });
        let flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime = AgentRuntimeState::new(&session.id);
        let (event_tx, mut event_rx) = mpsc::channel(1);
        // Hold ToolStart at a deterministic await after admission, without sleeps.
        event_tx
            .send(AgentEvent::Token {
                content: "barrier".into(),
            })
            .await
            .unwrap();
        let outcome = {
            let execution = execute_model_requested_tool_call_only(
                &callable,
                ToolExecutionOnlyContext {
                    vision_support: true,
                    output_cap: cap,
                    executing_supervisor: None,
                    tool_call: &call,
                    event_tx: &event_tx,
                    metrics_collector: None,
                    session_id: "live-hook-review",
                    root_session_id: "live-hook-review",
                    root_orchestration_only: false,
                    round_id: "round-1",
                    round: 0,
                    tools: &tools,
                    config: &config,
                    hook_session: sequential.then_some(&mut session),
                    hook_runtime_state: sequential.then_some(&mut runtime),
                    session_flags: flags,
                    available_tool_schemas: &[],
                },
            );
            tokio::pin!(execution);
            tokio::select! {
                biased;
                _ = &mut execution => panic!("ToolStart must be waiting on the barrier"),
                _ = std::future::ready(()) => {}
            }
            store.plugins[0].registered.hooks[0].enabled = true;
            store.save(&registry).await.unwrap();
            assert!(config
                .hook_runner
                .has_hooks_for(AgentHookPoint::BeforeToolExecution));
            assert!(matches!(
                event_rx.recv().await.unwrap(),
                AgentEvent::Token { .. }
            ));
            let outcome = loop {
                tokio::select! {
                    result = &mut execution => break result.unwrap(),
                    event = event_rx.recv() => { assert!(event.is_some()); }
                }
            };
            outcome
        };
        if sequential && allow {
            assert_eq!(outcome.output_cap, Some(cap));
            assert_eq!(outcome.result.as_ref().unwrap().result, "exact dispatch");
            assert_eq!(outcome.portable_tool.as_ref().unwrap().name, "exec_command");
            assert_eq!(*concrete.output_caps.lock().unwrap(), vec![cap]);
            assert!(session.metadata["runtime.plugin_hook_contexts"].contains("portable cap truth"));
            assert_eq!(
                session
                    .effective_token_budget()
                    .map(|b| b.max_tool_output_tokens),
                cap
            );
            assert!(session.resolved_token_budget.is_none());
            return;
        }
        assert_eq!(outcome.output_cap, None);
        assert!(concrete.output_caps.lock().unwrap().is_empty());
        let expected = if sequential {
            "Bash blocked"
        } else {
            "hooks became active after parallel admission"
        };
        assert!(matches!(outcome.result, Err(ref error) if error.contains(expected)));
        assert!(!outcome.post_tool_hook_eligible);
        assert!(outcome.portable_tool.is_none());
        assert!(concrete.exact_dispatches.lock().unwrap().is_empty());
        let (reply_tx, _reply_rx) = mpsc::channel(64);
        apply_test_outcome(&config, &tools, &call, &mut session, &reply_tx, outcome)
            .await
            .unwrap();
        let reply = session.messages.last().unwrap();
        assert_eq!(reply.tool_call_id.as_deref(), Some(call.id.as_str()));
        assert_eq!(reply.tool_success, Some(false));
        assert!(reply.content.contains(expected));
        if allow {
            // A real fresh sequential retry captures the changed local value;
            // the blocked parallel call is never silently rescheduled.
            let current = Some(cap.unwrap_or(0) + 97);
            session.token_budget = current.map(|n| bamboo_domain::TokenBudget {
                max_tool_output_tokens: n,
                ..Default::default()
            });
            let retry = execute_cap_hook_call(&mut session, &tools, &config, &call)
                .await
                .unwrap();
            assert_eq!(retry.output_cap, Some(current));
            assert_eq!(*concrete.output_caps.lock().unwrap(), vec![current]);
            assert_eq!(retry.result.unwrap().result, "exact dispatch");
        }
    }

    async fn check_live_portable_activation(sequential: bool) {
        check_cap_live_portable_activation(sequential, None, false).await;
    }

    #[tokio::test]
    async fn scoped_cap_late_portable_activation_and_fresh_retry_observe_actual_values() {
        for cap in [None, Some(0), Some(53)] {
            for sequential in [false, true] {
                for allow in [false, true] {
                    check_cap_live_portable_activation(sequential, cap, allow).await;
                }
            }
        }
    }

    #[tokio::test]
    async fn portable_hook_activation_after_parallel_admission_fails_closed() {
        check_live_portable_activation(false).await;
    }

    #[tokio::test]
    async fn portable_hook_activation_during_sequential_tool_start_enforces_policy() {
        check_live_portable_activation(true).await;
    }

    async fn execute_without_hooks(
        effective_callable_set: &EffectiveCallableSet,
        tools: &Arc<dyn ToolExecutor>,
        tool_call: &ToolCall,
        event_tx: &mpsc::Sender<AgentEvent>,
    ) -> ToolExecutionOutcome {
        execute_without_hooks_with_root_authority(
            effective_callable_set,
            tools,
            tool_call,
            event_tx,
            false,
        )
        .await
    }

    async fn execute_without_hooks_with_root_authority(
        effective_callable_set: &EffectiveCallableSet,
        tools: &Arc<dyn ToolExecutor>,
        tool_call: &ToolCall,
        event_tx: &mpsc::Sender<AgentEvent>,
        root_orchestration_only: bool,
    ) -> ToolExecutionOutcome {
        let session = Session::new("capability-gate-session", "model");
        execute_model_requested_tool_call_only(
            effective_callable_set,
            ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: None,
                executing_supervisor: None,
                tool_call,
                event_tx,
                metrics_collector: None,
                session_id: "capability-gate-session",
                root_orchestration_only,
                root_session_id: "capability-gate-session",
                round_id: "round-1",
                round: 0,
                tools,
                config: &AgentLoopConfig::default(),
                hook_session: None,
                hook_runtime_state: None,
                session_flags: ToolExecutionSessionFlags::from_session(&session),
                available_tool_schemas: &[],
            },
        )
        .await
        .expect("capability admission is a per-call outcome")
    }

    #[tokio::test]
    async fn capability_gate_allows_legacy_deferred_and_progressive_core_or_loaded_calls() {
        let concrete_tools = Arc::new(NameRecordingExecutor::new(&["Read", "probe"]));
        let tools: Arc<dyn ToolExecutor> = concrete_tools.clone();
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let legacy = effective_callable_set(
            &["Read", "probe"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        let progressive = effective_callable_set(
            &["Read", "probe"],
            CapabilityLoadingMode::Progressive,
            &["probe"],
        );

        let legacy_deferred =
            execute_without_hooks(&legacy, &tools, &probe_call("probe"), &event_tx).await;
        let progressive_core =
            execute_without_hooks(&progressive, &tools, &probe_call("Read"), &event_tx).await;
        let progressive_loaded =
            execute_without_hooks(&progressive, &tools, &probe_call("probe"), &event_tx).await;

        assert!(legacy_deferred.result.is_ok());
        assert!(progressive_core.result.is_ok());
        assert!(progressive_loaded.result.is_ok());
        assert_eq!(concrete_tools.entered(), ["probe", "Read", "probe"]);
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert_eq!(
            events
                .iter()
                .filter(|event| matches!(event, AgentEvent::ToolStart { .. }))
                .count(),
            3
        );
    }

    #[tokio::test]
    async fn admitted_shells_reject_repairable_json_before_tool_start_or_side_effects() {
        let temp = tempfile::tempdir().unwrap();
        let sentinel = temp.path().join("must-not-exist");
        let tools: Arc<dyn ToolExecutor> = Arc::new(bamboo_tools::BuiltinToolExecutor::new());
        let callable = effective_callable_set(
            &["exec_command", "write_stdin"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        let (event_tx, mut event_rx) = mpsc::channel(32);
        for (name, args) in [
            (
                "exec_command",
                serde_json::json!({"cmd":format!("touch '{}'", sentinel.display())}),
            ),
            (
                "default::exec_command",
                serde_json::json!({"cmd":format!("touch '{}'", sentinel.display())}),
            ),
            (
                "write_stdin",
                serde_json::json!({"session_id":"not-owned", "chars":"yes\n"}),
            ),
            (
                "default::write_stdin",
                serde_json::json!({"session_id":"not-owned", "eof":true}),
            ),
        ] {
            let mut call = probe_call(name);
            call.function.arguments = args.to_string();
            call.function.arguments.pop();
            assert!(parse_tool_args_best_effort(&call.function.arguments)
                .1
                .is_some());
            let outcome = execute_without_hooks(&callable, &tools, &call, &event_tx).await;
            assert!(
                matches!(outcome.result, Err(ref error) if error.contains("invalid JSON arguments"))
            );
            assert!(!outcome.post_tool_hook_eligible);
            assert!(!sentinel.exists());
        }
        assert!(std::iter::from_fn(|| event_rx.try_recv().ok())
            .all(|event| !matches!(event, AgentEvent::ToolStart { .. })));

        let concrete = Arc::new(NameRecordingExecutor::new(&[
            "vendor::exec_command",
            "vendor::write_stdin",
        ]));
        let tools: Arc<dyn ToolExecutor> = concrete.clone();
        let callable = effective_callable_set(
            &["vendor::exec_command", "vendor::write_stdin"],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        for name in ["vendor::exec_command", "vendor::write_stdin"] {
            let mut call = probe_call(name);
            call.function.arguments = "{\"ordinary\":true".into();
            assert!(execute_without_hooks(&callable, &tools, &call, &event_tx)
                .await
                .result
                .is_ok());
        }
        assert_eq!(
            concrete.entered(),
            ["vendor::exec_command", "vendor::write_stdin"]
        );
    }

    #[tokio::test]
    async fn supervisor_delegation_first_final_gate_rejects_stale_execution_schemas_in_both_modes()
    {
        use bamboo_domain::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        let names = [
            "Read",
            "SubAgent",
            "Plan",
            "Task",
            "session_control",
            "session_history",
            "loop_control",
            "work_dispatch",
            "exec_command",
            "write_stdin",
            "Edit",
            "load_skill",
            "vendor::Read",
            "default::Read",
        ];
        let mut supervisor = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        supervisor.authority_identity = SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        // The supplied catalog deliberately predates any restriction.
        let callable =
            effective_callable_set(&names, CapabilityLoadingMode::LegacyFullCatalog, &[]);
        for ultra in [false, true] {
            supervisor.set_root_orchestration_only(ultra).unwrap();
            let observation =
                ExecutingSupervisorObservation::capture_from_executing_session(&supervisor);
            let concrete = Arc::new(NameRecordingExecutor::new(&names));
            let tools: Arc<dyn ToolExecutor> = concrete.clone();
            let (tx, mut rx) = mpsc::channel(128);
            for name in names {
                let call = probe_call(name);
                let outcome = execute_model_requested_tool_call_only(
                    &callable,
                    ToolExecutionOnlyContext {
                        vision_support: true,
                        output_cap: None,
                        executing_supervisor: observation,
                        tool_call: &call,
                        event_tx: &tx,
                        metrics_collector: None,
                        session_id: &supervisor.id,
                        root_session_id: &supervisor.root_session_id,
                        root_orchestration_only: ultra,
                        round_id: "delegation-first",
                        round: 0,
                        tools: &tools,
                        config: &AgentLoopConfig::default(),
                        hook_session: None,
                        hook_runtime_state: None,
                        session_flags: ToolExecutionSessionFlags::from_session(&supervisor),
                        available_tool_schemas: &[],
                    },
                )
                .await
                .unwrap();
                let allowed = matches!(
                    name,
                    "Read"
                        | "SubAgent"
                        | "Plan"
                        | "Task"
                        | "session_control"
                        | "session_history"
                        | "work_dispatch"
                );
                assert_eq!(outcome.result.is_ok(), allowed, "ultra={ultra}: {name}");
                if !allowed {
                    assert!(!outcome.post_tool_hook_eligible);
                    assert!(outcome.portable_tool.is_none());
                }
            }
            let expected = vec![
                "Read",
                "SubAgent",
                "Plan",
                "Task",
                "session_control",
                "session_history",
                "work_dispatch",
            ];
            assert_eq!(concrete.entered(), expected);
            assert_eq!(
                std::iter::from_fn(|| rx.try_recv().ok())
                    .filter(|event| matches!(event, AgentEvent::ToolStart { .. }))
                    .count(),
                expected.len()
            );
        }
    }

    #[tokio::test]
    async fn supervisor_ultra_final_gate_uses_original_observation_and_exact_management_tool() {
        use bamboo_domain::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        let names = [
            "session_control",
            "session_history",
            "exec_command",
            "vendor::session_control",
            "default::session_control",
        ];
        let mut supervisor = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        supervisor.authority_identity = SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        supervisor.set_root_orchestration_only(true).unwrap();
        let observed = ExecutingSupervisorObservation::capture_from_executing_session(&supervisor);
        let callable =
            effective_callable_set(&names, CapabilityLoadingMode::LegacyFullCatalog, &[]);
        for (observation, caller) in [
            (observed, DEFAULT_SUPERVISOR_SESSION_ID),
            (None, DEFAULT_SUPERVISOR_SESSION_ID),
            (observed, "ordinary-root"),
        ] {
            let concrete = Arc::new(NameRecordingExecutor::new(&names));
            let tools: Arc<dyn ToolExecutor> = concrete.clone();
            let (tx, mut rx) = mpsc::channel(64);
            for name in names {
                let call = probe_call(name);
                let outcome = execute_model_requested_tool_call_only(
                    &callable,
                    ToolExecutionOnlyContext {
                        vision_support: true,
                        output_cap: None,
                        executing_supervisor: observation,
                        tool_call: &call,
                        event_tx: &tx,
                        metrics_collector: None,
                        session_id: caller,
                        root_session_id: caller,
                        root_orchestration_only: true,
                        round_id: "round-1",
                        round: 0,
                        tools: &tools,
                        config: &AgentLoopConfig::default(),
                        hook_session: None,
                        hook_runtime_state: None,
                        session_flags: ToolExecutionSessionFlags::from_session(&supervisor),
                        available_tool_schemas: &[],
                    },
                )
                .await
                .unwrap();
                let allowed = observation.is_some()
                    && caller == DEFAULT_SUPERVISOR_SESSION_ID
                    && matches!(name, "session_control" | "session_history");
                assert_eq!(outcome.result.is_ok(), allowed, "{caller}: {name}");
            }
            let expected = if observation.is_some() && caller == DEFAULT_SUPERVISOR_SESSION_ID {
                vec!["session_control", "session_history"]
            } else {
                vec![]
            };
            assert_eq!(concrete.entered(), expected);
            assert_eq!(
                std::iter::from_fn(|| rx.try_recv().ok())
                    .filter(|event| matches!(event, AgentEvent::ToolStart { .. }))
                    .count(),
                expected.len()
            );
        }
    }

    #[tokio::test]
    async fn selected_root_final_gate_rejects_stale_schema_and_exact_alias_before_tool_start() {
        let concrete_tools = Arc::new(NameRecordingExecutor::new(&[
            "Read",
            "exec_command",
            "write_stdin",
            "Edit",
            "apply_patch",
            "default::Read",
        ]));
        let tools: Arc<dyn ToolExecutor> = concrete_tools.clone();
        // Deliberately stale: the loaded callable set still contains names that
        // the live Root authority now denies.
        let stale = effective_callable_set(
            &[
                "Read",
                "exec_command",
                "write_stdin",
                "Edit",
                "apply_patch",
                "default::Read",
            ],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        let (event_tx, mut event_rx) = mpsc::channel(32);
        for name in [
            "exec_command",
            "default::exec_command",
            "write_stdin",
            "Edit",
            "apply_patch",
            "default::Read",
        ] {
            let outcome = execute_without_hooks_with_root_authority(
                &stale,
                &tools,
                &probe_call(name),
                &event_tx,
                true,
            )
            .await;
            assert!(matches!(
                outcome.result,
                Err(ref error) if error.contains("outside orchestration-only Root authority")
            ));
            assert!(!outcome.post_tool_hook_eligible);
        }
        let allowed = execute_without_hooks_with_root_authority(
            &stale,
            &tools,
            &probe_call("read_file"),
            &event_tx,
            true,
        )
        .await;
        assert!(allowed.result.is_ok());
        assert_eq!(concrete_tools.entered(), ["Read"]);
        let starts = std::iter::from_fn(|| event_rx.try_recv().ok())
            .filter(|event| matches!(event, AgentEvent::ToolStart { .. }))
            .count();
        assert_eq!(starts, 1);
    }

    #[tokio::test]
    async fn malformed_namespaced_browser_call_starts_with_fixed_display_name() {
        let concrete_tools = Arc::new(NameRecordingExecutor::new(&["browser"]));
        let tools: Arc<dyn ToolExecutor> = concrete_tools;
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let callable =
            effective_callable_set(&["browser"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
        let mut call = probe_call("private-selector::browser");
        call.function.arguments = "{malformed".to_string();
        let _ = execute_without_hooks(&callable, &tools, &call, &event_tx).await;
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert!(events.iter().any(|event| matches!(
            event,
            AgentEvent::ToolStart { tool_name, arguments, .. }
                if tool_name == "browser" && !arguments.to_string().contains("private-selector")
        )));
        assert_eq!(call.function.name, "private-selector::browser");
    }

    #[tokio::test]
    async fn capability_gate_rejects_unloaded_host_only_unknown_and_excluded_before_hooks() {
        let concrete_tools = Arc::new(NameRecordingExecutor::new(&[
            "Read",
            "probe",
            "Workspace",
            "excluded",
        ]));
        let tools: Arc<dyn ToolExecutor> = concrete_tools.clone();
        let effective_callable_set = effective_callable_set(
            &["Read", "probe", "Workspace"],
            CapabilityLoadingMode::Progressive,
            &[],
        );
        let (event_tx, mut event_rx) = mpsc::channel(16);

        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(DenyToolHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let unloaded_call = probe_call("probe");
        let mut session = Session::new("capability-gate-hook-session", "model");
        let session_flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime_state = AgentRuntimeState::new(&session.id);
        let unloaded = execute_model_requested_tool_call_only(
            &effective_callable_set,
            ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: None,
                executing_supervisor: None,
                tool_call: &unloaded_call,
                event_tx: &event_tx,
                metrics_collector: None,
                session_id: "capability-gate-hook-session",
                root_orchestration_only: false,
                root_session_id: "capability-gate-hook-session",
                round_id: "round-1",
                round: 0,
                tools: &tools,
                config: &config,
                hook_session: Some(&mut session),
                hook_runtime_state: Some(&mut runtime_state),
                session_flags,
                available_tool_schemas: &[],
            },
        )
        .await
        .expect("unloaded rejection is a per-call outcome");

        let mut outcomes = vec![("probe", unloaded)];
        for name in ["Workspace", "unknown_tool", "excluded"] {
            outcomes.push((
                name,
                execute_without_hooks(
                    &effective_callable_set,
                    &tools,
                    &probe_call(name),
                    &event_tx,
                )
                .await,
            ));
        }

        for (name, outcome) in outcomes {
            assert!(matches!(
                outcome.result,
                Err(ref error)
                    if error.contains(name)
                        && error.contains("not callable at the current conversation position")
            ));
        }
        assert!(concrete_tools.entered().is_empty());
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert!(events.iter().all(|event| !matches!(
            event,
            AgentEvent::ToolStart { .. } | AgentEvent::HookLifecycle { .. }
        )));
    }

    #[tokio::test]
    async fn capability_gate_preserves_exact_shadow_without_alias_fallback() {
        let concrete_tools = Arc::new(NameRecordingExecutor::new(&["Edit", "apply_patch"]));
        let tools: Arc<dyn ToolExecutor> = concrete_tools.clone();
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let core_only = effective_callable_set(
            &["Edit", "apply_patch"],
            CapabilityLoadingMode::Progressive,
            &[],
        );
        let exact_loaded = effective_callable_set(
            &["Edit", "apply_patch"],
            CapabilityLoadingMode::Progressive,
            &["apply_patch"],
        );
        let exact_call = probe_call("apply_patch");

        let rejected = execute_without_hooks(&core_only, &tools, &exact_call, &event_tx).await;
        let admitted = execute_without_hooks(&exact_loaded, &tools, &exact_call, &event_tx).await;

        assert!(matches!(
            rejected.result,
            Err(ref error) if error.contains("not callable at the current conversation position")
        ));
        assert!(admitted.result.is_ok());
        assert_eq!(concrete_tools.entered(), ["apply_patch"]);
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert_eq!(
            events
                .iter()
                .filter(|event| matches!(event, AgentEvent::ToolStart { .. }))
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn capability_gate_dispatches_the_resolved_owner_without_reresolving_original_shadow() {
        let concrete_tools = Arc::new(ExactOwnerRecordingExecutor::default());
        let tools: Arc<dyn ToolExecutor> = concrete_tools.clone();
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let effective_callable_set =
            effective_callable_set(&["Edit"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
        let call = probe_call("apply_patch");
        assert_eq!(
            effective_callable_set
                .resolve_callable_reference(&call.function.name)
                .as_deref(),
            Some("Edit"),
            "with no exact registration in the eligible catalog, the shared resolver selects the allowed builtin owner"
        );

        let outcome =
            execute_without_hooks(&effective_callable_set, &tools, &call, &event_tx).await;

        assert!(outcome.result.is_ok());
        assert!(concrete_tools
            .ordinary_dispatches
            .lock()
            .expect("ordinary dispatch probe lock")
            .is_empty());
        assert_eq!(
            *concrete_tools
                .exact_dispatches
                .lock()
                .expect("exact dispatch probe lock"),
            vec![("apply_patch".to_string(), "Edit".to_string())]
        );
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert!(events.iter().any(|event| matches!(
            event,
            AgentEvent::ToolStart { tool_name, .. } if tool_name == "apply_patch"
        )));
    }

    async fn apply_test_outcome(
        config: &AgentLoopConfig,
        tools: &Arc<dyn ToolExecutor>,
        tool_call: &ToolCall,
        session: &mut Session,
        event_tx: &mpsc::Sender<AgentEvent>,
        outcome: ToolExecutionOutcome,
    ) -> Result<bool, AgentError> {
        let session_id = session.id.clone();
        let mut runtime_state = AgentRuntimeState::new(&session.id);
        let mut task_context = None;
        let mut state = RoundExecutionState::default();
        let session_flags = ToolExecutionSessionFlags::from_session_and_configured_mode(
            session,
            config.permission_mode.unwrap_or_default(),
        );
        let admitted_execution_name = outcome
            .portable_tool
            .as_ref()
            .map(|tool| tool.execution_name().to_owned());
        apply_tool_execution_outcome(
            ToolExecutionApplyContext {
                policy_guard: &mut policy::ToolPolicyGuard::default(),
                admitted_execution_name: admitted_execution_name.as_deref(),
                tool_call,
                event_tx,
                metrics_collector: None,
                session_id: &session_id,
                round_id: "round-1",
                round: 0,
                session,
                tools,
                session_flags,
                config,
                runtime_state: &mut runtime_state,
                task_context: &mut task_context,
                state: &mut state,
            },
            outcome,
        )
        .await
    }

    #[tokio::test]
    async fn needs_human_uses_runner_identity_and_persists_before_clarification_event() {
        let persistence = Arc::new(BlockingPendingPersistence::default());
        let config = AgentLoopConfig {
            persistence: Some(persistence.clone()),
            ..Default::default()
        };
        let tools: Arc<dyn ToolExecutor> = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let tool_call = probe_call("canonical-tool");
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let outcome = ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Ok(ToolResult::text(false, "decision pending")),
            needs_human: Some(bamboo_agent_core::PendingQuestion {
                tool_call_id: "stale-call".to_string(),
                tool_name: "stale-tool".to_string(),
                question: "Choose?".to_string(),
                options: vec!["yes".to_string(), "no".to_string()],
                allow_custom: false,
                source: bamboo_agent_core::PendingQuestionSource::PauseTool,
            }),
            portable_tool: None,
            post_tool_hook_eligible: false,
            managed_running_violation: false,
            tool_duration: std::time::Duration::from_millis(1),
        };

        let apply = tokio::spawn(async move {
            let mut session = Session::new("canonical-pending", "model");
            apply_test_outcome(
                &config,
                &tools,
                &tool_call,
                &mut session,
                &event_tx,
                outcome,
            )
            .await
            .unwrap();
            session
        });

        tokio::time::timeout(
            std::time::Duration::from_secs(5),
            persistence.entered.notified(),
        )
        .await
        .expect("pending-question persistence should begin");
        let events_before_save: Vec<_> = std::iter::from_fn(|| event_rx.try_recv().ok()).collect();
        assert!(events_before_save
            .iter()
            .any(|event| matches!(event, AgentEvent::ToolComplete { .. })));
        assert!(!events_before_save
            .iter()
            .any(|event| matches!(event, AgentEvent::NeedClarification { .. })));

        let saved = persistence
            .saved
            .lock()
            .expect("pending persistence lock")
            .last()
            .cloned()
            .expect("pending session snapshot");
        let persisted_question = saved.pending_question.expect("persisted pending question");
        assert_eq!(persisted_question.tool_call_id, "call-canonical-tool");
        assert_eq!(persisted_question.tool_name, "canonical-tool");

        persistence.release.notify_one();
        let session = apply.await.unwrap();
        let pending = session.pending_question.expect("runtime pending question");
        assert_eq!(pending.tool_call_id, "call-canonical-tool");
        assert_eq!(pending.tool_name, "canonical-tool");

        let clarification =
            tokio::time::timeout(std::time::Duration::from_secs(5), event_rx.recv())
                .await
                .expect("clarification event should arrive after persistence")
                .expect("clarification channel should stay open");
        assert!(matches!(
            clarification,
            AgentEvent::NeedClarification {
                tool_call_id: Some(ref id),
                tool_name: Some(ref name),
                ..
            } if id == "call-canonical-tool" && name == "canonical-tool"
        ));
    }

    #[tokio::test(start_paused = true)]
    async fn telemetry_timeout_before_tool_start_has_no_dispatch_span() {
        let trace = bamboo_infrastructure::telemetry::test_support::TraceTest::default();
        let executor = Arc::new(NameRecordingExecutor::new(&["probe"]));
        let tools: Arc<dyn ToolExecutor> = executor.clone();
        let callable =
            effective_callable_set(&["probe"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
        let call = probe_call("probe");
        let (event_tx, mut event_rx) = mpsc::channel(1);
        event_tx
            .try_send(AgentEvent::Token {
                content: "occupied".into(),
            })
            .unwrap();
        let result = trace
            .scope(bamboo_infrastructure::telemetry::with_timeout(
                std::time::Duration::from_secs(1),
                execute_without_hooks(&callable, &tools, &call, &event_tx),
            ))
            .await;
        assert!(result.is_err());
        assert!(executor.entered().is_empty());
        assert!(trace.spans().is_empty());
        assert!(matches!(
            event_rx.try_recv().unwrap(),
            AgentEvent::Token { .. }
        ));
        assert!(event_rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn telemetry_records_actual_tool_errors_without_payloads() {
        struct ErrorExecutor(bool);
        #[async_trait]
        impl ToolExecutor for ErrorExecutor {
            async fn execute(&self, _: &ToolCall) -> Result<ToolResult, ToolError> {
                if self.0 {
                    Err(ToolError::Execution(
                        "PRIVATE_EXECUTOR_ERROR /Users/private".into(),
                    ))
                } else {
                    Ok(ToolResult::text(
                        false,
                        "PRIVATE_TOOL_OUTPUT /Users/private",
                    ))
                }
            }
            fn list_tools(&self) -> Vec<ToolSchema> {
                vec![tool_schema("probe")]
            }
        }
        for error_result in [false, true] {
            let trace = bamboo_infrastructure::telemetry::test_support::TraceTest::default();
            let tools: Arc<dyn ToolExecutor> = Arc::new(ErrorExecutor(error_result));
            let callable =
                effective_callable_set(&["probe"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
            let (event_tx, _event_rx) = mpsc::channel(16);
            let outcome = trace
                .scope(execute_without_hooks(
                    &callable,
                    &tools,
                    &probe_call("probe"),
                    &event_tx,
                ))
                .await;
            assert!(outcome.result.is_err() || !outcome.result.as_ref().unwrap().success);
            let spans = trace.spans();
            assert_eq!(spans.len(), 1);
            assert_eq!(spans[0].name, "execute_tool probe");
            assert!(spans[0]
                .attributes
                .iter()
                .any(|kv| kv.key.as_str() == "error.type" && kv.value.to_string() == "tool_error"));
            assert!(!format!("{spans:?}").contains("PRIVATE_"));
            assert!(!format!("{spans:?}").contains("/Users/"));
        }
    }

    #[tokio::test]
    async fn before_tool_hook_denies_without_dispatching_executor() {
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(DenyToolHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let tools = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let tool_call = ToolCall {
            id: "call-probe".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "probe".to_string(),
                arguments: serde_json::json!({"value": 7}).to_string(),
            },
        };
        let mut session = Session::new("hook-deny-session", "model");
        let session_flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime_state = AgentRuntimeState::new(&session.id);

        let trace = bamboo_infrastructure::telemetry::test_support::TraceTest::default();
        let outcome = trace
            .scope(execute_tool_call_only(ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: None,
                executing_supervisor: None,
                tool_call: &tool_call,
                event_tx: &event_tx,
                metrics_collector: None,
                session_id: "hook-deny-session",
                root_orchestration_only: false,
                root_session_id: "hook-deny-session",
                round_id: "round-1",
                round: 0,
                tools: &(tools.clone() as Arc<dyn ToolExecutor>),
                config: &config,
                hook_session: Some(&mut session),
                hook_runtime_state: Some(&mut runtime_state),
                session_flags,
                available_tool_schemas: &[],
            }))
            .await
            .expect("deny is a tool outcome, not a runner error");

        assert!(matches!(outcome.result, Err(ref error) if error.contains("policy hook blocked")));
        assert!(!tools.0.load(Ordering::SeqCst));
        assert_eq!(runtime_state.checkpoints.len(), 1);
        let events: Vec<_> = std::iter::from_fn(|| event_rx.try_recv().ok()).collect();
        assert!(events.iter().any(|event| matches!(
            event,
            AgentEvent::HookLifecycle { hook_name, decision: HookResult::Deny { .. }, .. }
                if hook_name == "deny_probe"
        )));
        assert!(
            trace.spans().is_empty(),
            "denied before dispatch must not fabricate tool spans"
        );
    }

    #[tokio::test]
    async fn configured_shell_hook_denies_bash_and_persists_synthetic_result() {
        let lifecycle_config = LifecycleHooksConfig {
            enabled: true,
            pre_tool_use: vec![LifecycleHookGroup {
                enabled: true,
                matcher: Some("^bash$".to_string()),
                hooks: vec![LifecycleHookHandler::command(
                    "printf 'configured bash denial' >&2; exit 2",
                    1_000,
                )],
            }],
            ..LifecycleHooksConfig::default()
        };
        let runner =
            crate::runtime::hooks::HookRunner::new().with_lifecycle_config(&lifecycle_config, None);
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let concrete_tools = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let tools: Arc<dyn ToolExecutor> = concrete_tools.clone();
        let (event_tx, _event_rx) = mpsc::channel(16);
        let tool_call = probe_call("bash");
        let workspace = tempfile::tempdir().unwrap();
        let mut session = Session::new("configured-hook-deny", "model");
        session.workspace = Some(workspace.path().to_string_lossy().into_owned());
        let session_flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime_state = AgentRuntimeState::new(&session.id);

        let outcome = execute_tool_call_only(ToolExecutionOnlyContext {
            vision_support: true,
            output_cap: None,
            executing_supervisor: None,
            tool_call: &tool_call,
            event_tx: &event_tx,
            metrics_collector: None,
            session_id: "configured-hook-deny",
            root_orchestration_only: false,
            root_session_id: "configured-hook-deny",
            round_id: "round-1",
            round: 0,
            tools: &tools,
            config: &config,
            hook_session: Some(&mut session),
            hook_runtime_state: Some(&mut runtime_state),
            session_flags,
            available_tool_schemas: &[],
        })
        .await
        .expect("hook denial is represented as a synthetic tool error");

        assert!(!concrete_tools.0.load(Ordering::SeqCst));
        apply_test_outcome(
            &config,
            &tools,
            &tool_call,
            &mut session,
            &event_tx,
            outcome,
        )
        .await
        .unwrap();
        let tool_message = session
            .messages
            .iter()
            .find(|message| message.tool_call_id.as_deref() == Some(&tool_call.id))
            .expect("synthetic denial must be appended as a tool result");
        assert!(tool_message.content.contains("configured bash denial"));
    }

    #[tokio::test]
    async fn allow_hook_skips_exact_configured_ask_in_engine_dispatch() {
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(AllowToolHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let workspace = tempfile::tempdir().unwrap();
        let path = workspace.path().join("engine-hook-allowed.txt");
        let permission_config = Arc::new(bamboo_tools::permission::PermissionConfig::new());
        permission_config
            .set_ask_rules([format!("Write({}/**)", workspace.path().to_string_lossy())]);
        let checker = Arc::new(bamboo_tools::permission::ConfigPermissionChecker::new(
            permission_config,
        ));
        let tools: Arc<dyn ToolExecutor> = Arc::new(
            bamboo_tools::BuiltinToolExecutorBuilder::new()
                .with_tool(bamboo_tools::WriteTool::new())
                .unwrap()
                .with_permission_checker(checker)
                .build(),
        );
        let (event_tx, _event_rx) = mpsc::channel(16);
        let tool_call = ToolCall {
            id: "call-write-allow".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "Write".to_string(),
                arguments: serde_json::json!({
                    "file_path": path.to_string_lossy(),
                    "content": "allowed"
                })
                .to_string(),
            },
        };
        let mut session = Session::new("hook-allow-engine", "model");
        session.workspace = Some(workspace.path().to_string_lossy().into_owned());
        let session_flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime_state = AgentRuntimeState::new(&session.id);

        let outcome = execute_tool_call_only(ToolExecutionOnlyContext {
            vision_support: true,
            output_cap: None,
            executing_supervisor: None,
            tool_call: &tool_call,
            event_tx: &event_tx,
            metrics_collector: None,
            session_id: "hook-allow-engine",
            root_orchestration_only: false,
            root_session_id: "hook-allow-engine",
            round_id: "round-1",
            round: 0,
            tools: &tools,
            config: &config,
            hook_session: Some(&mut session),
            hook_runtime_state: Some(&mut runtime_state),
            session_flags,
            available_tool_schemas: &[],
        })
        .await
        .unwrap();

        assert!(outcome.result.is_ok());
        assert_eq!(tokio::fs::read_to_string(path).await.unwrap(), "allowed");
    }

    #[tokio::test]
    async fn ask_hook_routes_to_parent_proxy_and_executes_only_after_approval() {
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(AskToolHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let tools = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let tool_executor: Arc<dyn ToolExecutor> = tools.clone();
        let reviewer = Arc::new(RecordingParentReviewer {
            seen: AtomicBool::new(false),
            approve: true,
        });
        let reviewer_proxy: Arc<dyn bamboo_tools::ApprovalProxy> = reviewer.clone();
        let (event_tx, _event_rx) = mpsc::channel(16);
        let tool_call = ToolCall {
            id: "call-probe".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "probe".to_string(),
                arguments: serde_json::json!({"value": 7}).to_string(),
            },
        };
        let mut session = Session::new("hook-ask-session", "model");
        let mut runtime_state = AgentRuntimeState::new(&session.id);
        runtime_state.bypass_permissions = true;
        session.agent_runtime_state = Some(runtime_state.clone());
        let session_flags = ToolExecutionSessionFlags::from_session(&session);

        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy),
            execute_tool_call_only(ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: None,
                executing_supervisor: None,
                tool_call: &tool_call,
                event_tx: &event_tx,
                metrics_collector: None,
                session_id: "hook-ask-session",
                root_orchestration_only: false,
                root_session_id: "hook-ask-session",
                round_id: "round-1",
                round: 0,
                tools: &tool_executor,
                config: &config,
                hook_session: Some(&mut session),
                hook_runtime_state: Some(&mut runtime_state),
                session_flags,
                available_tool_schemas: &[],
            }),
        )
        .await
        .expect("approved parent review should continue dispatch");

        assert!(outcome.result.is_ok());
        assert!(reviewer.seen.load(Ordering::SeqCst));
        assert!(tools.0.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn hook_ask_hides_focused_browser_resource_and_fails_closed_on_check_error() {
        let config = AgentLoopConfig::default();
        let session = Session::new("browser-hook-ask", "model");
        let runtime_state = AgentRuntimeState::new(&session.id);
        let reviewer = Arc::new(BrowserApprovalRecorder::default());
        let reviewer_proxy: Arc<dyn bamboo_tools::ApprovalProxy> = reviewer.clone();
        let key_args = serde_json::json!({
            "action":"key",
            "key":"private-key",
            "expected_epoch":17,
        });
        let key_call = ToolCall {
            id: "focused-key".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "browser".to_string(),
                arguments: key_args.to_string(),
            },
        };
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy.clone()),
            hook_ask_outcome(
                &key_call,
                "browser",
                &config,
                &session,
                &runtime_state,
                &key_args,
            ),
        )
        .await
        .expect("denied parent review returns a tool outcome");
        assert!(outcome.result.is_err());
        let asks = reviewer.0.lock().expect("browser approval record lock");
        assert_eq!(asks.len(), 1);
        assert_eq!(asks[0].resource, "[redacted]");
        let request = asks[0]
            .permission_request
            .as_ref()
            .expect("typed review request");
        assert_eq!(request.resource, "[redacted]");
        assert!(request.suggested_matchers.is_empty());
        assert!(!format!("{:?}", asks[0]).contains("private-key"));
        drop(asks);

        let eval_args = serde_json::json!({
            "code":"document.title = 'private-source'",
            "expected_url":"https://example.com/?token=private-query",
            "expected_epoch":17,
        });
        let eval_call = ToolCall {
            id: "browser-eval".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "browser_eval".to_string(),
                arguments: eval_args.to_string(),
            },
        };
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy.clone()),
            hook_ask_outcome(
                &eval_call,
                "browser_eval",
                &config,
                &session,
                &runtime_state,
                &eval_args,
            ),
        )
        .await
        .expect("denied eval review returns a tool outcome");
        assert!(outcome.result.is_err());
        let asks = reviewer.0.lock().expect("browser approval record lock");
        assert_eq!(asks.len(), 2);
        assert_eq!(asks[1].resource, "[redacted]");
        let eval_request = asks[1].permission_request.as_ref().unwrap();
        assert_eq!(eval_request.resource, "[redacted]");
        assert!(eval_request.suggested_matchers.is_empty());
        for secret in ["private-source", "private-query", "browser_eval:17:"] {
            assert!(!format!("{:?}", asks[1]).contains(secret));
        }
        drop(asks);

        let invalid_type_args = serde_json::json!({
            "action":"type",
            "text":"private browser input",
            "expected_epoch":"invalid",
        });
        let invalid_type_call = ToolCall {
            id: "focused-type-invalid".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "browser".to_string(),
                arguments: invalid_type_args.to_string(),
            },
        };
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy.clone()),
            hook_ask_outcome(
                &invalid_type_call,
                "browser",
                &config,
                &session,
                &runtime_state,
                &invalid_type_args,
            ),
        )
        .await
        .expect("invalid focused request fails closed");
        assert!(
            matches!(outcome.result, Err(ref error) if error == "Focused browser input permission check failed")
        );
        assert_eq!(
            reviewer
                .0
                .lock()
                .expect("browser approval record lock")
                .len(),
            2
        );

        // A namespaced model call resolves to canonical `browser` before hook
        // Ask. Even malformed actions with private-looking fields must not
        // fall back to a raw-arguments approval resource.
        let execution_name = "browser";
        for malformed_args in [
            serde_json::json!({
                "action":"select_options",
                "selector":"select[data-private='account']",
                "values":["private-option-value"],
            }),
            serde_json::json!({
                "action":null,
                "selector":"select[data-private='account']",
                "values":["private-option-value"],
            }),
        ] {
            let malformed_call = ToolCall {
                id: "select-hook-ask-malformed".to_string(),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: "default::browser".to_string(),
                    arguments: malformed_args.to_string(),
                },
            };
            let outcome = bamboo_tools::with_approval_proxy(
                Some(reviewer_proxy.clone()),
                hook_ask_outcome(
                    &malformed_call,
                    &execution_name,
                    &config,
                    &session,
                    &runtime_state,
                    &malformed_args,
                ),
            )
            .await
            .expect("malformed browser action fails closed");
            assert!(matches!(
                outcome.result,
                Err(ref error) if error == "Browser permission check failed"
            ));
            assert_eq!(
                reviewer
                    .0
                    .lock()
                    .expect("browser approval record lock")
                    .len(),
                2
            );
        }

        let read_only_args = serde_json::json!({
            "action":"snapshot",
            "selector":"select[data-private='account']",
            "values":["private-option-value"],
        });
        let read_only_call = ToolCall {
            id: "browser-hook-ask-read-only".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "default::browser".to_string(),
                arguments: read_only_args.to_string(),
            },
        };
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy),
            hook_ask_outcome(
                &read_only_call,
                &execution_name,
                &config,
                &session,
                &runtime_state,
                &read_only_args,
            ),
        )
        .await
        .expect("read-only browser hook Ask reaches parent");
        assert!(outcome.result.is_err());
        let asks = reviewer.0.lock().expect("browser approval record lock");
        assert_eq!(asks.len(), 3);
        assert_eq!(asks[2].resource, "[redacted]");
        let request = asks[2]
            .permission_request
            .as_ref()
            .expect("typed read-only review request");
        assert_eq!(request.resource, "[redacted]");
        assert!(request.suggested_matchers.is_empty());
        for private in ["private-option-value", "data-private"] {
            assert!(!format!("{:?}", asks[2]).contains(private));
        }
    }

    #[test]
    fn namespaced_browser_select_hook_ask_redacts_parent_request() {
        let data_dir = tempfile::tempdir().expect("isolated Bamboo data dir");
        let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
            .arg("namespaced_browser_select_hook_ask_child")
            .env("BAMBOO_DATA_DIR", data_dir.path())
            .env_remove("BAMBOO_CONFIG_ENCRYPTION_KEY")
            .env("BAMBOO_SELECT_HOOK_ASK_TEST", "1")
            .output()
            .expect("run hook Ask child test");
        assert!(output.status.success(), "isolated hook Ask test failed");
    }

    #[test]
    fn browser_download_hook_ask_redacts_parent_request() {
        let data_dir = tempfile::tempdir().expect("isolated Bamboo data dir");
        let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
            .arg("browser_download_hook_ask_child")
            .env("BAMBOO_DATA_DIR", data_dir.path())
            .env_remove("BAMBOO_CONFIG_ENCRYPTION_KEY")
            .env("BAMBOO_DOWNLOAD_HOOK_ASK_TEST", "1")
            .output()
            .expect("run download hook Ask child test");
        assert!(output.status.success(), "isolated hook Ask test failed");
    }

    #[tokio::test]
    async fn browser_download_hook_ask_child() {
        if std::env::var_os("BAMBOO_DOWNLOAD_HOOK_ASK_TEST").is_none() {
            return;
        }
        let config = AgentLoopConfig::default();
        let session = Session::new("browser-download-hook-ask", "model");
        let runtime_state = AgentRuntimeState::new(&session.id);
        let reviewer = Arc::new(BrowserApprovalRecorder::default());
        let reviewer_proxy: Arc<dyn bamboo_tools::ApprovalProxy> = reviewer.clone();
        let callable_set =
            effective_callable_set(&["browser"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
        let secret = "a[data-private='account']";

        for (index, name) in ["browser", "default::browser", "private-namespace::browser"]
            .into_iter()
            .enumerate()
        {
            let args = serde_json::json!({
                "action":"download", "selector":secret, "expected_epoch":17,
            });
            let call = ToolCall {
                id: format!("download-hook-ask-{index}"),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: name.to_string(),
                    arguments: args.to_string(),
                },
            };
            let execution_name = if name == "private-namespace::browser" {
                // Model aliases normally resolve before hook Ask; exercise a
                // private namespace reaching the same canonical execution.
                "browser".to_string()
            } else {
                callable_set
                    .resolve_callable_reference(&call.function.name)
                    .expect("browser resolves to the registered tool")
            };
            assert_eq!(execution_name, "browser");
            let outcome = bamboo_tools::with_approval_proxy(
                Some(reviewer_proxy.clone()),
                hook_ask_outcome(
                    &call,
                    &execution_name,
                    &config,
                    &session,
                    &runtime_state,
                    &args,
                ),
            )
            .await
            .expect("parent review returns an outcome");
            assert!(outcome.result.is_err());
        }

        let asks = reviewer.0.lock().expect("browser approval record lock");
        assert_eq!(asks.len(), 3);
        for ask in asks.iter() {
            assert_eq!(ask.tool_name, "browser");
            assert_eq!(ask.resource, "[redacted]");
            let request = ask.permission_request.as_ref().unwrap();
            assert_eq!(request.tool_name, "browser");
            assert_eq!(request.resource, "[redacted]");
            assert_eq!(
                request.operation_summary,
                "Download from selected browser element"
            );
            assert!(request.suggested_matchers.is_empty());
            let display = format!("{ask:?}");
            assert!(!display.contains(secret));
            assert!(!display.contains("download:css:"));
            assert!(!display.contains("private-namespace"));
        }
        drop(asks);

        let malformed = serde_json::json!({
            "action":"download", "selector":secret, "expected_epoch":17,
            "url":"https://example.test/private-query",
        });
        let call = ToolCall {
            id: "download-hook-ask-malformed".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "default::browser".to_string(),
                arguments: malformed.to_string(),
            },
        };
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy),
            hook_ask_outcome(
                &call,
                "browser",
                &config,
                &session,
                &runtime_state,
                &malformed,
            ),
        )
        .await
        .expect("malformed download fails closed");
        assert!(matches!(outcome.result,
            Err(ref error) if error == "Browser download permission check failed"));
        assert_eq!(
            reviewer
                .0
                .lock()
                .expect("browser approval record lock")
                .len(),
            3
        );
    }

    #[tokio::test]
    async fn namespaced_browser_select_hook_ask_child() {
        if std::env::var_os("BAMBOO_SELECT_HOOK_ASK_TEST").is_none() {
            return;
        }
        let config = AgentLoopConfig::default();
        let session = Session::new("browser-select-hook-ask", "model");
        let runtime_state = AgentRuntimeState::new(&session.id);
        let reviewer = Arc::new(BrowserApprovalRecorder::default());
        let reviewer_proxy: Arc<dyn bamboo_tools::ApprovalProxy> = reviewer.clone();
        let args = serde_json::json!({
            "action":"select_option",
            "selector":"select[data-private='account']",
            "values":["private-option-value"],
            "expected_epoch":17,
        });
        let call = ToolCall {
            id: "select-hook-ask".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "default::browser".to_string(),
                arguments: args.to_string(),
            },
        };
        let callable_set =
            effective_callable_set(&["browser"], CapabilityLoadingMode::LegacyFullCatalog, &[]);
        let execution_name = callable_set
            .resolve_callable_reference(&call.function.name)
            .expect("namespaced browser resolves to the registered tool");
        assert_eq!(execution_name, "browser");
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy.clone()),
            hook_ask_outcome(
                &call,
                &execution_name,
                &config,
                &session,
                &runtime_state,
                &args,
            ),
        )
        .await
        .expect("parent review returns an outcome");
        assert!(outcome.result.is_err());
        let asks = reviewer.0.lock().expect("browser approval record lock");
        assert_eq!(asks.len(), 1);
        assert_eq!(asks[0].tool_name, "default::browser");
        assert_eq!(asks[0].resource, "[redacted]");
        let request = asks[0]
            .permission_request
            .as_ref()
            .expect("typed review request");
        assert_eq!(
            request.permission_type,
            bamboo_tools::permission::PermissionType::BrowserInteraction
        );
        assert_eq!(request.resource, "[redacted]");
        assert_eq!(request.operation_summary, "Select native browser options");
        assert!(request.suggested_matchers.is_empty());
        for private in ["private-option-value", "data-private", "options:"] {
            assert!(!format!("{:?}", asks[0]).contains(private));
        }
        drop(asks);

        let invalid_args = serde_json::json!({
            "action":"select_option",
            "selector":"select[data-private='account']",
            "values":["private-option-value"],
            "expected_epoch":"invalid",
        });
        let invalid_call = ToolCall {
            id: "select-hook-ask-invalid".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "default::browser".to_string(),
                arguments: invalid_args.to_string(),
            },
        };
        let outcome = bamboo_tools::with_approval_proxy(
            Some(reviewer_proxy),
            hook_ask_outcome(
                &invalid_call,
                &execution_name,
                &config,
                &session,
                &runtime_state,
                &invalid_args,
            ),
        )
        .await
        .expect("invalid request fails closed");
        assert!(matches!(
            outcome.result,
            Err(ref error) if error == "Browser selection permission check failed"
        ));
        assert_eq!(
            reviewer
                .0
                .lock()
                .expect("browser approval record lock")
                .len(),
            1
        );
    }

    #[test]
    fn malformed_browser_tool_warning_hides_raw_preview_and_repair_message() {
        for (tool_name, raw) in [
            (
                "browser",
                r#"{"action":"type","text":"private browser input"#,
            ),
            ("browser_eval", r#"{"code":"private page source"#),
            (
                "session_message",
                r#"{"action":"send","message":"private peer message"#,
            ),
            (
                "SESSION_MESSAGE",
                r#"{"action":"reply","message":"private peer reply"#,
            ),
            (
                "work_update",
                r#"{"operations":[{"objective":"private work instructions"#,
            ),
        ] {
            let (_, warning) = parse_tool_args_best_effort(raw);
            let warning = warning.expect("malformed JSON warning");
            assert!(warning.contains("private"));
            let (preview, logged_warning) = parse_warning_log_details(tool_name, raw, &warning);
            assert_eq!(preview, "[redacted]");
            assert_eq!(logged_warning, "[redacted]");
            let (ordinary_preview, ordinary_warning) =
                parse_warning_log_details("probe", raw, &warning);
            assert!(ordinary_preview.contains("private"));
            assert_eq!(ordinary_warning, warning);
        }
    }

    #[test]
    fn file_input_tool_start_is_display_only_and_never_carries_file_bytes() {
        let args = serde_json::json!({
            "action":"set_file_input","selector":"#upload","filename":"private.txt",
            "data_base64":"cHJpdmF0ZSBieXRlcw==",
        });
        let original = args.clone();
        assert_eq!(
            tool_start_arguments_for_display("browser", &args),
            serde_json::json!({"action":"set_file_input","file":"[redacted]"})
        );
        assert_eq!(args, original);
        assert_eq!(tool_start_arguments_for_display("other", &args), args);
        assert_eq!(tool_start_name_for_display("default::browser"), "browser");
    }

    #[test]
    fn download_tool_start_is_display_only_and_never_carries_selector_or_extras() {
        let args = serde_json::json!({
            "action":"download","selector":"a[data-secret='private']",
            "expected_epoch":17,"url":"https://private.example/file",
            "nested":{"filename":"private.txt"},
        });
        let original = args.clone();
        let display = serde_json::json!({"action":"download","expected_epoch":17});
        assert_eq!(tool_start_arguments_for_display("browser", &args), display);
        assert_eq!(
            tool_start_arguments_for_display("default::browser", &args),
            display
        );
        let mut poisoned = args.clone();
        poisoned["data_base64"] = serde_json::json!("private-file-bytes");
        assert_eq!(
            tool_start_arguments_for_display("browser", &poisoned),
            display
        );
        assert_eq!(args, original);
        assert_eq!(tool_start_arguments_for_display("other", &args), args);
        assert_eq!(
            tool_start_name_for_display("private-selector::browser"),
            "browser"
        );
        assert_eq!(tool_start_name_for_display("other"), "other");
    }

    #[tokio::test]
    async fn post_tool_feedback_is_appended_to_persisted_tool_result() {
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(PostFeedbackHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let tools: Arc<dyn ToolExecutor> = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let (event_tx, _event_rx) = mpsc::channel(16);
        let tool_call = probe_call("probe");
        let mut session = Session::new("post-feedback", "model");
        let outcome = ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Ok(ToolResult::text(true, "raw output")),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: true,
            managed_running_violation: false,
            tool_duration: std::time::Duration::from_millis(7),
        };

        apply_test_outcome(
            &config,
            &tools,
            &tool_call,
            &mut session,
            &event_tx,
            outcome,
        )
        .await
        .unwrap();
        let persisted = serde_json::to_vec(&session).unwrap();
        let restored: Session = serde_json::from_slice(&persisted).unwrap();
        let content = &restored
            .messages
            .iter()
            .find(|message| message.tool_call_id.as_deref() == Some(&tool_call.id))
            .expect("tool result must survive persistence")
            .content;
        assert!(content.contains("raw output"));
        assert!(content.contains("lint: replace the generated token"));
        assert!(content.contains("Blocked by PostToolUse hook"));
        assert!(content.contains("generated output violates policy"));
    }

    #[tokio::test]
    async fn post_tool_feedback_runs_for_executor_errors() {
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(ErrorPostFeedbackHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let tools: Arc<dyn ToolExecutor> = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let (event_tx, _event_rx) = mpsc::channel(16);
        let tool_call = probe_call("probe");
        let mut session = Session::new("post-error-feedback", "model");
        let outcome = ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Err("executor exploded".to_string()),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: true,
            managed_running_violation: false,
            tool_duration: std::time::Duration::from_millis(3),
        };

        apply_test_outcome(
            &config,
            &tools,
            &tool_call,
            &mut session,
            &event_tx,
            outcome,
        )
        .await
        .unwrap();
        let content = &session
            .messages
            .iter()
            .find(|message| message.tool_call_id.as_deref() == Some(&tool_call.id))
            .expect("error tool result must be appended")
            .content;
        assert!(content.contains("executor exploded"));
        assert!(content.contains("error diagnostic from PostToolUse"));
    }

    #[tokio::test]
    async fn post_tool_hook_skips_running_and_needs_human_outcomes() {
        let calls = Arc::new(AtomicUsize::new(0));
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(CountingPostHook(calls.clone())));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            ..Default::default()
        };
        let (event_tx, _event_rx) = mpsc::channel(32);
        let tool_call = probe_call("probe");

        for (session_id, executor) in [
            (
                "post-skip-running",
                NonTerminalExecutor(NonTerminalOutcome::Running),
            ),
            (
                "post-skip-needs-human",
                NonTerminalExecutor(NonTerminalOutcome::NeedsHuman),
            ),
        ] {
            let tools: Arc<dyn ToolExecutor> = Arc::new(executor);
            let mut session = Session::new(session_id, "model");
            let session_flags = ToolExecutionSessionFlags::from_session(&session);
            let outcome = execute_tool_call_only(ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: Some(97),
                executing_supervisor: None,
                tool_call: &tool_call,
                event_tx: &event_tx,
                metrics_collector: None,
                session_id,
                root_session_id: session_id,
                root_orchestration_only: false,
                round_id: "round-1",
                round: 0,
                tools: &tools,
                config: &config,
                hook_session: None,
                hook_runtime_state: None,
                session_flags,
                available_tool_schemas: &[],
            })
            .await
            .unwrap();
            assert_eq!(outcome.output_cap, Some(Some(97)));
            assert!(!outcome.post_tool_hook_eligible);
            apply_test_outcome(
                &config,
                &tools,
                &tool_call,
                &mut session,
                &event_tx,
                outcome,
            )
            .await
            .unwrap();
        }

        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn ask_hook_without_parent_proxy_fails_closed_without_manual_prompt() {
        let mut runner = crate::runtime::hooks::HookRunner::new();
        runner.register(Arc::new(AskToolHook));
        let config = AgentLoopConfig {
            hook_runner: Arc::new(runner),
            approval_delegate: Some(Arc::new(PanicLegacyApprovalDelegate)),
            ..Default::default()
        };
        let tools = Arc::new(RecordingExecutor(AtomicBool::new(false)));
        let tool_executor: Arc<dyn ToolExecutor> = tools.clone();
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let tool_call = ToolCall {
            id: "call-probe".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "probe".to_string(),
                arguments: serde_json::json!({"value": 7}).to_string(),
            },
        };
        let mut session = Session::new("hook-ask-no-parent", "model");
        session.parent_session_id = Some("parent-with-legacy-delegate".to_string());
        let session_flags = ToolExecutionSessionFlags::from_session(&session);
        let mut runtime_state = AgentRuntimeState::new(&session.id);

        let outcome = execute_tool_call_only(ToolExecutionOnlyContext {
            vision_support: true,
            output_cap: None,
            executing_supervisor: None,
            tool_call: &tool_call,
            event_tx: &event_tx,
            metrics_collector: None,
            session_id: "hook-ask-no-parent",
            root_orchestration_only: false,
            root_session_id: "hook-ask-no-parent",
            round_id: "round-1",
            round: 0,
            tools: &tool_executor,
            config: &config,
            hook_session: Some(&mut session),
            hook_runtime_state: Some(&mut runtime_state),
            session_flags,
            available_tool_schemas: &[],
        })
        .await
        .expect("missing parent is represented as a denied tool outcome");

        assert!(matches!(
            outcome.result,
            Err(ref error) if error.contains("no parent-agent reviewer")
        ));
        assert!(!tools.0.load(Ordering::SeqCst));
        assert!(
            !std::iter::from_fn(|| event_rx.try_recv().ok()).any(|event| matches!(
                event,
                AgentEvent::NeedClarification { .. } | AgentEvent::ChildApprovalRequested { .. }
            ))
        );
    }

    struct WaitingCapHook {
        decision: HookResult,
        entered: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    }
    #[async_trait]
    impl AgentHook for WaitingCapHook {
        fn point(&self) -> AgentHookPoint {
            AgentHookPoint::BeforeToolExecution
        }
        async fn run(
            &self,
            _: AgentHookPoint,
            payload: &HookPayload,
            session: &Session,
        ) -> HookResult {
            let HookPayload::ToolExecution { tool_call_id, .. } = payload else {
                panic!("tool seam")
            };
            let mut ctx = bamboo_agent_core::tools::ToolCtx::none(tool_call_id.clone());
            ctx.session_id = Some(session.id.clone().into());
            assert_eq!(
                bamboo_agent_core::tools::observed_tool_output_cap(&ctx),
                None,
                "BeforeTool is outside the executor observation scope"
            );
            self.entered.notify_one();
            self.release.notified().await;
            self.decision.clone()
        }
    }

    async fn execute_cap_hook_call(
        session: &mut Session,
        tools: &Arc<dyn ToolExecutor>,
        config: &AgentLoopConfig,
        call: &ToolCall,
    ) -> Result<ToolExecutionOutcome, AgentError> {
        let (event_tx, _event_rx) = mpsc::channel(128);
        let flags = ToolExecutionSessionFlags::from_session(session);
        let sid = session.id.clone();
        let mut runtime = session
            .agent_runtime_state
            .clone()
            .unwrap_or_else(|| AgentRuntimeState::new(&sid));
        let callable = effective_callable_set(
            &[call.function.name.as_str()],
            CapabilityLoadingMode::LegacyFullCatalog,
            &[],
        );
        execute_model_requested_tool_call_only(
            &callable,
            ToolExecutionOnlyContext {
                vision_support: true,
                output_cap: None,
                executing_supervisor: None,
                tool_call: call,
                event_tx: &event_tx,
                metrics_collector: None,
                session_id: &sid,
                root_session_id: &sid,
                root_orchestration_only: false,
                round_id: "cap-hook",
                round: 0,
                tools,
                config,
                hook_session: Some(session),
                hook_runtime_state: Some(&mut runtime),
                session_flags: flags,
                available_tool_schemas: &[],
            },
        )
        .await
    }

    #[tokio::test]
    async fn scoped_cap_follows_real_continuing_native_hook_outcomes() {
        for cap in [None, Some(0), Some(53)] {
            for decision in [
                HookResult::Continue,
                HookResult::Allow,
                HookResult::Mutated,
                HookResult::InjectContext {
                    text: "cap-context".into(),
                },
                HookResult::WithContext {
                    result: Box::new(HookResult::Allow),
                    text: "cap-control".into(),
                },
            ] {
                let mut session = Session::new("cap-hook-session", "model");
                session.token_budget = cap.map(|n| bamboo_domain::TokenBudget {
                    max_tool_output_tokens: n,
                    ..Default::default()
                });
                let initial = serde_json::to_value(&session.token_budget).unwrap();
                let entered = Arc::new(tokio::sync::Notify::new());
                let release = Arc::new(tokio::sync::Notify::new());
                let mut runner = crate::runtime::hooks::HookRunner::new();
                runner.register(Arc::new(WaitingCapHook {
                    decision: decision.clone(),
                    entered: entered.clone(),
                    release: release.clone(),
                }));
                let config = AgentLoopConfig {
                    hook_runner: Arc::new(runner),
                    ..Default::default()
                };
                let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
                let tools: Arc<dyn ToolExecutor> = concrete.clone();
                let call = probe_call("probe");
                let outcome = {
                    let execution = execute_cap_hook_call(&mut session, &tools, &config, &call);
                    tokio::pin!(execution);
                    tokio::select! {
                        result = &mut execution => panic!("hook must wait: {}", result.is_ok()),
                        _ = entered.notified() => {}
                    }
                    assert!(concrete.exact_dispatches.lock().unwrap().is_empty());
                    release.notify_one();
                    execution.await.unwrap()
                };
                assert_eq!(outcome.output_cap, Some(cap));
                assert_eq!(*concrete.output_caps.lock().unwrap(), vec![cap]);
                assert_eq!(outcome.result.unwrap().result, "exact dispatch");
                assert_eq!(
                    serde_json::to_value(&session.token_budget).unwrap(),
                    initial
                );
                assert!(session.resolved_token_budget.is_none());
                if matches!(
                    decision,
                    HookResult::InjectContext { .. } | HookResult::WithContext { .. }
                ) {
                    assert!(session
                        .messages
                        .iter()
                        .any(|m| m.content.contains("cap-context")
                            || m.content.contains("cap-control")));
                }
            }
        }
    }

    #[tokio::test]
    async fn scoped_cap_is_absent_on_real_native_control_exit_and_cancel() {
        for decision in [
            HookResult::Deny {
                reason: "blocked cap".into(),
            },
            HookResult::Ask,
            HookResult::Suspend {
                reason: "park cap".into(),
            },
            HookResult::Abort {
                reason: "abort cap".into(),
            },
        ] {
            let mut session = Session::new("cap-hook-stop", "model");
            session.token_budget = Some(bamboo_domain::TokenBudget {
                max_tool_output_tokens: 83,
                ..Default::default()
            });
            let entered = Arc::new(tokio::sync::Notify::new());
            let release = Arc::new(tokio::sync::Notify::new());
            let mut runner = crate::runtime::hooks::HookRunner::new();
            runner.register(Arc::new(WaitingCapHook {
                decision,
                entered: entered.clone(),
                release: release.clone(),
            }));
            let config = AgentLoopConfig {
                hook_runner: Arc::new(runner),
                ..Default::default()
            };
            let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
            let tools: Arc<dyn ToolExecutor> = concrete.clone();
            let call = probe_call("probe");
            release.notify_one();
            if let Ok(outcome) = execute_cap_hook_call(&mut session, &tools, &config, &call).await {
                assert_eq!(outcome.output_cap, None);
                assert!(outcome.result.is_err());
            }
            assert!(concrete.output_caps.lock().unwrap().is_empty());
            let mut execution =
                Box::pin(execute_cap_hook_call(&mut session, &tools, &config, &call));
            tokio::select! { biased;
                _ = &mut execution => panic!("hook must block"),
                _ = std::future::ready(()) => {}
            }
            drop(execution);
            assert!(concrete.output_caps.lock().unwrap().is_empty());
        }
    }

    #[tokio::test]
    async fn scoped_cap_native_ask_continuation_is_distinct_from_returned_ask() {
        for approve in [false, true] {
            let mut runner = crate::runtime::hooks::HookRunner::new();
            runner.register(Arc::new(AskToolHook));
            let config = AgentLoopConfig {
                hook_runner: Arc::new(runner),
                ..Default::default()
            };
            let mut session = Session::new("cap-ask", "model");
            session.token_budget = Some(bamboo_domain::TokenBudget {
                max_tool_output_tokens: 4096,
                ..Default::default()
            });
            let mut state = AgentRuntimeState::new(&session.id);
            state.bypass_permissions = true;
            session.agent_runtime_state = Some(state);
            let concrete = Arc::new(ExactOwnerRecordingExecutor::default());
            let tools: Arc<dyn ToolExecutor> = concrete.clone();
            let reviewer = Arc::new(RecordingParentReviewer {
                seen: AtomicBool::new(false),
                approve,
            });
            let outcome = bamboo_tools::with_approval_proxy(
                Some(reviewer.clone()),
                execute_cap_hook_call(&mut session, &tools, &config, &probe_call("probe")),
            )
            .await
            .unwrap();
            assert!(reviewer.seen.load(Ordering::SeqCst));
            assert_eq!(outcome.output_cap, approve.then_some(Some(4096)));
            assert_eq!(outcome.result.is_ok(), approve);
            assert_eq!(
                *concrete.output_caps.lock().unwrap(),
                if approve { vec![Some(4096)] } else { vec![] }
            );
        }
    }
}