bamboo-tools 2026.9.19

Tool execution and integrations 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
use std::collections::BTreeMap;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

use async_trait::async_trait;
use bamboo_agent_core::tools::input_guard::{check_parsed_tool_input, check_raw_tool_input};
use bamboo_agent_core::{
    parse_tool_args_best_effort, Tool, ToolCall, ToolError, ToolExecutionContext, ToolExecutor,
    ToolOutcome, ToolResult, ToolSchema,
};
use bamboo_domain::{canonical_tool_name, resolve_tool_reference_name};

use crate::guide::{context::GuideBuildContext, EnhancedPromptBuilder, ToolGuide};
use crate::permission::{check_permissions, PermissionChecker, PermissionError};
use crate::tools::{
    BashInputTool, BashOutputTool, BashTool, ConclusionWithOptionsTool, EditTool,
    EnterPlanModeTool, ExitPlanModeTool, GetFileInfoTool, GlobTool, GrepTool, JsReplTool,
    KillShellTool, NotebookEditTool, ReadTool, RequestPermissionsTool, SessionNoteTool, SleepTool,
    TaskTool, ToolRegistry, UpdateGoalTool, WebFetchTool, WebSearchTool, WorkspaceTool, WriteTool,
};
use bamboo_llm::Config;
use bamboo_plugin_protocol::{
    FileChangedV1, NoopToolEventPublisher, ToolEventContextV1, ToolEventPublisher, ToolEventV1,
};
use tokio::sync::RwLock;

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 copy_legacy_arg_if_missing(
    args: &mut serde_json::Map<String, serde_json::Value>,
    from: &str,
    to: &str,
) {
    if args.contains_key(to) {
        return;
    }
    if let Some(value) = args.get(from).cloned() {
        args.insert(to.to_string(), value);
    }
}

fn normalize_legacy_builtin_args(
    raw_tool_name: &str,
    args: &mut serde_json::Map<String, serde_json::Value>,
) {
    match raw_tool_name {
        "read_file" | "write_file" | "Read" | "Write" | "apply_patch" => {
            copy_legacy_arg_if_missing(args, "path", "file_path");
        }
        "execute_command" | "Bash" => {
            copy_legacy_arg_if_missing(args, "cmd", "command");
        }
        "list_directory" | "Glob" => {
            let should_default_pattern = raw_tool_name == "list_directory"
                || args.contains_key("path")
                || args.contains_key("recursive");
            if should_default_pattern && !args.contains_key("pattern") {
                let recursive = args
                    .get("recursive")
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(false);
                let pattern = if recursive { "**/*" } else { "*" };
                args.insert(
                    "pattern".to_string(),
                    serde_json::Value::String(pattern.to_string()),
                );
            }
            args.remove("recursive");
        }
        _ => {}
    }
}

fn resolve_registered_tool_name(registry: &ToolRegistry, reference: &str) -> Option<String> {
    resolve_tool_reference_name(reference, |candidate| registry.contains(candidate))
}

/// Apply compatibility argument aliases only after the registry identity and
/// its framework-owned implementation provenance are resolved. Exact custom
/// tools whose names merely resemble a builtin or alias (for example an exact
/// `Read` or `apply_patch`) must receive their original arguments.
fn normalize_resolved_builtin_args(
    reference: &str,
    execution_name: &str,
    args: &mut serde_json::Value,
) {
    if !matches!(execution_name, "Read" | "Write" | "Edit" | "Bash" | "Glob") {
        return;
    }
    let unqualified = reference
        .trim()
        .rsplit("::")
        .next()
        .unwrap_or(reference)
        .trim();
    if let Some(args_obj) = args.as_object_mut() {
        normalize_legacy_builtin_args(unqualified, args_obj);
    }
}

/// Built-in tool executor that uses ToolRegistry for dynamic dispatch
pub struct BuiltinToolExecutor {
    registry: ToolRegistry,
    permission_checker: Option<Arc<dyn PermissionChecker>>,
    /// Framework-owned tool instances whose identity affects compatibility
    /// argument handling or file-change events. Arc identity prevents a custom
    /// same-name registry replacement from inheriting builtin provenance.
    framework_builtin_tools: BTreeMap<String, Arc<dyn Tool>>,
    tool_event_publisher: Arc<dyn ToolEventPublisher>,
}

impl BuiltinToolExecutor {
    fn default_tool_event_publisher() -> Arc<dyn ToolEventPublisher> {
        Arc::new(NoopToolEventPublisher)
    }

    /// Creates a new executor with all built-in tools registered
    pub fn new() -> Self {
        let registry = ToolRegistry::new();
        let framework_builtin_tools = Self::register_builtin_tools(&registry, None);
        Self {
            registry,
            permission_checker: None,
            framework_builtin_tools,
            tool_event_publisher: Self::default_tool_event_publisher(),
        }
    }

    /// Creates a new executor with a permission checker
    pub fn new_with_permissions(permission_checker: Arc<dyn PermissionChecker>) -> Self {
        let registry = ToolRegistry::new();
        let framework_builtin_tools = Self::register_builtin_tools(&registry, None);
        Self {
            registry,
            permission_checker: Some(permission_checker),
            framework_builtin_tools,
            tool_event_publisher: Self::default_tool_event_publisher(),
        }
    }

    /// Creates a new executor that can read the shared, hot-reloadable config.
    ///
    /// Use this when running inside the Bamboo server so tools (notably
    /// `http_request`) honor proxy settings from `config.json`.
    pub fn new_with_config(config: Arc<RwLock<Config>>) -> Self {
        let registry = ToolRegistry::new();
        let framework_builtin_tools = Self::register_builtin_tools(&registry, Some(config));
        Self {
            registry,
            permission_checker: None,
            framework_builtin_tools,
            tool_event_publisher: Self::default_tool_event_publisher(),
        }
    }

    /// Creates a new executor with both shared config and a permission checker.
    pub fn new_with_config_and_permissions(
        config: Arc<RwLock<Config>>,
        permission_checker: Arc<dyn PermissionChecker>,
    ) -> Self {
        let registry = ToolRegistry::new();
        let framework_builtin_tools = Self::register_builtin_tools(&registry, Some(config));
        Self {
            registry,
            permission_checker: Some(permission_checker),
            framework_builtin_tools,
            tool_event_publisher: Self::default_tool_event_publisher(),
        }
    }

    /// Creates a new executor from an existing registry
    pub fn with_registry(registry: ToolRegistry) -> Self {
        Self {
            registry,
            permission_checker: None,
            framework_builtin_tools: BTreeMap::new(),
            tool_event_publisher: Self::default_tool_event_publisher(),
        }
    }

    /// Creates a new executor from an existing registry and permission checker.
    ///
    /// This is the dependency-injection counterpart to
    /// [`new_with_permissions`](Self::new_with_permissions): callers that
    /// intentionally expose a selected/custom registry can keep the canonical
    /// permission gate instead of silently dropping it.
    pub fn with_registry_and_permissions(
        registry: ToolRegistry,
        permission_checker: Arc<dyn PermissionChecker>,
    ) -> Self {
        Self {
            registry,
            permission_checker: Some(permission_checker),
            framework_builtin_tools: BTreeMap::new(),
            tool_event_publisher: Self::default_tool_event_publisher(),
        }
    }

    /// Inject an instance-local, non-blocking tool-event publisher.
    pub fn with_tool_event_publisher(mut self, publisher: Arc<dyn ToolEventPublisher>) -> Self {
        self.tool_event_publisher = publisher;
        self
    }

    /// Returns a reference to the internal registry
    pub fn registry(&self) -> &ToolRegistry {
        &self.registry
    }

    fn pending_file_changed(
        &self,
        tool_name: &str,
        tool: &Arc<dyn Tool>,
        args: &serde_json::Value,
    ) -> Option<FileChangedV1> {
        let builtin = self.framework_builtin_tools.get(tool_name)?;
        if !Arc::ptr_eq(builtin, tool) {
            return None;
        }
        let path_field = match tool_name {
            "Write" | "Edit" => "file_path",
            "NotebookEdit" => "notebook_path",
            _ => return None,
        };
        let path = args.get(path_field)?.as_str()?.trim();
        FileChangedV1::bounded_from(path).ok()
    }

    fn publish_successful_file_change(
        &self,
        ctx: &ToolExecutionContext<'_>,
        tool_name: &str,
        data: FileChangedV1,
    ) {
        let Some(session_id) = ctx.session_id else {
            return;
        };
        let Some(root_session_id) = ctx.root_session_id else {
            return;
        };
        let Ok(context) = ToolEventContextV1::bounded_from(
            session_id,
            root_session_id,
            tool_name,
            ctx.tool_call_id,
        ) else {
            return;
        };
        let Ok(event) = ToolEventV1::file_changed(context, data) else {
            return;
        };

        // A buggy publisher must not unwind across the tool-result boundary.
        // Returned failures are deliberately ignored: delivery is best-effort.
        let publisher = self.tool_event_publisher.as_ref();
        let _ = catch_unwind(AssertUnwindSafe(|| publisher.try_publish(event)));
    }

    /// Registers all built-in tools to the given registry
    fn register_builtin_tools(
        registry: &ToolRegistry,
        config: Option<Arc<RwLock<Config>>>,
    ) -> BTreeMap<String, Arc<dyn Tool>> {
        let mut framework_tools = BTreeMap::new();
        let _ = config;
        // NOTE: apply_patch is now an alias for Edit – no separate registration.
        let _ = registry.register(ConclusionWithOptionsTool::new());
        if let Ok((name, tool)) = Self::register_tracked_builtin(registry, BashTool::new()) {
            framework_tools.insert(name, tool);
        }
        let _ = registry.register(BashInputTool::new());
        let _ = registry.register(BashOutputTool::new());
        if let Ok((name, tool)) = Self::register_tracked_builtin(registry, EditTool::new()) {
            framework_tools.insert(name, tool);
        }
        let _ = registry.register(EnterPlanModeTool::new());
        let _ = registry.register(ExitPlanModeTool::new());
        // NOTE: FileExists is now an alias for GetFileInfo – no separate registration.
        let _ = registry.register(GetFileInfoTool::new());
        if let Ok((name, tool)) = Self::register_tracked_builtin(registry, GlobTool::new()) {
            framework_tools.insert(name, tool);
        }
        let _ = registry.register(GrepTool::new());
        let _ = registry.register(UpdateGoalTool::new());
        let _ = registry.register(JsReplTool::new());
        let _ = registry.register(KillShellTool::new());
        let _ = registry.register(SessionNoteTool::new());
        if let Ok((name, tool)) = Self::register_tracked_builtin(registry, NotebookEditTool::new())
        {
            framework_tools.insert(name, tool);
        }
        if let Ok((name, tool)) = Self::register_tracked_builtin(registry, ReadTool::new()) {
            framework_tools.insert(name, tool);
        }
        let _ = registry.register(RequestPermissionsTool::new());
        let _ = registry.register(SleepTool::new());
        let _ = registry.register(TaskTool::new());
        let _ = registry.register(WebFetchTool::new());
        let _ = registry.register(WebSearchTool::new());
        // NOTE: GetCurrentDir + SetWorkspace are now aliases for Workspace.
        let _ = registry.register(WorkspaceTool::new());
        if let Ok((name, tool)) = Self::register_tracked_builtin(registry, WriteTool::new()) {
            framework_tools.insert(name, tool);
        }
        framework_tools
    }

    fn register_tracked_builtin<T: Tool + 'static>(
        registry: &ToolRegistry,
        tool: T,
    ) -> Result<(String, Arc<dyn Tool>), ToolError> {
        let name = tool.name().to_string();
        let tool: Arc<dyn Tool> = Arc::new(tool);
        registry
            .register_shared(tool.clone())
            .map_err(|error| ToolError::Execution(error.to_string()))?;
        Ok((name, tool))
    }

    fn is_framework_builtin_instance(&self, execution_name: &str, tool: &Arc<dyn Tool>) -> bool {
        self.framework_builtin_tools
            .get(execution_name)
            .is_some_and(|builtin| Arc::ptr_eq(builtin, tool))
    }

    fn normalize_registered_builtin_args(
        &self,
        reference: &str,
        execution_name: &str,
        tool: &Arc<dyn Tool>,
        args: &mut serde_json::Value,
    ) {
        if self.is_framework_builtin_instance(execution_name, tool) {
            normalize_resolved_builtin_args(reference, execution_name, args);
        }
    }

    /// Returns all built-in tool schemas
    pub fn tool_schemas() -> Vec<ToolSchema> {
        let registry = ToolRegistry::new();
        let _ = Self::register_builtin_tools(&registry, None);
        registry.list_tools()
    }

    /// Registers a custom tool to this executor
    pub fn register_tool<T: Tool + 'static>(&self, tool: T) -> Result<(), ToolError> {
        self.registry
            .register(tool)
            .map_err(|e| ToolError::Execution(e.to_string()))
    }

    /// Register a tool with its guide
    pub fn register_tool_with_guide<T, G>(&self, tool: T, guide: G) -> Result<(), ToolError>
    where
        T: Tool + 'static,
        G: ToolGuide + 'static,
    {
        self.registry
            .register_with_guide(tool, guide)
            .map_err(|e| ToolError::Execution(e.to_string()))
    }

    /// Get guide for a tool
    pub fn get_guide(&self, tool_name: &str) -> Option<Arc<dyn ToolGuide>> {
        self.registry.get_guide(tool_name)
    }

    fn parse_execution_args(
        &self,
        call: &ToolCall,
        ctx: &ToolExecutionContext<'_>,
    ) -> serde_json::Value {
        if let Some(pre_parsed) = ctx.pre_parsed_args {
            return pre_parsed.clone();
        }
        let args_raw = call.function.arguments.trim();
        let (parsed, parse_warning) = parse_tool_args_best_effort(&call.function.arguments);
        if let Some(warning) = parse_warning {
            tracing::warn!(
                "Builtin tool argument parsing fallback applied: session_id={:?}, tool_call_id={}, tool_name={}, args_len={}, args_preview=\"{}\", warning={}",
                ctx.session_id,
                call.id,
                call.function.name,
                args_raw.len(),
                preview_for_log(args_raw, 180),
                warning
            );
        }
        parsed
    }

    async fn execute_registered_with_context_outcome(
        &self,
        call: &ToolCall,
        execution_name: &str,
        ctx: ToolExecutionContext<'_>,
    ) -> Result<ToolOutcome, ToolError> {
        let tool = self
            .registry
            .get(execution_name)
            .ok_or_else(|| ToolError::NotFound(format!("Tool '{}' not found", execution_name)))?;
        check_raw_tool_input(execution_name, &call.function.arguments)?;
        let mut args = self.parse_execution_args(call, &ctx);
        check_parsed_tool_input(execution_name, &args)?;
        self.normalize_registered_builtin_args(
            &call.function.name,
            execution_name,
            &tool,
            &mut args,
        );

        if let Some(outcome) = self
            .check_permissions_for_resolved(call, execution_name, &args, &ctx)
            .await?
        {
            return Ok(outcome);
        }

        let publisher_enabled =
            catch_unwind(AssertUnwindSafe(|| self.tool_event_publisher.is_enabled()))
                .unwrap_or(false);
        let pending_file_changed = publisher_enabled
            .then(|| self.pending_file_changed(execution_name, &tool, &args))
            .flatten();

        let outcome = tool.invoke(args, ctx.to_tool_ctx()).await?;
        if matches!(
            &outcome,
            ToolOutcome::Completed(result) if result.success
        ) {
            if let Some(data) = pending_file_changed {
                self.publish_successful_file_change(&ctx, execution_name, data);
            }
        }
        Ok(outcome)
    }

    /// Build enhanced prompt for all registered tools
    pub fn build_enhanced_prompt(&self, context: GuideBuildContext) -> String {
        EnhancedPromptBuilder::build(Some(&self.registry), &self.registry.list_tools(), &context)
    }
}

fn permission_error_to_tool_error(error: PermissionError) -> ToolError {
    match error {
        PermissionError::CheckFailed(_) => ToolError::InvalidArguments(error.to_string()),
        _ => ToolError::Execution(error.to_string()),
    }
}

impl Default for BuiltinToolExecutor {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolExecutor for BuiltinToolExecutor {
    async fn execute(&self, call: &ToolCall) -> Result<ToolResult, ToolError> {
        self.execute_with_context(call, ToolExecutionContext::none(&call.id))
            .await
    }

    async fn execute_with_context(
        &self,
        call: &ToolCall,
        ctx: ToolExecutionContext<'_>,
    ) -> Result<ToolResult, ToolError> {
        self.execute_with_context_outcome(call, ctx)
            .await
            .map(ToolOutcome::into_tool_result)
    }

    async fn execute_with_context_outcome(
        &self,
        call: &ToolCall,
        ctx: ToolExecutionContext<'_>,
    ) -> Result<ToolOutcome, ToolError> {
        let reference = call.function.name.trim();
        let tool_name =
            resolve_registered_tool_name(&self.registry, reference).ok_or_else(|| {
                ToolError::NotFound(format!("Tool '{}' not found", call.function.name))
            })?;
        self.execute_registered_with_context_outcome(call, &tool_name, ctx)
            .await
    }

    async fn execute_exact_with_context_outcome(
        &self,
        call: &ToolCall,
        execution_name: &str,
        ctx: ToolExecutionContext<'_>,
    ) -> Result<ToolOutcome, ToolError> {
        self.execute_registered_with_context_outcome(call, execution_name, ctx)
            .await
    }

    /// The real permission gate for built-in tools, extracted from the execute
    /// path so it is reusable by wrapping executors (issue #341). The behavior is
    /// byte-for-byte the same block that used to run inline in
    /// `execute_with_context_outcome`:
    ///
    /// - resolves the SAME `tool_name` + `args` the execute path runs with (so
    ///   the check sees exactly what the tool will run with);
    /// - "always ask" rules (`requires_forced_confirmation`) force a confirmation
    ///   even under bypass; everything else is skipped when the session is in
    ///   bypass-permissions mode;
    /// - forced confirmations route through `check_or_request_forced` so the
    ///   active mode/bypass can't suppress the prompt;
    /// - a `ConfirmationRequired` first tries the cross-process `ApprovalProxy`
    ///   (a subagent worker forwarding to its host), then the interactive human
    ///   sink (returning the synthesized approval pause as `Ok(Some(..))`), then
    ///   fails closed;
    /// - deny fails closed.
    ///
    /// The only mechanical difference from the old inline block: the interactive
    /// pause is returned as `Ok(Some(outcome))` and a clean pass returns
    /// `Ok(None)`, so the caller decides whether to run the tool. The fallback
    /// arg-parse warning is intentionally NOT re-logged here — the execute path
    /// already logs it once for this call.
    async fn check_permissions_for(
        &self,
        call: &ToolCall,
        ctx: &ToolExecutionContext<'_>,
    ) -> Result<Option<ToolOutcome>, ToolError> {
        let reference = call.function.name.trim();
        let tool_name = resolve_registered_tool_name(&self.registry, reference)
            .unwrap_or_else(|| canonical_tool_name(reference));
        let mut args = if let Some(pre_parsed) = ctx.pre_parsed_args {
            pre_parsed.clone()
        } else {
            parse_tool_args_best_effort(&call.function.arguments).0
        };
        if let Some(tool) = self.registry.get(&tool_name) {
            self.normalize_registered_builtin_args(reference, &tool_name, &tool, &mut args);
        }
        self.check_permissions_for_resolved(call, &tool_name, &args, ctx)
            .await
    }

    async fn check_permissions_for_exact(
        &self,
        call: &ToolCall,
        execution_name: &str,
        ctx: &ToolExecutionContext<'_>,
    ) -> Result<Option<ToolOutcome>, ToolError> {
        let tool = self
            .registry
            .get(execution_name)
            .ok_or_else(|| ToolError::NotFound(format!("Tool '{}' not found", execution_name)))?;
        let mut args = if let Some(pre_parsed) = ctx.pre_parsed_args {
            pre_parsed.clone()
        } else {
            parse_tool_args_best_effort(&call.function.arguments).0
        };
        self.normalize_registered_builtin_args(
            call.function.name.trim(),
            execution_name,
            &tool,
            &mut args,
        );
        self.check_permissions_for_resolved(call, execution_name, &args, ctx)
            .await
    }

    async fn check_permissions_for_resolved(
        &self,
        call: &ToolCall,
        execution_name: &str,
        resolved_args: &serde_json::Value,
        ctx: &ToolExecutionContext<'_>,
    ) -> Result<Option<ToolOutcome>, ToolError> {
        let tool_name = execution_name.to_string();
        let args = resolved_args.clone();
        if ctx.auto_approve_permissions && tool_name.eq_ignore_ascii_case("request_permissions") {
            return Err(ToolError::Execution(
                "Auto mode cannot request expanded permissions; operate within existing hard boundaries"
                    .to_string(),
            ));
        }
        if ctx.plan_read_only && !crate::orchestrator::plan_mode_allows_tool(&tool_name) {
            return Err(ToolError::Execution(format!(
                "Plan mode: {tool_name} operation blocked"
            )));
        }
        let Some(permission_checker) = &self.permission_checker else {
            return Ok(None);
        };
        let hook_permission_override = crate::current_hook_permission_override(&call.id);

        if let Some(contexts) =
            check_permissions(&tool_name, &args).map_err(permission_error_to_tool_error)?
        {
            let proactive_permission_request =
                tool_name.eq_ignore_ascii_case("request_permissions");
            for context in contexts {
                let resource = context.resource.clone();
                let operation_summary = context.operation_description.clone();
                let risk_level = context.risk_level();
                let permission_type = context.permission_type;
                let platform_hard_deny = permission_checker.hard_deny_reason(&context);
                let config = permission_checker.permission_config();
                let proxy = crate::approval::current_approval_proxy();
                let request = if let Some(config) = config.as_ref() {
                    if proactive_permission_request && proxy.is_some() {
                        return Err(ToolError::Execution(
                            "request_permissions requires the local typed decision protocol; a boolean approval relay cannot create remembered authority"
                                .to_string(),
                        ));
                    }
                    // A boolean approval relay can only honor one-shot choices.
                    // Interactive local sessions support all typed scopes; the
                    // evaluator omits workspace when no stable identity is known.
                    let mut supported_decisions = if proxy.is_some() {
                        crate::permission::PermissionRequest::forced_decisions()
                    } else {
                        crate::permission::PermissionRequest::ordinary_decisions(true)
                    };
                    if proactive_permission_request {
                        // AllowOnce is bound to the request_permissions call,
                        // not the later target operation, so offering it would
                        // falsely claim authority was granted. Remembered
                        // scopes remain exact matcher-bound and are replay-safe.
                        supported_decisions.retain(|decision| {
                            *decision != crate::permission::PermissionDecisionKind::AllowOnce
                        });
                    }
                    // Workspace-scoped policy is an authority boundary. Tool
                    // arguments are model-controlled resources and must never
                    // choose that scope identity; only the workspace registered
                    // for this stable session may enable AllowWorkspace.
                    let workspace_path = ctx
                        .session_id
                        .and_then(|session_id| config.session_workspace(session_id));
                    match config.evaluate(crate::permission::PermissionEvaluation {
                        request_id: call.id.clone(),
                        session_id: ctx.session_id.unwrap_or_default().to_string(),
                        workspace_path,
                        tool_name: tool_name.clone(),
                        tool_args: args.clone(),
                        permission_type,
                        resource: resource.clone(),
                        operation_summary: operation_summary.clone(),
                        risk_level,
                        bypass_requested: ctx.bypass_permissions,
                        auto_approve_requested: ctx.auto_approve_permissions,
                        platform_hard_deny,
                        consume_once: true,
                        supported_decisions,
                    }) {
                        crate::permission::PermissionOutcome::Allow { .. } => continue,
                        crate::permission::PermissionOutcome::Deny { reason, .. } => {
                            return Err(ToolError::Execution(reason.message));
                        }
                        crate::permission::PermissionOutcome::Ask(request)
                            if matches!(
                                hook_permission_override,
                                Some(crate::HookPermissionOverride::Allow)
                            ) && !proactive_permission_request
                                && request.reason_code
                                    != crate::permission::PermissionReasonCode::HardDangerous =>
                        {
                            continue;
                        }
                        crate::permission::PermissionOutcome::Ask(request) => request,
                    }
                } else {
                    if proactive_permission_request {
                        return Err(ToolError::Execution(
                            "request_permissions requires a typed PermissionConfig and cannot fall back to a display-string approval"
                                .to_string(),
                        ));
                    }
                    // Compatibility path for custom checkers that do not expose a
                    // typed config. It remains one-shot only and fail-closed.
                    if let Some(reason) = platform_hard_deny {
                        return Err(ToolError::Execution(reason));
                    }
                    let force_ask =
                        permission_checker.requires_forced_confirmation(&tool_name, &args);
                    let hook_allows = matches!(
                        hook_permission_override,
                        Some(crate::HookPermissionOverride::Allow)
                    );
                    if ctx.auto_approve_permissions
                        || ((ctx.bypass_permissions || hook_allows) && !force_ask)
                    {
                        continue;
                    }
                    let decision = if force_ask {
                        permission_checker.check_or_request_forced(context).await
                    } else if let Some(session_id) = ctx.session_id {
                        permission_checker
                            .check_or_request_for_session(session_id, context)
                            .await
                    } else {
                        permission_checker.check_or_request(context).await
                    };
                    match decision {
                        Ok(true) => continue,
                        Ok(false) => {
                            return Err(ToolError::Execution(format!(
                                "Permission denied for: {}",
                                resource
                            )));
                        }
                        Err(PermissionError::ConfirmationRequired { .. }) => {
                            crate::permission::PermissionRequest {
                                request_id: call.id.clone(),
                                request_generation:
                                    crate::permission::PermissionRequest::fresh_generation(),
                                session_id: ctx.session_id.unwrap_or_default().to_string(),
                                workspace_path: None,
                                tool_name: tool_name.clone(),
                                permission_type,
                                resource: resource.clone(),
                                operation_summary: operation_summary.clone(),
                                risk_level,
                                reason_code: if force_ask {
                                    crate::permission::PermissionReasonCode::ConfiguredAlwaysAsk
                                } else {
                                    crate::permission::PermissionReasonCode::RiskThreshold
                                },
                                effective_mode: bamboo_config::settings::PermissionMode::Default,
                                bypass_requested: ctx.bypass_permissions,
                                auto_approve_requested: ctx.auto_approve_permissions,
                                policy_revision: 0,
                                matched_rule: None,
                                allowed_decisions:
                                    crate::permission::PermissionRequest::forced_decisions(),
                                suggested_matchers: crate::permission::conservative_matchers(
                                    permission_type,
                                    &resource,
                                ),
                            }
                        }
                        Err(other) => return Err(permission_error_to_tool_error(other)),
                    }
                };

                // A worker/external relay gets the same typed request but only
                // one-shot decisions are advertised until its protocol supports
                // a stronger scope. No boolean downgrade can create a grant.
                if let Some(proxy) = proxy {
                    let approved = proxy
                        .request_approval(crate::approval::ApprovalAsk {
                            tool_name: tool_name.clone(),
                            permission: permission_type.description().to_string(),
                            resource: resource.clone(),
                            permission_request: Some(request.clone()),
                        })
                        .await;
                    if approved {
                        continue;
                    }
                    return Err(ToolError::Execution(format!(
                        "Permission denied by host for: {}",
                        resource
                    )));
                }

                // Interactive sessions pause through the legacy question shape
                // while carrying the complete typed request alongside it.
                if let Some(tx) = ctx.event_tx {
                    let _ = tx
                        .send(bamboo_agent_core::AgentEvent::ToolApprovalRequested {
                            tool_call_id: call.id.clone(),
                            tool_name: tool_name.clone(),
                            parameters: args.clone(),
                        })
                        .await;

                    let question = format!(
                        "**Permission required**\n\nThe `{}` tool needs approval to {} on:\n\n`{}`",
                        tool_name,
                        permission_type.description(),
                        resource
                    );
                    if let Some(config) = config {
                        config.register_pending_request(request.clone());
                    }
                    let payload = serde_json::json!({
                        "status": "awaiting_permission_approval",
                        "question": question,
                        "permission_type": permission_type,
                        "resource": resource,
                        "options": ["Approve", "Deny"],
                        "allow_custom": false,
                        "permission_request": request,
                    });
                    return Ok(Some(ToolOutcome::Completed(ToolResult {
                        success: true,
                        result: payload.to_string(),
                        display_preference: Some("request_permissions".to_string()),
                        images: Vec::new(),
                    })));
                }

                return Err(ToolError::Execution(format!(
                    "Permission approval required for: {}",
                    resource
                )));
            }
        }

        Ok(None)
    }

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

    fn owns_exact_tool(&self, tool_name: &str) -> bool {
        self.registry.contains(tool_name)
    }

    fn tool_mutability(&self, tool_name: &str) -> crate::ToolMutability {
        let resolved = resolve_registered_tool_name(&self.registry, tool_name);
        resolved
            .as_deref()
            .and_then(|name| self.registry.get(name))
            .map(|tool| tool.classify(&serde_json::Value::Null).mutability)
            .unwrap_or_else(|| crate::classify_tool(&canonical_tool_name(tool_name)))
    }

    fn call_mutability(&self, call: &ToolCall) -> crate::ToolMutability {
        self.call_parallel_classification(call).0
    }

    fn tool_concurrency_safe(&self, tool_name: &str) -> bool {
        let resolved = resolve_registered_tool_name(&self.registry, tool_name);
        resolved
            .as_deref()
            .and_then(|name| self.registry.get(name))
            .map(|tool| tool.classify(&serde_json::Value::Null).parallel_safe)
            .unwrap_or_else(|| self.tool_mutability(tool_name) == crate::ToolMutability::ReadOnly)
    }

    fn call_concurrency_safe(&self, call: &ToolCall) -> bool {
        self.call_parallel_classification(call).1
    }

    fn call_parallel_classification(&self, call: &ToolCall) -> (crate::ToolMutability, bool) {
        // One args-aware `classify` returns the (mutability, parallel_safe) pair
        // with a single arg parse — the collapse of the former
        // `call_mutability`/`call_concurrency_safe` pair.
        let reference = call.function.name.trim();
        let resolved = resolve_registered_tool_name(&self.registry, reference);
        let mut args = bamboo_agent_core::parse_tool_args_best_effort(&call.function.arguments).0;
        match resolved.as_deref().and_then(|execution_name| {
            self.registry
                .get(execution_name)
                .map(|tool| (execution_name, tool))
        }) {
            Some((execution_name, tool)) => {
                self.normalize_registered_builtin_args(reference, execution_name, &tool, &mut args);
                let class = tool.classify(&args);
                (class.mutability, class.parallel_safe)
            }
            None => (
                self.tool_mutability(reference),
                self.tool_concurrency_safe(reference),
            ),
        }
    }
}

/// Builder for constructing a BuiltinToolExecutor with custom tool configurations
pub struct BuiltinToolExecutorBuilder {
    registry: ToolRegistry,
    permission_checker: Option<Arc<dyn PermissionChecker>>,
    framework_builtin_tools: BTreeMap<String, Arc<dyn Tool>>,
    tool_event_publisher: Arc<dyn ToolEventPublisher>,
}

impl BuiltinToolExecutorBuilder {
    /// Creates a new builder with no tools registered
    pub fn new() -> Self {
        Self {
            registry: ToolRegistry::new(),
            permission_checker: None,
            framework_builtin_tools: BTreeMap::new(),
            tool_event_publisher: BuiltinToolExecutor::default_tool_event_publisher(),
        }
    }

    /// Registers all default built-in tools
    pub fn with_default_tools(mut self) -> Self {
        self.framework_builtin_tools
            .extend(BuiltinToolExecutor::register_builtin_tools(
                &self.registry,
                None,
            ));
        self
    }

    /// Registers a specific filesystem tool by name
    pub fn with_filesystem_tool(mut self, name: &str) -> Result<Self, ToolError> {
        let (name, tool) = match name {
            "Read" => {
                BuiltinToolExecutor::register_tracked_builtin(&self.registry, ReadTool::new())?
            }
            "Write" => {
                BuiltinToolExecutor::register_tracked_builtin(&self.registry, WriteTool::new())?
            }
            // apply_patch is now an alias for Edit
            "Edit" | "apply_patch" => {
                BuiltinToolExecutor::register_tracked_builtin(&self.registry, EditTool::new())?
            }
            "NotebookEdit" => BuiltinToolExecutor::register_tracked_builtin(
                &self.registry,
                NotebookEditTool::new(),
            )?,
            _ => return Err(ToolError::NotFound(format!("Unknown tool: {}", name))),
        };
        self.framework_builtin_tools.insert(name, tool);
        Ok(self)
    }

    /// Registers a specific command tool by name
    pub fn with_command_tool(mut self, name: &str) -> Result<Self, ToolError> {
        if name == "Bash" {
            let (name, tool) =
                BuiltinToolExecutor::register_tracked_builtin(&self.registry, BashTool::new())?;
            self.framework_builtin_tools.insert(name, tool);
            return Ok(self);
        }
        match name {
            "BashOutput" => self.registry.register(BashOutputTool::new()),
            "KillShell" => self.registry.register(KillShellTool::new()),
            "Task" => self.registry.register(TaskTool::new()),
            _ => return Err(ToolError::NotFound(format!("Unknown tool: {}", name))),
        }
        .map_err(|e| ToolError::Execution(e.to_string()))?;
        Ok(self)
    }

    /// Registers a custom tool
    pub fn with_tool<T: Tool + 'static>(self, tool: T) -> Result<Self, ToolError> {
        self.registry
            .register(tool)
            .map_err(|e| ToolError::Execution(e.to_string()))?;
        Ok(self)
    }

    /// Sets a permission checker for this executor
    pub fn with_permission_checker(mut self, checker: Arc<dyn PermissionChecker>) -> Self {
        self.permission_checker = Some(checker);
        self
    }

    /// Sets the instance-local tool-event publisher.
    pub fn with_tool_event_publisher(mut self, publisher: Arc<dyn ToolEventPublisher>) -> Self {
        self.tool_event_publisher = publisher;
        self
    }

    /// Builds the executor
    pub fn build(self) -> BuiltinToolExecutor {
        BuiltinToolExecutor {
            registry: self.registry,
            permission_checker: self.permission_checker,
            framework_builtin_tools: self.framework_builtin_tools,
            tool_event_publisher: self.tool_event_publisher,
        }
    }
}

impl Default for BuiltinToolExecutorBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bamboo_agent_core::AgentEvent;
    use bamboo_agent_core::FunctionCall;
    use bamboo_agent_core::ToolCtx;
    use bamboo_agent_core::ToolExecutionContext;
    use bamboo_domain::tool_names::{normalize_tool_ref, BUILTIN_TOOL_NAMES};
    use bamboo_plugin_protocol::{
        FileChangedV1, InMemoryToolEventRecorder, ToolEventContextV1, ToolEventPublishError,
        ToolEventV1, MAX_TOOL_EVENT_PATH_BYTES,
    };
    use serde_json::json;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use tokio::fs;
    use tokio::sync::mpsc;

    use crate::tools::WriteTool;

    fn make_tool_call(name: &str, args: serde_json::Value) -> ToolCall {
        make_tool_call_with_id("call_1", name, args)
    }

    #[tokio::test]
    async fn oversized_write_is_rejected_before_creating_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("oversized.txt");
        let call = make_tool_call(
            "write_file",
            json!({
                "path": file,
                "content": "x".repeat(1024 * 1024),
            }),
        );
        let error = BuiltinToolExecutor::new().execute(&call).await.unwrap_err();
        assert!(matches!(error, ToolError::InvalidArguments(_)));
        assert!(!file.exists());
    }

    fn make_tool_call_with_id(id: &str, name: &str, args: serde_json::Value) -> ToolCall {
        ToolCall {
            id: id.to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: args.to_string(),
            },
        }
    }

    fn tool_event_context<'a>(
        call: &'a ToolCall,
        session_id: Option<&'a str>,
        root_session_id: Option<&'a str>,
    ) -> ToolExecutionContext<'a> {
        ToolExecutionContext {
            executing_supervisor: None,
            session_id,
            root_session_id,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        }
    }

    fn assert_single_file_changed(
        recorder: &InMemoryToolEventRecorder,
        session_id: &str,
        root_session_id: &str,
        tool_name: &str,
        tool_call_id: &str,
        path: &str,
    ) {
        let events = recorder.try_snapshot().expect("snapshot tool events");
        assert_eq!(
            events.len(),
            1,
            "successful mutation must emit exactly once"
        );
        let event = &events[0];
        assert_eq!(event.context.session_id, session_id);
        assert_eq!(event.context.root_session_id, root_session_id);
        assert_eq!(event.context.tool_name, tool_name);
        assert_eq!(event.context.tool_call_id, tool_call_id);
        assert_eq!(
            event
                .file_changed_data()
                .expect("known file_changed event")
                .expect("valid file_changed payload")
                .path,
            path
        );
    }

    fn seed_event(call_id: &str) -> ToolEventV1 {
        ToolEventV1::file_changed(
            ToolEventContextV1::bounded("seed-session", "seed-root-session", "Write", call_id)
                .unwrap(),
            FileChangedV1::bounded("/seed/file.txt").unwrap(),
        )
        .unwrap()
    }

    fn make_tool_call_with_raw_args(name: &str, raw_args: &str) -> ToolCall {
        ToolCall {
            id: "call_1".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: raw_args.to_string(),
            },
        }
    }

    struct ReturningPublisher(ToolEventPublishError);

    impl ToolEventPublisher for ReturningPublisher {
        fn try_publish(&self, _event: ToolEventV1) -> Result<(), ToolEventPublishError> {
            Err(self.0.clone())
        }
    }

    struct IsEnabledPanicPublisher;

    impl ToolEventPublisher for IsEnabledPanicPublisher {
        fn is_enabled(&self) -> bool {
            panic!("is_enabled publisher panic")
        }

        fn try_publish(&self, _event: ToolEventV1) -> Result<(), ToolEventPublishError> {
            unreachable!("disabled publisher must not receive an event")
        }
    }

    struct TryPublishPanicPublisher;

    impl ToolEventPublisher for TryPublishPanicPublisher {
        fn try_publish(&self, _event: ToolEventV1) -> Result<(), ToolEventPublishError> {
            panic!("try_publish publisher panic")
        }
    }

    struct StubWriteTool {
        success: bool,
    }

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

        fn description(&self) -> &str {
            "test-only custom tool that deliberately spoofs Write"
        }

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

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

    fn marked_stub_write_executor(
        success: bool,
        publisher: Arc<dyn ToolEventPublisher>,
    ) -> BuiltinToolExecutor {
        let registry = ToolRegistry::new();
        let tool: Arc<dyn Tool> = Arc::new(StubWriteTool { success });
        registry
            .register_shared(tool.clone())
            .expect("register stub Write");
        BuiltinToolExecutor {
            registry,
            permission_checker: None,
            framework_builtin_tools: BTreeMap::from([("Write".to_string(), tool)]),
            tool_event_publisher: publisher,
        }
    }

    async fn assert_real_write_succeeds_with_publisher(
        publisher: Arc<dyn ToolEventPublisher>,
        label: &str,
    ) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(format!("publisher-{label}.txt"));
        let call = make_tool_call_with_id(
            &format!("publisher-{label}"),
            "Write",
            json!({"file_path": path, "content": label}),
        );
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Write")
            .expect("register built-in Write")
            .with_tool_event_publisher(publisher)
            .build();

        let result = executor
            .execute_with_context(
                &call,
                tool_event_context(
                    &call,
                    Some("publisher-session"),
                    Some("publisher-root-session"),
                ),
            )
            .await
            .expect("publisher behavior must not turn tool success into an error");

        assert!(
            result.success,
            "publisher must not alter ToolResult.success"
        );
        assert_eq!(fs::read_to_string(path).await.unwrap(), label);
    }

    fn make_executor(
        permission_checker: Option<Arc<dyn PermissionChecker>>,
    ) -> BuiltinToolExecutor {
        let builder = BuiltinToolExecutorBuilder::new()
            .with_tool(WriteTool::new())
            .expect("register Write tool");

        let builder = match permission_checker {
            Some(checker) => builder.with_permission_checker(checker),
            None => builder,
        };

        builder.build()
    }

    async fn permission_request_payload(
        executor: &BuiltinToolExecutor,
        session_id: &str,
        args: serde_json::Value,
    ) -> serde_json::Value {
        let (event_tx, _event_rx) = mpsc::channel(4);
        let call = make_tool_call("Write", args);
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some(session_id),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: Some(&event_tx),
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };
        let result = executor
            .execute_with_context(&call, ctx)
            .await
            .expect("interactive permission gate should pause");
        serde_json::from_str(&result.result).expect("typed permission payload")
    }

    struct RecordingApprovalProxy {
        requests: Arc<AtomicUsize>,
        approve: bool,
    }

    #[async_trait]
    impl crate::approval::ApprovalProxy for RecordingApprovalProxy {
        async fn request_approval(&self, _ask: crate::approval::ApprovalAsk) -> bool {
            self.requests.fetch_add(1, Ordering::SeqCst);
            self.approve
        }
    }

    #[test]
    fn test_normalize_tool_ref_accepts_claude_style_names() {
        assert_eq!(
            normalize_tool_ref("default::Bash"),
            Some("Bash".to_string())
        );
    }

    #[test]
    fn test_normalize_tool_ref_accepts_legacy_camel_aliases() {
        assert_eq!(
            normalize_tool_ref("default::fileExists"),
            Some("FileExists".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::getCurrentDir"),
            Some("GetCurrentDir".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::getFileInfo"),
            Some("GetFileInfo".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::setWorkspace"),
            Some("SetWorkspace".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::sleep"),
            Some("Sleep".to_string())
        );
    }

    #[test]
    fn test_normalize_tool_ref_accepts_legacy_snake_case_aliases() {
        assert_eq!(
            normalize_tool_ref("default::execute_command"),
            Some("Bash".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::file_exists"),
            Some("FileExists".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::get_current_dir"),
            Some("GetCurrentDir".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::get_file_info"),
            Some("GetFileInfo".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::list_directory"),
            Some("Glob".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::memory_note"),
            Some("memory_note".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::read_file"),
            Some("Read".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::set_workspace"),
            Some("SetWorkspace".to_string())
        );
        assert_eq!(
            normalize_tool_ref("default::write_file"),
            Some("Write".to_string())
        );
    }

    #[test]
    fn test_normalize_tool_ref_accepts_spawn_task_aliases() {
        for alias in [
            "default::spawn_session",
            "default::sub_session",
            "default::sub_task",
            "default::team_agent",
            "default::child_session",
        ] {
            assert_eq!(normalize_tool_ref(alias), Some("SubAgent".to_string()));
        }
    }

    #[test]
    fn test_normalize_tool_ref_accepts_server_overlay_tools() {
        assert_eq!(normalize_tool_ref("compress_context"), None);
        assert_eq!(
            normalize_tool_ref("default::read_skill_resource"),
            Some("read_skill_resource".to_string())
        );
    }

    #[tokio::test]
    async fn test_executor_accepts_legacy_read_file_path_argument() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("legacy-read.txt");
        fs::write(&file_path, "legacy read content").await.unwrap();

        let executor = BuiltinToolExecutor::new();
        let call = make_tool_call("read_file", json!({"path": file_path}));

        let result = executor.execute(&call).await.unwrap();
        assert!(result.success);
        assert!(result.result.contains("legacy read content"));
    }

    #[tokio::test]
    async fn test_executor_accepts_legacy_list_directory_without_pattern() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("legacy-list.txt");
        fs::write(&file_path, "legacy list content").await.unwrap();

        let executor = BuiltinToolExecutor::new();
        let call = make_tool_call("list_directory", json!({"path": dir.path()}));

        let result = executor.execute(&call).await.unwrap();
        assert!(result.success);
        assert!(result.result.contains("legacy-list.txt"));
    }

    #[tokio::test]
    async fn test_executor_accepts_canonical_read_with_path_argument() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("canonical-read.txt");
        fs::write(&file_path, "canonical read content")
            .await
            .unwrap();

        let executor = BuiltinToolExecutor::new();
        let call = make_tool_call("Read", json!({"path": file_path}));

        let result = executor.execute(&call).await.unwrap();
        assert!(result.success);
        assert!(result.result.contains("canonical read content"));

        let namespaced = make_tool_call("default::Read", json!({"path": file_path}));
        let result = executor.execute(&namespaced).await.unwrap();
        assert!(result.success);
        assert!(result.result.contains("canonical read content"));
    }

    #[tokio::test]
    async fn test_executor_accepts_canonical_glob_without_pattern_when_path_present() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("canonical-list.txt");
        fs::write(&file_path, "canonical list content")
            .await
            .unwrap();

        let executor = BuiltinToolExecutor::new();
        let call = make_tool_call("Glob", json!({"path": dir.path()}));

        let result = executor.execute(&call).await.unwrap();
        assert!(result.success);
        assert!(result.result.contains("canonical-list.txt"));
    }

    #[test]
    fn test_executor_workspace_mutability_depends_on_path_argument() {
        let executor = BuiltinToolExecutor::new();
        let get_call = make_tool_call("Workspace", json!({}));
        let set_call = make_tool_call("Workspace", json!({"path": "/tmp"}));

        assert_eq!(
            executor.call_mutability(&get_call),
            crate::ToolMutability::ReadOnly
        );
        assert!(executor.call_concurrency_safe(&get_call));

        assert_eq!(
            executor.call_mutability(&set_call),
            crate::ToolMutability::Mutating
        );
        assert!(!executor.call_concurrency_safe(&set_call));
    }

    #[test]
    fn call_parallel_classification_matches_individual_methods() {
        // Regression guard for the issue #17 perf refactor: the combined
        // `call_parallel_classification` (which parses args once) must return the
        // exact same (mutability, concurrency_safe) pair as calling
        // `call_mutability` and `call_concurrency_safe` separately (which each
        // parse args). Covers a read-only tool, mutating tools, and an
        // args-aware tool (Workspace get vs set) so every branch of the
        // single-parse override is exercised.
        let executor = BuiltinToolExecutor::new();
        let cases: &[(&str, serde_json::Value)] = &[
            ("Read", json!({})),
            ("Grep", json!({"pattern": "x"})),
            (
                "Write",
                json!({"file_path": "/tmp/par_cls.txt", "content": "y"}),
            ),
            ("Bash", json!({"command": "echo hi"})),
            ("Workspace", json!({})),
            ("Workspace", json!({"path": "/tmp"})),
        ];

        for (name, args) in cases {
            let call = make_tool_call(name, args.clone());
            let expected_mutability = executor.call_mutability(&call);
            let expected_concurrency = executor.call_concurrency_safe(&call);
            let (mutability, concurrency) = executor.call_parallel_classification(&call);
            assert_eq!(
                mutability, expected_mutability,
                "mutability mismatch for {name} ({args})"
            );
            assert_eq!(
                concurrency, expected_concurrency,
                "concurrency mismatch for {name} ({args})"
            );
        }
    }

    #[test]
    fn list_tools_snapshot_is_stable_across_calls() {
        // The per-round schema cache (issue #17 Part A) assumes the executor's
        // `list_tools()` is stable within a round: a snapshot taken once must
        // equal a fresh call. Guards that invariant so caching the set for the
        // duration of a round can't serve a stale or filtered view.
        let executor = BuiltinToolExecutor::new();
        let first: Vec<String> = executor
            .list_tools()
            .into_iter()
            .map(|s| s.function.name)
            .collect();
        let second: Vec<String> = executor
            .list_tools()
            .into_iter()
            .map(|s| s.function.name)
            .collect();
        assert!(!first.is_empty(), "builtin executor should expose tools");
        assert_eq!(
            first, second,
            "list_tools() must be deterministic per round"
        );
    }

    #[tokio::test]
    async fn test_executor_recovers_truncated_json_arguments() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("recovered-write.txt");

        // Missing closing brace simulates EOF while parsing an object.
        let malformed_args = format!(
            r#"{{"file_path":"{}","content":"recovered content""#,
            path.display()
        );

        let executor = BuiltinToolExecutor::new();
        let call = make_tool_call_with_raw_args("Write", &malformed_args);

        let result = executor
            .execute(&call)
            .await
            .expect("truncated JSON should be auto-repaired");
        assert!(result.success);

        let written = fs::read_to_string(&path)
            .await
            .expect("file should be written");
        assert_eq!(written, "recovered content");
    }

    #[test]
    fn test_normalize_tool_ref_rejects_unknown_tool() {
        assert_eq!(normalize_tool_ref("default::search"), None);
    }

    #[test]
    fn test_executor_does_not_expose_legacy_tools() {
        let executor = BuiltinToolExecutor::new();
        let tool_names: Vec<String> = executor
            .list_tools()
            .into_iter()
            .map(|schema| schema.function.name)
            .collect();

        for legacy in ["claude_code", "search_in_file", "search_in_project"] {
            assert!(!tool_names.iter().any(|name| name == legacy));
        }
    }

    #[test]
    fn test_critical_tool_schemas_match_claude_shapes() {
        let executor = BuiltinToolExecutor::new();
        let tools = executor.list_tools();

        let get_params = |name: &str| {
            tools
                .iter()
                .find(|tool| tool.function.name == name)
                .unwrap()
                .function
                .parameters
                .clone()
        };

        let grep = get_params("Grep");
        assert_eq!(grep["required"], json!(["pattern"]));
        assert_eq!(
            grep["properties"]["output_mode"]["enum"],
            json!(["content", "files_with_matches", "count"])
        );
        assert!(grep["properties"]["-A"].is_object());
        assert!(grep["properties"]["-B"].is_object());
        assert!(grep["properties"]["-C"].is_object());
        assert!(grep["properties"]["-n"].is_object());
        assert!(grep["properties"]["-i"].is_object());

        let edit = get_params("Edit");
        assert_eq!(edit["required"], json!(["file_path"]));
        assert_eq!(edit["properties"]["old_string"]["type"], "string");
        assert_eq!(edit["properties"]["new_string"]["type"], "string");
        assert_eq!(edit["properties"]["patch"]["type"], "string");
        assert_eq!(edit["properties"]["replace_all"]["type"], "boolean");
        assert!(edit.get("oneOf").is_none());

        // apply_patch is now an alias for Edit – its schema is the Edit
        // schema, so we just verify that Edit includes the patch property.
        assert_eq!(edit["properties"]["patch"]["type"], "string");
        assert_eq!(edit["properties"]["line_number"]["type"], "integer");

        let bash = get_params("Bash");
        assert_eq!(bash["required"], json!(["command"]));
        assert_eq!(bash["properties"]["run_in_background"]["type"], "boolean");
        assert_eq!(bash["properties"]["workdir"]["type"], "string");

        let bash_output = get_params("BashOutput");
        assert_eq!(bash_output["required"], json!(["bash_id"]));
        assert_eq!(bash_output["properties"]["filter"]["type"], "string");
    }

    #[test]
    fn test_tool_schemas_avoid_openai_forbidden_top_level_keywords() {
        let executor = BuiltinToolExecutor::new();
        let tools = executor.list_tools();
        let forbidden = ["oneOf", "anyOf", "allOf", "not", "enum"];

        for tool in tools {
            let params = &tool.function.parameters;
            assert_eq!(
                params["type"], "object",
                "tool '{}' parameters must be a top-level object schema",
                tool.function.name
            );
            for key in forbidden {
                assert!(
                    params.get(key).is_none(),
                    "tool '{}' parameters contains forbidden top-level keyword '{}'",
                    tool.function.name,
                    key
                );
            }
        }
    }

    #[test]
    fn test_executor_has_all_builtin_tools() {
        let executor = BuiltinToolExecutor::new();
        let tools = executor.list_tools();

        assert_eq!(tools.len(), BUILTIN_TOOL_NAMES.len());

        let tool_names: Vec<String> = tools.iter().map(|t| t.function.name.clone()).collect();
        for tool_name in BUILTIN_TOOL_NAMES {
            assert!(tool_names.contains(&tool_name.to_string()));
        }
    }

    #[test]
    fn test_executor_builds_enhanced_prompt() {
        let executor = BuiltinToolExecutor::new();
        let prompt = executor.build_enhanced_prompt(GuideBuildContext::default());
        assert!(prompt.contains("## Tool Usage Guidelines"));
        assert!(prompt.contains("**Read**"));
    }

    #[test]
    fn test_executor_builder_empty() {
        let executor = BuiltinToolExecutorBuilder::new().build();
        assert!(executor.list_tools().is_empty());
    }

    #[test]
    fn test_executor_builder_with_default_tools() {
        let executor = BuiltinToolExecutorBuilder::new()
            .with_default_tools()
            .build();
        assert_eq!(executor.list_tools().len(), BUILTIN_TOOL_NAMES.len());
    }

    #[test]
    fn test_executor_builder_with_specific_tool() {
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Read")
            .unwrap()
            .build();

        let tools = executor.list_tools();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].function.name, "Read");
    }

    #[tokio::test]
    async fn test_executor_skips_permission_checks_without_checker() {
        let executor = make_executor(None);
        let path = "/tmp/executor_permission_none.txt";
        let _ = fs::remove_file(path).await;

        let call = make_tool_call("Write", json!({"file_path": path, "content": "ok"}));
        let result = executor.execute(&call).await.expect("execute tool");

        assert!(result.success);
        let _ = fs::remove_file(path).await;
    }

    #[tokio::test]
    async fn test_executor_with_permission_checker_enforces_checks() {
        let checker = Arc::new(crate::permission::DenyDangerousPermissionChecker);
        let executor = make_executor(Some(checker));
        let path = "/tmp/executor_permission_denied.txt";
        let _ = fs::remove_file(path).await;

        let call = make_tool_call("Write", json!({"file_path": path, "content": "nope"}));
        let result = executor.execute(&call).await;

        assert!(matches!(result, Err(ToolError::Execution(_))));
        assert!(fs::metadata(path).await.is_err());
    }

    #[tokio::test]
    async fn test_bypass_permissions_skips_checker() {
        // Model the worker side of a child whose parent bypass flag was inherited:
        // a production Bash tool under the production config evaluator must
        // execute an ordinary command directly. Even though both a parent
        // approval proxy and a human-event sink are installed, neither path may
        // be touched.
        let config = Arc::new(crate::permission::PermissionConfig::new());
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(BashTool::new())
            .expect("register Bash tool")
            .with_permission_checker(checker)
            .build();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bypass_allows_bash.txt");
        let command = format!("printf ordinary > {}", path.display());
        let approval_requests = Arc::new(AtomicUsize::new(0));
        let proxy: Arc<dyn crate::approval::ApprovalProxy> = Arc::new(RecordingApprovalProxy {
            requests: approval_requests.clone(),
            approve: true,
        });
        let (event_tx, mut event_rx) = mpsc::channel(8);

        let call = make_tool_call("Bash", json!({"command": command}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-bypass"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: Some(&event_tx),
            available_tool_schemas: None,
            bypass_permissions: true,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };
        let result = crate::approval::with_approval_proxy(
            Some(proxy),
            executor.execute_with_context(&call, ctx),
        )
        .await;

        assert!(result.is_ok(), "bypass should allow the write: {result:?}");
        assert_eq!(fs::read_to_string(&path).await.unwrap(), "ordinary");
        assert_eq!(
            approval_requests.load(Ordering::SeqCst),
            0,
            "ordinary bypassed child command must not invoke the parent reviewer"
        );
        assert!(
            event_rx.try_recv().is_err(),
            "ordinary bypassed child command must not emit a human approval event"
        );
    }

    #[tokio::test]
    async fn hook_allow_skips_configured_ask_for_exact_call() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hook-allowed.txt");
        let path_str = path.to_str().unwrap().to_string();
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_ask_rules([format!("Write({}/**)", dir.path().to_str().unwrap())]);
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = make_executor(Some(checker));
        let call = make_tool_call(
            "Write",
            json!({"file_path": path_str, "content": "allowed by hook"}),
        );
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-hook-allow"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = crate::with_hook_permission_override(
            Some(crate::HookPermissionOverride::Allow),
            &call.id,
            executor.execute_with_context(&call, ctx),
        )
        .await;

        assert!(
            result.is_ok(),
            "hook allow should skip ordinary ask: {result:?}"
        );
        assert_eq!(fs::read_to_string(path).await.unwrap(), "allowed by hook");
        assert_eq!(
            crate::current_hook_permission_override(&call.id),
            None,
            "the one-call override must not leak"
        );
    }

    #[tokio::test]
    async fn hook_allow_cannot_skip_hard_dangerous_parent_review() {
        let config = Arc::new(crate::permission::PermissionConfig::new());
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(BashTool::new())
            .expect("register Bash tool")
            .with_permission_checker(checker)
            .build();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hard-dangerous-must-not-run.txt");
        let command = format!("eval 'printf denied > {}'", path.display());
        let requests = Arc::new(AtomicUsize::new(0));
        let proxy: Arc<dyn crate::approval::ApprovalProxy> = Arc::new(RecordingApprovalProxy {
            requests: requests.clone(),
            approve: false,
        });
        let call = make_tool_call("Bash", json!({"command": command}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-hook-hard-dangerous"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: true,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = crate::with_hook_permission_override(
            Some(crate::HookPermissionOverride::Allow),
            &call.id,
            crate::approval::with_approval_proxy(
                Some(proxy),
                executor.execute_with_context(&call, ctx),
            ),
        )
        .await;

        assert!(
            matches!(result, Err(ToolError::Execution(ref message)) if message.contains("denied by host")),
            "hard-dangerous review must remain authoritative: {result:?}"
        );
        assert_eq!(requests.load(Ordering::SeqCst), 1);
        assert!(!path.exists());
    }

    #[tokio::test]
    async fn hook_allow_cannot_skip_explicit_deny() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("explicit-deny.txt");
        let path_str = path.to_str().unwrap().to_string();
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.deny_scoped_session_permission(
            "s-hook-explicit-deny",
            crate::permission::PermissionType::WriteFile,
            path_str.clone(),
        );
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = make_executor(Some(checker));
        let call = make_tool_call(
            "Write",
            json!({"file_path": path_str, "content": "must not be written"}),
        );
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-hook-explicit-deny"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = crate::with_hook_permission_override(
            Some(crate::HookPermissionOverride::Allow),
            &call.id,
            executor.execute_with_context(&call, ctx),
        )
        .await;

        assert!(
            matches!(result, Err(ToolError::Execution(ref message)) if message.contains("remembered session decision")),
            "explicit deny must remain authoritative: {result:?}"
        );
        assert!(!path.exists());
    }

    #[tokio::test]
    async fn test_forced_ask_rule_overrides_bypass() {
        // A hard-dangerous Bash command must still traverse the worker's parent
        // approval proxy under bypass. The returned verdict is authoritative:
        // deny prevents execution, while approve lets the exact command run.
        let config = Arc::new(crate::permission::PermissionConfig::new());
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(BashTool::new())
            .expect("register Bash tool")
            .with_permission_checker(checker)
            .build();
        let dir = tempfile::tempdir().unwrap();
        let denied_path = dir.path().join("forced-denied.txt");
        let denied_command = format!("eval 'printf denied > {}'", denied_path.display());
        let denied_requests = Arc::new(AtomicUsize::new(0));
        let deny_proxy: Arc<dyn crate::approval::ApprovalProxy> =
            Arc::new(RecordingApprovalProxy {
                requests: denied_requests.clone(),
                approve: false,
            });

        let denied_call = make_tool_call("Bash", json!({"command": denied_command}));
        let denied_ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-forced"),
            root_session_id: None,
            tool_call_id: &denied_call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: true,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };
        let denied = crate::approval::with_approval_proxy(
            Some(deny_proxy),
            executor.execute_with_context(&denied_call, denied_ctx),
        )
        .await;

        assert!(
            matches!(denied, Err(ToolError::Execution(ref message)) if message.contains("denied by host")),
            "parent denial must block forced-ask execution under bypass: {denied:?}"
        );
        assert_eq!(denied_requests.load(Ordering::SeqCst), 1);
        assert!(!denied_path.exists(), "denied command must not execute");

        let approved_path = dir.path().join("forced-approved.txt");
        let approved_command = format!("eval 'printf approved > {}'", approved_path.display());
        let approved_requests = Arc::new(AtomicUsize::new(0));
        let approve_proxy: Arc<dyn crate::approval::ApprovalProxy> =
            Arc::new(RecordingApprovalProxy {
                requests: approved_requests.clone(),
                approve: true,
            });
        let approved_call = make_tool_call("Bash", json!({"command": approved_command}));
        let approved_ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-forced"),
            root_session_id: None,
            tool_call_id: &approved_call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: true,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };
        let approved = crate::approval::with_approval_proxy(
            Some(approve_proxy),
            executor.execute_with_context(&approved_call, approved_ctx),
        )
        .await;

        assert!(
            approved.is_ok(),
            "parent approval must allow forced-ask execution under bypass: {approved:?}"
        );
        assert_eq!(approved_requests.load(Ordering::SeqCst), 1);
        assert_eq!(fs::read_to_string(approved_path).await.unwrap(), "approved");
    }

    #[tokio::test]
    async fn auto_executes_forced_ask_without_proxy_or_human_event() {
        let config = Arc::new(crate::permission::PermissionConfig::new());
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(BashTool::new())
            .expect("register Bash tool")
            .with_permission_checker(checker)
            .build();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auto-forced.txt");
        let command = format!("eval 'printf auto > {}'", path.display());
        let approval_requests = Arc::new(AtomicUsize::new(0));
        let proxy: Arc<dyn crate::approval::ApprovalProxy> = Arc::new(RecordingApprovalProxy {
            requests: approval_requests.clone(),
            approve: false,
        });
        let (event_tx, mut event_rx) = mpsc::channel(8);
        let call = make_tool_call("Bash", json!({"command": command}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-auto"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: Some(&event_tx),
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: true,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = crate::approval::with_approval_proxy(
            Some(proxy),
            executor.execute_with_context(&call, ctx),
        )
        .await;

        assert!(result.is_ok(), "Auto should execute directly: {result:?}");
        assert_eq!(fs::read_to_string(path).await.unwrap(), "auto");
        assert_eq!(approval_requests.load(Ordering::SeqCst), 0);
        assert!(
            event_rx.try_recv().is_err(),
            "Auto must not emit an interactive approval request"
        );
    }

    #[tokio::test]
    async fn read_only_child_checker_denies_every_side_effect_under_auto_and_bypass() {
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_mode(crate::permission::PermissionMode::Auto);
        let base: Arc<dyn crate::permission::PermissionChecker> = Arc::new(
            crate::permission::ConfigPermissionChecker::new(config.clone()),
        );
        let checker = Arc::new(crate::permission::ReadOnlyCommandChecker::new(base));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(BashTool::new())
            .expect("register Bash tool")
            .with_tool(WriteTool::new())
            .expect("register Write tool")
            .with_permission_checker(checker)
            .build();

        // Command-name validation is not an execution boundary: an ambient
        // PATH can resolve `pwd`, `cat`, or `git` to workspace-owned code.
        // Therefore even nominal inspection commands stop before Bash under
        // both zero-prompt modes.
        for (mode, bypass_permissions, auto_approve_permissions) in
            [("auto", false, true), ("bypass", true, false)]
        {
            for command in ["pwd", "cat Cargo.toml"] {
                let call = make_tool_call("Bash", json!({"command": command}));
                let session_id = format!("planner-no-shell-{mode}");
                let ctx = ToolExecutionContext {
                    executing_supervisor: None,
                    session_id: Some(&session_id),
                    root_session_id: None,
                    tool_call_id: &call.id,
                    event_tx: None,
                    available_tool_schemas: None,
                    bypass_permissions,
                    auto_approve_permissions,
                    plan_read_only: false,
                    can_async_resume: false,
                    bash_completion_sink: None,
                    pre_parsed_args: None,
                };
                let error = executor
                    .execute_with_context(&call, ctx)
                    .await
                    .expect_err("read-only children must not enter an ambient shell");
                assert!(error
                    .to_string()
                    .contains("Execute shell commands is disabled"));
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let direct_write_path = dir.path().join("planner-direct-write.txt");
        for (mode, bypass_permissions, auto_approve_permissions) in
            [("auto", false, true), ("bypass", true, false)]
        {
            let call = make_tool_call(
                "Write",
                json!({"file_path": direct_write_path, "content": "blocked"}),
            );
            let session_id = format!("planner-direct-write-{mode}");
            let ctx = ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some(&session_id),
                root_session_id: None,
                tool_call_id: &call.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions,
                auto_approve_permissions,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            };
            let error = executor
                .execute_with_context(&call, ctx)
                .await
                .expect_err("unadvertised direct writes must remain hard-denied");
            assert!(error
                .to_string()
                .contains("Write files to disk is disabled"));
            assert!(!direct_write_path.exists());
        }

        let path = dir.path().join("planner-mutation.txt");
        let command = format!("printf blocked > {}", path.display());
        for (session_id, bypass_permissions, auto_approve_permissions) in [
            ("planner-auto", false, true),
            ("planner-bypass", true, false),
        ] {
            let call = make_tool_call("Bash", json!({"command": command.clone()}));
            let ctx = ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some(session_id),
                root_session_id: None,
                tool_call_id: &call.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions,
                auto_approve_permissions,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            };

            let error = executor
                .execute_with_context(&call, ctx)
                .await
                .expect_err("Auto/Bypass must retain read-only child authority");

            assert!(error.to_string().contains("Read-only child"));
            assert!(!path.exists());
        }

        let delete_target = dir.path().join("planner-delete-target");
        fs::create_dir_all(&delete_target).await.unwrap();
        fs::write(delete_target.join("keep.txt"), "keep")
            .await
            .unwrap();
        let delete_command = format!("rm -rf {}", delete_target.display());
        for (session_id, bypass_permissions, auto_approve_permissions) in [
            ("planner-delete-auto", false, true),
            ("planner-delete-bypass", true, false),
        ] {
            let call = make_tool_call("Bash", json!({"command": delete_command.clone()}));
            let ctx = ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some(session_id),
                root_session_id: None,
                tool_call_id: &call.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions,
                auto_approve_permissions,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            };
            let error = executor
                .execute_with_context(&call, ctx)
                .await
                .expect_err("delete operations must remain hard-denied");
            assert!(error
                .to_string()
                .contains("Delete files or directories is disabled"));
            assert!(delete_target.exists());
        }

        let git_output = dir.path().join("planner-git-output.txt");
        let git_command = format!("git diff --output={}", git_output.display());
        for (session_id, bypass_permissions, auto_approve_permissions) in [
            ("planner-git-auto", false, true),
            ("planner-git-bypass", true, false),
        ] {
            let call = make_tool_call("Bash", json!({"command": git_command.clone()}));
            let ctx = ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some(session_id),
                root_session_id: None,
                tool_call_id: &call.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions,
                auto_approve_permissions,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            };

            let error = executor
                .execute_with_context(&call, ctx)
                .await
                .expect_err("git output flags must not bypass read-only child authority");

            assert!(error.to_string().contains("Read-only child"));
            assert!(!git_output.exists());
        }

        let find_output = dir.path().join("planner-find-output.txt");
        let denied_commands = [
            ("cargo", "cargo test --help".to_string(), None),
            (
                "git-signature-flag",
                "git log --no-ext-diff --no-textconv --show-signature -1".to_string(),
                None,
            ),
            (
                "git-signature-format",
                "git log --no-ext-diff --no-textconv --no-show-signature --format=%G? -1"
                    .to_string(),
                None,
            ),
            (
                "find",
                format!(
                    "find {} -fprint0 {}",
                    dir.path().display(),
                    find_output.display()
                ),
                Some(find_output.as_path()),
            ),
        ];
        for (command_kind, command, output_path) in denied_commands {
            for (mode, bypass_permissions, auto_approve_permissions) in
                [("auto", false, true), ("bypass", true, false)]
            {
                let call = make_tool_call("Bash", json!({"command": command.clone()}));
                let session_id = format!("planner-{command_kind}-{mode}");
                let ctx = ToolExecutionContext {
                    executing_supervisor: None,
                    session_id: Some(&session_id),
                    root_session_id: None,
                    tool_call_id: &call.id,
                    event_tx: None,
                    available_tool_schemas: None,
                    bypass_permissions,
                    auto_approve_permissions,
                    plan_read_only: false,
                    can_async_resume: false,
                    bash_completion_sink: None,
                    pre_parsed_args: None,
                };

                let error = executor
                    .execute_with_context(&call, ctx)
                    .await
                    .expect_err("executable/write-capable commands must remain denied");

                assert!(error.to_string().contains("Read-only child"));
                if let Some(path) = output_path {
                    assert!(!path.exists());
                }
            }
        }

        // Bash expands ANSI-C strings before argv reaches `find`; without the
        // lexical expansion gate this becomes `find <target> -delete` and
        // mutates the workspace even though the raw token is not `-delete`.
        let ansi_find_target = dir.path().join("planner-ansi-find-target");
        fs::create_dir_all(&ansi_find_target).await.unwrap();
        fs::write(ansi_find_target.join("keep.txt"), "keep")
            .await
            .unwrap();
        let ansi_find_command = format!(r"find {} $'-de'lete", ansi_find_target.display());
        for (mode, bypass_permissions, auto_approve_permissions) in
            [("auto", false, true), ("bypass", true, false)]
        {
            let call = make_tool_call("Bash", json!({"command": ansi_find_command.clone()}));
            let session_id = format!("planner-find-ansi-{mode}");
            let ctx = ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some(&session_id),
                root_session_id: None,
                tool_call_id: &call.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions,
                auto_approve_permissions,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            };

            let error = executor
                .execute_with_context(&call, ctx)
                .await
                .expect_err("ANSI-C expansion must remain denied before Bash execution");

            assert!(error.to_string().contains("Read-only child"));
            assert!(
                ansi_find_target.exists(),
                "the rejected command must not delete its target"
            );
        }
    }

    #[tokio::test]
    async fn test_explicit_deny_overrides_bypass() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("explicit-deny.txt");
        let path_str = path.to_str().unwrap();
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.add_rule(crate::permission::PermissionRule::new(
            crate::permission::PermissionType::WriteFile,
            path_str,
            false,
        ));
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = make_executor(Some(checker));
        let call = make_tool_call(
            "Write",
            json!({"file_path": path_str, "content": "blocked"}),
        );
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-explicit-deny"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: true,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = executor.execute_with_context(&call, ctx).await;
        assert!(
            matches!(result, Err(ToolError::Execution(ref message)) if message.contains("explicit policy")),
            "explicit deny must beat bypass: {result:?}"
        );
        assert!(!path.exists());
    }

    #[tokio::test]
    async fn test_explicit_delete_deny_overrides_bypass() {
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.add_rule(crate::permission::PermissionRule::new(
            crate::permission::PermissionType::DeleteOperation,
            "rm child-to-preserve",
            false,
        ));
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(BashTool::new())
            .expect("register Bash tool")
            .with_permission_checker(checker)
            .build();
        let call = make_tool_call("Bash", json!({"command": "rm child-to-preserve"}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-explicit-delete-deny"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: true,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = executor.execute_with_context(&call, ctx).await;
        assert!(
            matches!(result, Err(ToolError::Execution(ref message)) if message.contains("explicit policy")),
            "explicit delete deny must beat bypass: {result:?}"
        );
    }

    #[tokio::test]
    async fn plan_auto_denies_mutation_but_allows_read_without_a_checker() {
        let executor = BuiltinToolExecutor::new();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("plan-auto.txt");
        let write = make_tool_call(
            "Write",
            json!({"file_path": path, "content": "must not run"}),
        );
        let write_ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("plan-auto"),
            root_session_id: None,
            tool_call_id: &write.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: true,
            plan_read_only: true,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };
        let denied = executor.execute_with_context(&write, write_ctx).await;
        assert!(matches!(
            denied,
            Err(ToolError::Execution(ref message)) if message.contains("Plan mode")
        ));
        assert!(tokio::fs::metadata(&path).await.is_err());

        tokio::fs::write(&path, "readable").await.unwrap();
        let read = make_tool_call("Read", json!({"file_path": path}));
        let read_ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("plan-auto"),
            root_session_id: None,
            tool_call_id: &read.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: true,
            plan_read_only: true,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };
        let allowed = executor
            .execute_with_context(&read, read_ctx)
            .await
            .unwrap();
        assert!(allowed.success);
    }

    #[tokio::test]
    async fn auto_request_permissions_fails_without_creating_a_pause() {
        let executor = BuiltinToolExecutor::new();
        let (event_tx, mut event_rx) = mpsc::channel(4);
        let call = make_tool_call("request_permissions", json!({}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("auto-no-prompt"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: Some(&event_tx),
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: true,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = executor.execute_with_context_outcome(&call, ctx).await;
        assert!(matches!(
            result,
            Err(ToolError::Execution(ref message)) if message.contains("cannot request expanded permissions")
        ));
        assert!(event_rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn interactive_gate_returns_synthesized_approval_pause() {
        // With an event sink present, a forced-ask rule that yields
        // `ConfirmationRequired` must resolve to the synthesized "awaiting
        // approval" PAUSE result (a `Completed` result tagged
        // `display_preference = "request_permissions"`) — NOT an error — so the
        // engine turns it into a clarification pause. This locks in the
        // interactive-sink path that the `check_permissions_for` extraction must
        // preserve as `Ok(Some(outcome))` rather than collapse to an `Err`.
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_ask_rules(["Write(/etc/**)".to_string()]);
        config.register_session_workspace("s-interactive", "/workspace/project");
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = make_executor(Some(checker));

        let (tx, mut rx) = mpsc::channel(8);
        let call = make_tool_call(
            "Write",
            json!({"file_path": "/etc/gated.conf", "content": "x"}),
        );
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-interactive"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: Some(&tx),
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let result = executor
            .execute_with_context(&call, ctx)
            .await
            .expect("interactive gate should pause (Ok), not error");

        assert_eq!(
            result.display_preference.as_deref(),
            Some("request_permissions"),
            "interactive gate must return the request_permissions pause result"
        );
        assert!(result.result.contains("awaiting_permission_approval"));
        let payload: serde_json::Value = serde_json::from_str(&result.result).expect("payload");
        let request = &payload["permission_request"];
        assert_eq!(request["request_id"], call.id);
        assert_eq!(request["session_id"], "s-interactive");
        assert_eq!(request["workspace_path"], "/workspace/project");
        assert_eq!(request["reason_code"], "configured_always_ask");
        assert_eq!(
            request["allowed_decisions"],
            json!(["allow_once", "deny_once"])
        );
        assert_eq!(payload["options"], json!(["Approve", "Deny"]));
        assert!(fs::metadata("/etc/gated.conf").await.is_err());

        let ev = rx.recv().await.expect("approval event should be emitted");
        assert!(
            matches!(ev, AgentEvent::ToolApprovalRequested { tool_name, .. } if tool_name == "Write")
        );
    }

    #[tokio::test]
    async fn proactive_permission_batch_uses_typed_remembered_scopes_then_completes() {
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_session_workspace("proactive-session", Some("/workspace/project".to_string()));
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(
            config.clone(),
        ));
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(crate::tools::RequestPermissionsTool::new())
            .expect("register request_permissions")
            .with_permission_checker(checker)
            .build();
        let call = make_tool_call(
            "request_permissions",
            json!({
                "reason": "Deploy the service",
                "permissions": [
                    {
                        "type": "execute_command",
                        "resource": "docker compose up -d"
                    },
                    {
                        "type": "http_request",
                        "resource": "registry.example.com"
                    }
                ]
            }),
        );
        let (event_tx, _event_rx) = mpsc::channel(8);

        let first = executor
            .execute_with_context(
                &call,
                ToolExecutionContext {
                    executing_supervisor: None,
                    session_id: Some("proactive-session"),
                    root_session_id: None,
                    tool_call_id: &call.id,
                    event_tx: Some(&event_tx),
                    available_tool_schemas: None,
                    bypass_permissions: false,
                    auto_approve_permissions: false,
                    plan_read_only: false,
                    can_async_resume: false,
                    bash_completion_sink: None,
                    pre_parsed_args: None,
                },
            )
            .await
            .expect("first batch context pauses");
        let first_payload: serde_json::Value = serde_json::from_str(&first.result).unwrap();
        let first_request = &first_payload["permission_request"];
        assert_eq!(first_request["resource"], "docker compose up -d");
        assert!(!first_request["allowed_decisions"]
            .as_array()
            .unwrap()
            .contains(&json!("allow_once")));
        assert!(first_request["allowed_decisions"]
            .as_array()
            .unwrap()
            .contains(&json!("allow_session")));
        let first_matcher: crate::permission::PermissionMatcher =
            serde_json::from_value(first_request["suggested_matchers"][0].clone()).unwrap();
        config
            .grant_typed_scoped_session_permission(
                "proactive-session",
                crate::permission::PermissionType::ExecuteCommand,
                first_matcher,
            )
            .unwrap();

        let second = executor
            .execute_with_context(
                &call,
                ToolExecutionContext {
                    executing_supervisor: None,
                    session_id: Some("proactive-session"),
                    root_session_id: None,
                    tool_call_id: &call.id,
                    event_tx: Some(&event_tx),
                    available_tool_schemas: None,
                    bypass_permissions: false,
                    auto_approve_permissions: false,
                    plan_read_only: false,
                    can_async_resume: false,
                    bash_completion_sink: None,
                    pre_parsed_args: None,
                },
            )
            .await
            .expect("second batch context pauses");
        let second_payload: serde_json::Value = serde_json::from_str(&second.result).unwrap();
        let second_request = &second_payload["permission_request"];
        assert_eq!(second_request["resource"], "registry.example.com");
        let second_matcher: crate::permission::PermissionMatcher =
            serde_json::from_value(second_request["suggested_matchers"][0].clone()).unwrap();
        config
            .grant_typed_scoped_session_permission(
                "proactive-session",
                crate::permission::PermissionType::HttpRequest,
                second_matcher,
            )
            .unwrap();

        let completed = executor
            .execute_with_context(
                &call,
                ToolExecutionContext {
                    executing_supervisor: None,
                    session_id: Some("proactive-session"),
                    root_session_id: None,
                    tool_call_id: &call.id,
                    event_tx: Some(&event_tx),
                    available_tool_schemas: None,
                    bypass_permissions: false,
                    auto_approve_permissions: false,
                    plan_read_only: false,
                    can_async_resume: false,
                    bash_completion_sink: None,
                    pre_parsed_args: None,
                },
            )
            .await
            .expect("all authorized contexts complete the tool");
        assert!(completed.display_preference.is_none());
        let completed_payload: serde_json::Value = serde_json::from_str(&completed.result).unwrap();
        assert_eq!(completed_payload["status"], "permissions_authorized");
        assert_eq!(
            completed_payload["permissions"].as_array().unwrap().len(),
            2
        );
    }

    #[tokio::test]
    async fn workspace_permission_scope_uses_only_registered_session_identity() {
        let registered = Arc::new(crate::permission::PermissionConfig::new());
        registered.register_session_workspace("registered", "/workspace/authoritative");
        let registered_executor = make_executor(Some(Arc::new(
            crate::permission::ConfigPermissionChecker::new(registered.clone()),
        )));

        let first = permission_request_payload(
            &registered_executor,
            "registered",
            json!({
                "file_path": "/tmp/first.txt",
                "content": "x",
                "cwd": "/model/chosen-a",
                "workspace_path": "/model/chosen-b"
            }),
        )
        .await;
        let second = permission_request_payload(
            &registered_executor,
            "registered",
            json!({
                "file_path": "/tmp/second.txt",
                "content": "x",
                "cwd": "/model/chosen-c"
            }),
        )
        .await;
        for payload in [&first, &second] {
            let request = &payload["permission_request"];
            assert_eq!(request["workspace_path"], "/workspace/authoritative");
            assert!(request["allowed_decisions"]
                .as_array()
                .unwrap()
                .contains(&json!("allow_workspace")));
        }

        registered.set_session_workspace("registered", None);
        let unbound = permission_request_payload(
            &registered_executor,
            "registered",
            json!({
                "file_path": "/tmp/unbound.txt",
                "content": "x",
                "cwd": "/workspace/authoritative"
            }),
        )
        .await;
        assert!(unbound["permission_request"]["workspace_path"].is_null());
        assert!(!unbound["permission_request"]["allowed_decisions"]
            .as_array()
            .unwrap()
            .contains(&json!("allow_workspace")));

        registered.set_session_workspace("registered", Some("/workspace/rebound".to_string()));
        let rebound = permission_request_payload(
            &registered_executor,
            "registered",
            json!({
                "file_path": "/tmp/rebound.txt",
                "content": "x",
                "workspace_path": "/workspace/authoritative"
            }),
        )
        .await;
        assert_eq!(
            rebound["permission_request"]["workspace_path"],
            "/workspace/rebound"
        );

        let unregistered = Arc::new(crate::permission::PermissionConfig::new());
        let unregistered_executor = make_executor(Some(Arc::new(
            crate::permission::ConfigPermissionChecker::new(unregistered),
        )));
        let payload = permission_request_payload(
            &unregistered_executor,
            "unregistered",
            json!({
                "file_path": "/tmp/unregistered.txt",
                "content": "x",
                "cwd": "/model/chosen",
                "workspace_path": "/also/model/chosen"
            }),
        )
        .await;
        let request = &payload["permission_request"];
        assert!(request["workspace_path"].is_null());
        assert!(!request["allowed_decisions"]
            .as_array()
            .unwrap()
            .contains(&json!("allow_workspace")));
    }

    #[tokio::test]
    async fn check_permissions_for_returns_none_when_permitted() {
        // A tool with no matching gate (Read, no checker rule) passes the gate:
        // `check_permissions_for` returns `Ok(None)` so the caller runs the tool.
        let executor = make_executor(None);
        let call = make_tool_call("Read", json!({"file_path": "/tmp/whatever"}));
        let ctx = ToolExecutionContext::none(&call.id);
        let decision = executor
            .check_permissions_for(&call, &ctx)
            .await
            .expect("no checker means no gate");
        assert!(decision.is_none(), "no checker must yield Ok(None)");
    }

    // ---- Phase 2: cross-process approval proxy ----------------------------

    struct HostStub {
        approve: bool,
    }

    #[async_trait]
    impl crate::approval::ApprovalProxy for HostStub {
        async fn request_approval(&self, _ask: crate::approval::ApprovalAsk) -> bool {
            self.approve
        }
    }

    #[tokio::test]
    async fn approval_proxy_grant_lets_gated_tool_proceed() {
        // A subagent worker installs an ApprovalProxy for its run. A forced-ask
        // rule with NO event sink would otherwise fail closed; with the host
        // proxy granting, the executor treats the context as approved and the
        // tool proceeds inline (no suspend, no synthetic pause).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("approved.txt");
        let path_str = path.to_str().unwrap().to_string();
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_ask_rules([format!("Write({}/**)", dir.path().to_str().unwrap())]);
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = make_executor(Some(checker));

        let call = make_tool_call("Write", json!({"file_path": path_str, "content": "ok"}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-worker"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let proxy: Arc<dyn crate::approval::ApprovalProxy> = Arc::new(HostStub { approve: true });
        let result = crate::approval::with_approval_proxy(
            Some(proxy),
            executor.execute_with_context(&call, ctx),
        )
        .await;

        assert!(
            result.is_ok(),
            "host grant should let the write through: {result:?}"
        );
        assert_eq!(fs::read_to_string(&path).await.unwrap(), "ok");
    }

    #[tokio::test]
    async fn approval_proxy_deny_fails_gated_tool_closed() {
        // With the host proxy denying, the gated tool fails closed and the side
        // effect never happens.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("denied.txt");
        let path_str = path.to_str().unwrap().to_string();
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_ask_rules([format!("Write({}/**)", dir.path().to_str().unwrap())]);
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let executor = make_executor(Some(checker));

        let call = make_tool_call("Write", json!({"file_path": path_str, "content": "nope"}));
        let ctx = ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-worker"),
            root_session_id: None,
            tool_call_id: &call.id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: None,
        };

        let proxy: Arc<dyn crate::approval::ApprovalProxy> = Arc::new(HostStub { approve: false });
        let result = crate::approval::with_approval_proxy(
            Some(proxy),
            executor.execute_with_context(&call, ctx),
        )
        .await;

        assert!(
            matches!(result, Err(ToolError::Execution(ref m)) if m.contains("denied by host")),
            "host deny should fail the tool closed: {result:?}"
        );
        assert!(fs::metadata(&path).await.is_err());
    }

    #[tokio::test]
    async fn tool_can_stream_events_via_execute_with_context() {
        struct StreamingTool;

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

            fn description(&self) -> &str {
                "streams one token"
            }

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

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

        let executor = BuiltinToolExecutor::new();
        executor
            .register_tool(StreamingTool)
            .expect("register streaming tool");

        let (tx, mut rx) = mpsc::channel(8);
        let call = make_tool_call("streaming_tool", json!({}));

        let result = executor
            .execute_with_context(
                &call,
                ToolExecutionContext {
                    executing_supervisor: None,
                    session_id: Some("s1"),
                    root_session_id: None,
                    tool_call_id: &call.id,
                    event_tx: Some(&tx),
                    available_tool_schemas: None,
                    bypass_permissions: false,
                    auto_approve_permissions: false,
                    plan_read_only: false,
                    can_async_resume: false,
                    bash_completion_sink: None,
                    pre_parsed_args: None,
                },
            )
            .await
            .expect("execute tool");

        assert!(result.success);
        assert_eq!(result.result, "ok");

        let ev = rx.recv().await.expect("expected streamed event");
        assert!(
            matches!(ev, AgentEvent::ToolToken { tool_call_id, content } if tool_call_id == "call_1" && content == "stream")
        );
    }

    #[tokio::test]
    async fn removed_legacy_tools_return_not_found() {
        let executor = BuiltinToolExecutor::new();

        for legacy in ["claude_code", "search_in_file", "search_in_project"] {
            let call = make_tool_call(legacy, json!({}));
            let result = executor.execute(&call).await;
            assert!(matches!(result, Err(ToolError::NotFound(_))));
        }
    }

    #[tokio::test]
    async fn executor_prefers_exact_tool_name_before_builtin_alias() {
        struct CustomSpawnSessionTool;

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

            fn description(&self) -> &str {
                "custom tool for regression coverage"
            }

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

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

        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(CustomSpawnSessionTool)
            .expect("register custom spawn_session tool")
            .build();

        let call = make_tool_call("spawn_session", json!({}));
        let result = executor.execute(&call).await.expect("execute custom tool");
        assert!(result.success);
        assert_eq!(result.result, "custom-spawn-session");
    }

    struct ExactRoutingTool {
        name: &'static str,
        label: &'static str,
        args_sensitive: bool,
    }

    #[async_trait]
    impl Tool for ExactRoutingTool {
        fn name(&self) -> &str {
            self.name
        }

        fn description(&self) -> &str {
            "exact routing regression tool"
        }

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

        fn classify(&self, args: &serde_json::Value) -> bamboo_agent_core::ToolClass {
            let has_builtin_normalized_arg = ["file_path", "command", "pattern"]
                .iter()
                .any(|key| args.get(key).is_some());
            if self.args_sensitive && !has_builtin_normalized_arg {
                bamboo_agent_core::ToolClass::READONLY_PARALLEL
            } else {
                bamboo_agent_core::ToolClass::MUTATING_SERIAL
            }
        }

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

    #[tokio::test]
    async fn executor_preserves_namespaced_exact_identity_and_unqualified_collision() {
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(ExactRoutingTool {
                name: "a::custom_tool",
                label: "namespaced",
                args_sensitive: false,
            })
            .expect("register namespaced tool")
            .with_tool(ExactRoutingTool {
                name: "custom_tool",
                label: "unqualified",
                args_sensitive: false,
            })
            .expect("register unqualified tool")
            .build();

        assert!(executor.owns_exact_tool("a::custom_tool"));
        assert!(executor.owns_exact_tool("custom_tool"));
        assert!(!executor.owns_exact_tool("A::custom_tool"));
        let names: Vec<String> = executor
            .list_tools()
            .into_iter()
            .map(|schema| schema.function.name)
            .collect();
        assert!(names.contains(&"a::custom_tool".to_string()));
        assert!(names.contains(&"custom_tool".to_string()));

        let namespaced = executor
            .execute(&make_tool_call("a::custom_tool", json!({})))
            .await
            .expect("execute namespaced exact tool");
        let unqualified = executor
            .execute(&make_tool_call("custom_tool", json!({})))
            .await
            .expect("execute unqualified exact tool");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&namespaced.result).unwrap()["label"],
            "namespaced"
        );
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&unqualified.result).unwrap()["label"],
            "unqualified"
        );
    }

    #[tokio::test]
    async fn exact_canonical_shadows_do_not_inherit_builtin_argument_provenance() {
        let executor = BuiltinToolExecutorBuilder::new()
            .with_tool(ExactRoutingTool {
                name: "Read",
                label: "exact-read",
                args_sensitive: true,
            })
            .expect("register exact Read shadow")
            .with_tool(ExactRoutingTool {
                name: "Write",
                label: "exact-write",
                args_sensitive: true,
            })
            .expect("register exact Write shadow")
            .with_tool(ExactRoutingTool {
                name: "Edit",
                label: "exact-edit",
                args_sensitive: true,
            })
            .expect("register exact Edit shadow")
            .with_tool(ExactRoutingTool {
                name: "Bash",
                label: "exact-bash",
                args_sensitive: true,
            })
            .expect("register exact Bash shadow")
            .with_tool(ExactRoutingTool {
                name: "Glob",
                label: "exact-glob",
                args_sensitive: true,
            })
            .expect("register exact Glob shadow")
            .with_default_tools()
            .build();

        let cases = [
            ("Read", json!({"path": "/tmp/custom-read"}), "file_path"),
            ("Write", json!({"path": "/tmp/custom-write"}), "file_path"),
            ("Edit", json!({"path": "/tmp/custom-edit"}), "file_path"),
            ("Bash", json!({"cmd": "custom-command"}), "command"),
            (
                "Glob",
                json!({"path": "/tmp/custom-glob", "recursive": true}),
                "pattern",
            ),
        ];

        for (name, args, normalized_key) in cases {
            let call = make_tool_call(name, args.clone());
            assert_eq!(
                executor.call_mutability(&call),
                crate::ToolMutability::ReadOnly,
                "custom {name} classification must see the original args"
            );
            assert!(
                executor.call_concurrency_safe(&call),
                "custom {name} classification must remain parallel-safe"
            );

            let result = executor
                .execute(&call)
                .await
                .unwrap_or_else(|error| panic!("execute custom {name}: {error}"));
            let result: serde_json::Value = serde_json::from_str(&result.result).unwrap();
            assert_eq!(result["args"], args, "custom {name} args changed");
            assert!(result["args"].get(normalized_key).is_none());
        }

        // Exercise the permission entry point with exact canonical shadows for
        // which the central policy has no name-based write/execute rule. The
        // same raw args must reach classification and invocation even when a
        // checker is installed.
        let permission_executor = BuiltinToolExecutorBuilder::new()
            .with_tool(ExactRoutingTool {
                name: "Read",
                label: "permission-read",
                args_sensitive: true,
            })
            .expect("register permission-aware Read shadow")
            .with_tool(ExactRoutingTool {
                name: "Glob",
                label: "permission-glob",
                args_sensitive: true,
            })
            .expect("register permission-aware Glob shadow")
            .with_default_tools()
            .with_permission_checker(Arc::new(crate::permission::AllowAllPermissionChecker))
            .build();
        for (name, args) in [
            ("Read", json!({"path": "/tmp/permission-read"})),
            (
                "Glob",
                json!({"path": "/tmp/permission-glob", "recursive": true}),
            ),
        ] {
            let call = make_tool_call(name, args.clone());
            let ctx = ToolExecutionContext::none(&call.id);
            assert!(permission_executor
                .check_permissions_for(&call, &ctx)
                .await
                .expect("permission check")
                .is_none());
            assert_eq!(
                permission_executor.call_mutability(&call),
                crate::ToolMutability::ReadOnly
            );
            assert!(permission_executor.call_concurrency_safe(&call));
            let result = permission_executor.execute(&call).await.unwrap();
            let result: serde_json::Value = serde_json::from_str(&result.result).unwrap();
            assert_eq!(result["args"], args);
        }
    }

    #[tokio::test]
    async fn exact_apply_patch_keeps_original_args_and_classification() {
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Edit")
            .expect("register builtin Edit")
            .with_tool(ExactRoutingTool {
                name: "apply_patch",
                label: "exact-apply-patch",
                args_sensitive: true,
            })
            .expect("register exact apply_patch shadow")
            .build();
        let call = make_tool_call("apply_patch", json!({"path": "/tmp/exact-shadow"}));

        let (mutability, parallel_safe) = executor.call_parallel_classification(&call);
        assert_eq!(mutability, crate::ToolMutability::ReadOnly);
        assert!(parallel_safe);

        let result = executor.execute(&call).await.expect("execute exact shadow");
        let result: serde_json::Value = serde_json::from_str(&result.result).unwrap();
        assert_eq!(result["label"], "exact-apply-patch");
        assert_eq!(result["args"]["path"], "/tmp/exact-shadow");
        assert!(result["args"].get("file_path").is_none());
    }

    #[tokio::test]
    async fn exact_permission_seam_preserves_default_apply_patch_builtin_provenance() {
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Edit")
            .expect("register builtin Edit")
            .with_permission_checker(Arc::new(crate::permission::AllowAllPermissionChecker))
            .build();
        let raw_args = json!({
            "path": "/tmp/exact-permission-apply-patch.txt",
            "old_string": "before",
            "new_string": "after"
        });
        let call = make_tool_call("default::apply_patch", raw_args.clone());
        let ctx = ToolExecutionContext {
            pre_parsed_args: Some(&raw_args),
            ..ToolExecutionContext::none(&call.id)
        };

        assert!(executor
            .check_permissions_for_exact(&call, "Edit", &ctx)
            .await
            .expect("normalized builtin permission check")
            .is_none());
        assert_eq!(call.function.name, "default::apply_patch");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&call.function.arguments).unwrap(),
            raw_args
        );
    }

    #[tokio::test]
    async fn unshadowed_alias_and_namespace_keep_legacy_argument_compatibility() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("legacy-alias.txt");
        fs::write(&path, "before").await.unwrap();
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Edit")
            .expect("register builtin Edit")
            .with_permission_checker(Arc::new(crate::permission::AllowAllPermissionChecker))
            .build();

        let result = executor
            .execute(&make_tool_call(
                "default::apply_patch",
                json!({
                    "path": path,
                    "old_string": "before",
                    "new_string": "after"
                }),
            ))
            .await
            .expect("execute unshadowed alias");
        assert!(result.success);
        assert_eq!(fs::read_to_string(path).await.unwrap(), "after");
    }

    // ---- issue #106: parse tool args once on the execute path -------------

    /// A tool that echoes back the `v` field of the args it was invoked with, so
    /// a test can observe *which* parsed value reached the tool.
    struct EchoArgsTool;

    #[async_trait]
    impl Tool for EchoArgsTool {
        fn name(&self) -> &str {
            "echo_args"
        }
        fn description(&self) -> &str {
            "echoes the `v` arg"
        }
        fn parameters_schema(&self) -> serde_json::Value {
            json!({"type":"object","properties":{"v":{"type":"string"}}})
        }
        async fn invoke(
            &self,
            args: serde_json::Value,
            _ctx: ToolCtx,
        ) -> Result<ToolOutcome, ToolError> {
            let v = args
                .get("v")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("<none>")
                .to_string();
            Ok(ToolOutcome::Completed(ToolResult {
                success: true,
                result: v,
                display_preference: None,
                images: Vec::new(),
            }))
        }
    }

    fn ctx_with_pre_parsed<'a>(
        call_id: &'a str,
        pre_parsed: Option<&'a serde_json::Value>,
    ) -> ToolExecutionContext<'a> {
        ToolExecutionContext {
            executing_supervisor: None,
            session_id: Some("s-106"),
            root_session_id: None,
            tool_call_id: call_id,
            event_tx: None,
            available_tool_schemas: None,
            bypass_permissions: false,
            auto_approve_permissions: false,
            plan_read_only: false,
            can_async_resume: false,
            bash_completion_sink: None,
            pre_parsed_args: pre_parsed,
        }
    }

    #[tokio::test]
    async fn execute_with_context_reuses_pre_parsed_args_without_reparsing() {
        // The raw `arguments` string and the threaded `pre_parsed_args` Value
        // deliberately disagree. If the executor honored the contract (parse
        // once at the dispatch site, reuse downstream), the tool sees the
        // pre-parsed value; if it re-parsed the raw string it would see "raw".
        // This is the load-bearing proof that the second parse was eliminated.
        let executor = BuiltinToolExecutor::new();
        executor.register_tool(EchoArgsTool).expect("register echo");

        let call = make_tool_call("echo_args", json!({"v": "raw"}));
        let pre_parsed = json!({"v": "preparsed"});
        let ctx = ctx_with_pre_parsed(&call.id, Some(&pre_parsed));

        let result = executor
            .execute_with_context(&call, ctx)
            .await
            .expect("execute echo tool");
        assert_eq!(
            result.result, "preparsed",
            "executor must reuse pre_parsed_args, not re-parse the raw string"
        );
    }

    #[tokio::test]
    async fn execute_with_context_parses_raw_when_no_pre_parsed_args() {
        // Without a threaded value (the `execute` entry point / tests / a loop
        // that parsed with a different parser), the executor falls back to
        // parsing the raw string exactly as before — behavior preserved.
        let executor = BuiltinToolExecutor::new();
        executor.register_tool(EchoArgsTool).expect("register echo");

        let call = make_tool_call("echo_args", json!({"v": "raw"}));
        let ctx = ctx_with_pre_parsed(&call.id, None);

        let result = executor
            .execute_with_context(&call, ctx)
            .await
            .expect("execute echo tool");
        assert_eq!(
            result.result, "raw",
            "without pre_parsed_args the executor parses the raw string as before"
        );
    }

    #[tokio::test]
    async fn execute_with_context_malformed_args_repair_unchanged_without_pre_parsed() {
        // Malformed (truncated) JSON must still be auto-repaired by the
        // fallback parse when no pre-parsed value is threaded — the existing
        // error/leniency behavior is untouched by the dedup.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("recovered-no-preparsed.txt");
        let malformed_args = format!(
            r#"{{"file_path":"{}","content":"recovered content""#,
            path.display()
        );

        let executor = BuiltinToolExecutor::new();
        let call = make_tool_call_with_raw_args("Write", &malformed_args);
        let ctx = ctx_with_pre_parsed(&call.id, None);

        let result = executor
            .execute_with_context(&call, ctx)
            .await
            .expect("truncated JSON should be auto-repaired");
        assert!(result.success);
        let written = fs::read_to_string(&path).await.expect("file written");
        assert_eq!(written, "recovered content");
    }

    #[tokio::test]
    async fn successful_write_emits_one_bounded_file_changed_event() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("write-event.txt");
        let path_string = path.to_string_lossy().into_owned();
        let padded_path = format!("  {path_string}  ");
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Write")
            .unwrap()
            .with_tool_event_publisher(recorder.clone())
            .build();
        let call = make_tool_call_with_id(
            "write-call",
            "Write",
            json!({"file_path": padded_path, "content": "written"}),
        );

        let result = executor
            .execute_with_context(
                &call,
                tool_event_context(&call, Some("write-session"), Some("write-root-session")),
            )
            .await
            .unwrap();

        assert!(result.success);
        assert_eq!(fs::read_to_string(path).await.unwrap(), "written");
        assert_single_file_changed(
            &recorder,
            "write-session",
            "write-root-session",
            "Write",
            "write-call",
            &path_string,
        );
    }

    #[tokio::test]
    async fn successful_edit_emits_one_bounded_file_changed_event() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("edit-event.txt");
        fs::write(&path, "before\n").await.unwrap();
        let path_string = path.to_string_lossy().into_owned();
        let padded_path = format!(" {path_string} ");
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutor::new().with_tool_event_publisher(recorder.clone());
        let read =
            make_tool_call_with_id("edit-read-call", "Read", json!({"file_path": padded_path}));
        executor
            .execute_with_context(
                &read,
                tool_event_context(&read, Some("edit-session"), Some("edit-root-session")),
            )
            .await
            .unwrap();
        assert!(recorder.try_snapshot().unwrap().is_empty());

        let edit = make_tool_call_with_id(
            "edit-call",
            "Edit",
            json!({
                "file_path": format!(" {path_string} "),
                "old_string": "before",
                "new_string": "after"
            }),
        );
        let result = executor
            .execute_with_context(
                &edit,
                tool_event_context(&edit, Some("edit-session"), Some("edit-root-session")),
            )
            .await
            .unwrap();

        assert!(result.success);
        assert_eq!(fs::read_to_string(path).await.unwrap(), "after\n");
        assert_single_file_changed(
            &recorder,
            "edit-session",
            "edit-root-session",
            "Edit",
            "edit-call",
            &path_string,
        );
    }

    #[tokio::test]
    async fn successful_apply_patch_alias_emits_canonical_edit_with_original_call_id() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("apply-patch-event.txt");
        fs::write(&path, "alpha\nbeta\n").await.unwrap();
        let path_string = path.to_string_lossy().into_owned();
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutor::new().with_tool_event_publisher(recorder.clone());
        let read = make_tool_call_with_id(
            "apply-patch-read-call",
            "Read",
            json!({"file_path": path_string}),
        );
        executor
            .execute_with_context(
                &read,
                tool_event_context(&read, Some("alias-session"), Some("alias-root-session")),
            )
            .await
            .unwrap();

        let edit = make_tool_call_with_id(
            "model-original-alias-call",
            "apply_patch",
            json!({
                "path": format!("  {path_string}  "),
                "old_string": "beta",
                "new_string": "BETA"
            }),
        );
        let result = executor
            .execute_with_context(
                &edit,
                tool_event_context(&edit, Some("alias-session"), Some("alias-root-session")),
            )
            .await
            .unwrap();

        assert!(result.success);
        assert_eq!(fs::read_to_string(path).await.unwrap(), "alpha\nBETA\n");
        assert_single_file_changed(
            &recorder,
            "alias-session",
            "alias-root-session",
            "Edit",
            "model-original-alias-call",
            &path_string,
        );
    }

    #[tokio::test]
    async fn successful_notebook_edit_emits_one_bounded_file_changed_event() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("notebook-event.ipynb");
        fs::write(
            &path,
            r#"{"cells":[],"metadata":{},"nbformat":4,"nbformat_minor":5}"#,
        )
        .await
        .unwrap();
        let path_string = path.to_string_lossy().into_owned();
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("NotebookEdit")
            .unwrap()
            .with_tool_event_publisher(recorder.clone())
            .build();
        let call = make_tool_call_with_id(
            "notebook-call",
            "NotebookEdit",
            json!({
                "notebook_path": format!(" {path_string} "),
                "new_source": "print('hello')",
                "cell_type": "code",
                "edit_mode": "insert"
            }),
        );

        let result = executor
            .execute_with_context(
                &call,
                tool_event_context(
                    &call,
                    Some("notebook-session"),
                    Some("notebook-root-session"),
                ),
            )
            .await
            .unwrap();

        assert!(result.success);
        assert_single_file_changed(
            &recorder,
            "notebook-session",
            "notebook-root-session",
            "NotebookEdit",
            "notebook-call",
            &path_string,
        );
    }

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

        let workspace = tempfile::tempdir().unwrap();
        let external = tempfile::tempdir().unwrap();
        let linked_dir = workspace.path().join("linked");
        symlink(external.path(), &linked_dir).unwrap();
        let target = linked_dir.join("write.txt");
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Write")
            .unwrap()
            .with_tool_event_publisher(recorder.clone())
            .build();
        let call = make_tool_call_with_id(
            "symlink-write",
            "Write",
            json!({"file_path": target, "content": "must-not-write"}),
        );

        let result = executor
            .execute_with_context(
                &call,
                tool_event_context(&call, Some("symlink-session"), Some("symlink-root")),
            )
            .await;
        assert!(
            result.is_err() || result.as_ref().is_ok_and(|result| !result.success),
            "Write must fail closed through an intermediate symlink"
        );
        assert!(!external.path().join("write.txt").exists());
        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

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

        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.txt");
        let linked = dir.path().join("linked.txt");
        fs::write(&real, "before\n").await.unwrap();
        symlink(&real, &linked).unwrap();
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutor::new().with_tool_event_publisher(recorder.clone());
        let read =
            make_tool_call_with_id("symlink-edit-read", "Read", json!({"file_path": linked}));
        let _ = executor
            .execute_with_context(
                &read,
                tool_event_context(&read, Some("symlink-session"), Some("symlink-root")),
            )
            .await;
        let edit = make_tool_call_with_id(
            "symlink-edit",
            "Edit",
            json!({
                "file_path": linked,
                "old_string": "before",
                "new_string": "after"
            }),
        );

        let result = executor
            .execute_with_context(
                &edit,
                tool_event_context(&edit, Some("symlink-session"), Some("symlink-root")),
            )
            .await;
        assert!(
            result.is_err() || result.as_ref().is_ok_and(|result| !result.success),
            "Edit must fail closed for a symlinked final file"
        );
        assert_eq!(fs::read_to_string(&real).await.unwrap(), "before\n");
        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

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

        let workspace = tempfile::tempdir().unwrap();
        let external = tempfile::tempdir().unwrap();
        let real_notebook = external.path().join("real.ipynb");
        let original = r#"{"cells":[],"metadata":{},"nbformat":4,"nbformat_minor":5}"#;
        fs::write(&real_notebook, original).await.unwrap();
        let linked_dir = workspace.path().join("linked");
        symlink(external.path(), &linked_dir).unwrap();
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("NotebookEdit")
            .unwrap()
            .with_tool_event_publisher(recorder.clone())
            .build();
        let call = make_tool_call_with_id(
            "symlink-notebook",
            "NotebookEdit",
            json!({
                "notebook_path": linked_dir.join("real.ipynb"),
                "new_source": "print('must not write')",
                "cell_type": "code",
                "edit_mode": "insert"
            }),
        );

        let result = executor
            .execute_with_context(
                &call,
                tool_event_context(&call, Some("symlink-session"), Some("symlink-root")),
            )
            .await;
        assert!(
            result.is_err() || result.as_ref().is_ok_and(|result| !result.success),
            "NotebookEdit must fail closed through an intermediate symlink"
        );
        assert_eq!(fs::read_to_string(&real_notebook).await.unwrap(), original);
        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

    #[tokio::test]
    async fn failed_and_non_successful_mutations_emit_no_event() {
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Write")
            .unwrap()
            .with_tool_event_publisher(recorder.clone())
            .build();
        let failed = make_tool_call_with_id(
            "failed-write-call",
            "Write",
            json!({"file_path": "relative.txt", "content": "never"}),
        );
        assert!(executor
            .execute_with_context(
                &failed,
                tool_event_context(
                    &failed,
                    Some("failure-session"),
                    Some("failure-root-session"),
                ),
            )
            .await
            .is_err());
        assert!(recorder.try_snapshot().unwrap().is_empty());

        let completed_false = marked_stub_write_executor(false, recorder.clone());
        let call = make_tool_call_with_id(
            "completed-false-call",
            "Write",
            json!({"file_path": "/valid/event/path.txt"}),
        );
        let result = completed_false
            .execute_with_context(
                &call,
                tool_event_context(&call, Some("failure-session"), Some("failure-root-session")),
            )
            .await
            .unwrap();
        assert!(!result.success);
        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

    #[tokio::test]
    async fn committed_postverify_failure_emits_no_tool_event() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("postverify-conflict.txt");
        fs::write(&path, "before").await.unwrap();
        let path_string = path.to_string_lossy().into_owned();
        let session_id = format!("event-conflict-{}", uuid::Uuid::new_v4());
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor =
            Arc::new(BuiltinToolExecutor::new().with_tool_event_publisher(recorder.clone()));

        let initial_read = make_tool_call_with_id(
            "conflict-initial-read",
            "Read",
            json!({"file_path": path_string}),
        );
        executor
            .execute_with_context(
                &initial_read,
                tool_event_context(
                    &initial_read,
                    Some(&session_id),
                    Some("conflict-root-session"),
                ),
            )
            .await
            .unwrap();
        let (advance_reached, resume_advance) =
            crate::tools::read_tracker::pause_next_advance_for_test(&session_id, &path_string)
                .await;

        let writer_executor = executor.clone();
        let writer_session = session_id.clone();
        let writer_path = path_string.clone();
        let writer = tokio::spawn(async move {
            let call = make_tool_call_with_id(
                "conflict-write-call",
                "Write",
                json!({"file_path": writer_path, "content": "intended"}),
            );
            writer_executor
                .execute_with_context(
                    &call,
                    tool_event_context(&call, Some(&writer_session), Some("conflict-root-session")),
                )
                .await
        });

        tokio::time::timeout(
            std::time::Duration::from_secs(5),
            advance_reached.notified(),
        )
        .await
        .expect("Write did not reach post-write baseline advancement");
        fs::write(&path, "other").await.unwrap();
        let concurrent_read = make_tool_call_with_id(
            "conflict-concurrent-read",
            "Read",
            json!({"file_path": path_string}),
        );
        executor
            .execute_with_context(
                &concurrent_read,
                tool_event_context(
                    &concurrent_read,
                    Some(&session_id),
                    Some("conflict-root-session"),
                ),
            )
            .await
            .unwrap();
        fs::write(&path, "intended").await.unwrap();
        resume_advance.notify_one();

        let outcome = tokio::time::timeout(std::time::Duration::from_secs(5), writer)
            .await
            .expect("Write did not resume")
            .unwrap();
        assert!(
            matches!(outcome, Err(ToolError::Execution(ref message)) if message.contains("Write committed")),
            "committed postverify conflict must stay an error: {outcome:?}"
        );
        assert_eq!(fs::read_to_string(path).await.unwrap(), "intended");
        assert!(
            recorder.try_snapshot().unwrap().is_empty(),
            "an on-disk mutation is not a successful tool outcome"
        );
    }

    #[tokio::test]
    async fn permission_pause_does_not_publish_a_success_event() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("approval-gated.txt");
        let config = Arc::new(crate::permission::PermissionConfig::new());
        config.set_ask_rules([format!("Write({}/**)", dir.path().display())]);
        config.register_session_workspace(
            "approval-session",
            dir.path().to_string_lossy().into_owned(),
        );
        let checker = Arc::new(crate::permission::ConfigPermissionChecker::new(config));
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = BuiltinToolExecutorBuilder::new()
            .with_filesystem_tool("Write")
            .unwrap()
            .with_permission_checker(checker)
            .with_tool_event_publisher(recorder.clone())
            .build();
        let call = make_tool_call_with_id(
            "approval-call",
            "Write",
            json!({"file_path": path, "content": "not-yet"}),
        );
        let (event_tx, _event_rx) = mpsc::channel(4);
        let mut ctx = tool_event_context(
            &call,
            Some("approval-session"),
            Some("approval-root-session"),
        );
        ctx.event_tx = Some(&event_tx);

        let result = executor.execute_with_context(&call, ctx).await.unwrap();
        assert!(
            result.success,
            "approval pause is a synthetic success result"
        );
        assert_eq!(
            result.display_preference.as_deref(),
            Some("request_permissions")
        );
        assert!(!path.exists(), "permission pause must not invoke Write");
        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

    #[tokio::test]
    async fn missing_authority_or_oversize_path_fails_closed_without_event() {
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let executor = marked_stub_write_executor(true, recorder.clone());

        let missing_session = make_tool_call_with_id(
            "missing-session-call",
            "Write",
            json!({"file_path": "/bounded/path.txt"}),
        );
        assert!(
            executor
                .execute_with_context(
                    &missing_session,
                    tool_event_context(&missing_session, None, Some("authority-root-session"),),
                )
                .await
                .unwrap()
                .success
        );

        let missing_root = make_tool_call_with_id(
            "missing-root-call",
            "Write",
            json!({"file_path": "/bounded/path.txt"}),
        );
        assert!(
            executor
                .execute_with_context(
                    &missing_root,
                    tool_event_context(&missing_root, Some("authority-session"), None),
                )
                .await
                .unwrap()
                .success
        );

        let oversize_path = make_tool_call_with_id(
            "oversize-path-call",
            "Write",
            json!({"file_path": "x".repeat(MAX_TOOL_EVENT_PATH_BYTES + 1)}),
        );
        assert!(
            executor
                .execute_with_context(
                    &oversize_path,
                    tool_event_context(
                        &oversize_path,
                        Some("authority-session"),
                        Some("authority-root-session"),
                    ),
                )
                .await
                .unwrap()
                .success
        );

        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

    #[tokio::test]
    async fn custom_write_name_never_acquires_builtin_event_provenance() {
        let recorder = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
        let registry = ToolRegistry::new();
        registry.register(StubWriteTool { success: true }).unwrap();
        let from_registry = BuiltinToolExecutor::with_registry(registry)
            .with_tool_event_publisher(recorder.clone());
        let first = make_tool_call_with_id(
            "spoof-registry-call",
            "Write",
            json!({"file_path": "/spoof/path.txt"}),
        );
        assert!(
            from_registry
                .execute_with_context(
                    &first,
                    tool_event_context(&first, Some("spoof-session"), Some("spoof-root-session"),),
                )
                .await
                .unwrap()
                .success
        );

        let custom_before_defaults = BuiltinToolExecutorBuilder::new()
            .with_tool(StubWriteTool { success: true })
            .unwrap()
            .with_default_tools()
            .with_tool_event_publisher(recorder.clone())
            .build();
        let second = make_tool_call_with_id(
            "spoof-builder-order-call",
            "Write",
            json!({"file_path": "/spoof/path.txt"}),
        );
        assert!(
            custom_before_defaults
                .execute_with_context(
                    &second,
                    tool_event_context(&second, Some("spoof-session"), Some("spoof-root-session"),),
                )
                .await
                .unwrap()
                .success
        );

        let replaced_builtin =
            BuiltinToolExecutor::new().with_tool_event_publisher(recorder.clone());
        assert!(replaced_builtin.registry().unregister("Write"));
        replaced_builtin
            .register_tool(StubWriteTool { success: true })
            .unwrap();
        let third = make_tool_call_with_id(
            "spoof-replaced-builtin-call",
            "Write",
            json!({"file_path": "/spoof/path.txt"}),
        );
        assert!(
            replaced_builtin
                .execute_with_context(
                    &third,
                    tool_event_context(&third, Some("spoof-session"), Some("spoof-root-session"),),
                )
                .await
                .unwrap()
                .success
        );

        assert!(recorder.try_snapshot().unwrap().is_empty());
    }

    #[tokio::test]
    async fn publisher_rejection_or_panic_never_changes_successful_tool_result() {
        let full = Arc::new(InMemoryToolEventRecorder::new(1).unwrap());
        full.try_publish(seed_event("seed-full")).unwrap();
        assert_real_write_succeeds_with_publisher(full.clone(), "full").await;
        let retained = full.try_snapshot().unwrap();
        assert_eq!(retained.len(), 1);
        assert_eq!(retained[0].context.tool_call_id, "seed-full");

        let publishers: Vec<(&str, Arc<dyn ToolEventPublisher>)> = vec![
            (
                "busy",
                Arc::new(ReturningPublisher(ToolEventPublishError::Busy)),
            ),
            (
                "poisoned",
                Arc::new(ReturningPublisher(ToolEventPublishError::Poisoned)),
            ),
            (
                "failed",
                Arc::new(ReturningPublisher(ToolEventPublishError::Failed(
                    "sink unavailable".to_string(),
                ))),
            ),
            ("enabled-panic", Arc::new(IsEnabledPanicPublisher)),
            ("publish-panic", Arc::new(TryPublishPanicPublisher)),
        ];
        for (label, publisher) in publishers {
            assert_real_write_succeeds_with_publisher(publisher, label).await;
        }
    }
}