bamboo-engine 2026.8.1

Execution engine and orchestration for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
//! Actor external child runner.
//!
//! Runs a child session as an independent **actor**: a separate OS process with its own
//! isolated context, speaking the `bamboo-subagent` WebSocket protocol. This is the
//! engine-side adapter on the `wants_external` seam: it spawns the worker binary, waits for
//! it to self-register into the Tier-1 file fabric, connects, sends the assignment, and
//! forwards the child's `AgentEvent`s back onto the parent's `event_tx`.
//!
//! The built-in **local actor** instance of this runner is the default runtime for
//! every sub-agent (the in-process runtime was removed). The expert `externalAgents`
//! tables can additionally route specific roles to other actor/a2a agents.

use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use bamboo_agent_core::{AgentError, AgentEvent, Role, Session};
use bamboo_domain::poison::PoisonRecover;
use bamboo_domain::SessionInboxClaim;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use bamboo_subagent::fleet::{spawn_worker_on_bus, SpawnedChild};
use bamboo_subagent::proto::{
    AgentRecord, ChildFrame, LogicalSessionIdentity, ParentFrame, PermissionPolicyContext, RunSpec,
    SessionMessageDelivery, TerminalStatus,
};
use bamboo_subagent::provision::{
    ChildIdentity, ExecutorSpec, ModelRefSpec, Placement, ProvisionSpec, ScopedCredential,
};
use bamboo_subagent::transport::{client_config_trusting_cert, ChildClient};

use crate::runtime::execution::{ExternalChildRunner, SessionInboxRuntimeBinding, SpawnJob};

/// Default cap on simultaneously running actor processes.
pub const DEFAULT_MAX_CONCURRENT_ACTORS: usize = 8;

/// Max nesting depth for direct nested execution (Phase 6). A worker whose
/// session `spawn_depth` is below this gets its own spawn stack + the real
/// SubAgent tool; at/over it, neither (and the tool itself refuses). Mirrors
/// `bamboo_server_tools::DEFAULT_MAX_SPAWN_DEPTH` (kept in sync; engine can't
/// depend on server-tools). Root orchestrator = 0 ⇒ 4 levels of sub-agents.
pub const MAX_SPAWN_DEPTH: u32 = 4;

/// Default cap on idle pooled (warm, reusable) workers kept per fingerprint.
const DEFAULT_MAX_IDLE_PER_KEY: usize = 4;

/// How long a pooled worker waits for its next assignment before reclaiming
/// itself (must comfortably exceed the gap between sibling spawns).
const POOLED_IDLE_TIMEOUT_SECS: u64 = 300;

/// Deadline for a local worker's FIRST frame after a Run is dispatched. A warm
/// worker answers in seconds; a cold spawn within tens. Total silence past this
/// means the worker is dead (e.g. a pooled worker that exited right after its
/// liveness check) and its Run is queued with nobody to serve it — trip it so the
/// runner respawns once instead of hanging forever. Generous, to never false-trip
/// a slow-but-healthy cold start.
const WORKER_FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(60);

fn active_scoped_session_deny_count(
    config: &bamboo_tools::permission::PermissionConfig,
    session_id: &str,
) -> usize {
    config
        .temporary_grants()
        .into_iter()
        .filter(|grant| {
            grant.scope == bamboo_tools::permission::TemporaryPermissionGrantScope::Session
                && grant.effect == bamboo_tools::permission::TemporaryPermissionGrantEffect::Deny
                && grant.session_id.as_deref() == Some(session_id)
        })
        .count()
}

fn ensure_no_active_scoped_session_denies(
    config: &bamboo_tools::permission::PermissionConfig,
    session_id: &str,
) -> Result<(), AgentError> {
    let count = active_scoped_session_deny_count(config, session_id);
    if count == 0 {
        Ok(())
    } else {
        Err(AgentError::LLM(format!(
            "external executor activation blocked by {count} active session-scoped explicit deny rule(s)"
        )))
    }
}

/// Plaintext token returned once by the server authority for one Codex run.
/// `token_id` is non-secret and is the handle used for guaranteed revocation.
pub struct IssuedCodexRunToken {
    pub token_id: String,
    pub token: String,
}

/// Server-owned authority for Bamboo-as-provider Codex credentials. The engine
/// only needs mint/revoke; verification remains inside the HTTP server.
pub trait CodexRunTokenAuthority: Send + Sync + 'static {
    fn issue(&self, session_id: &str) -> Result<IssuedCodexRunToken, String>;
    fn revoke(&self, token_id: &str);
}

struct CodexRunTokenGuard {
    authority: Arc<dyn CodexRunTokenAuthority>,
    token_id: String,
}

impl Drop for CodexRunTokenGuard {
    fn drop(&mut self) {
        self.authority.revoke(&self.token_id);
    }
}

fn executor_uses_bamboo_codex(executor: &ExecutorSpec) -> bool {
    matches!(
        executor,
        ExecutorSpec::Codex {
            auth_mode: Some(mode),
            ..
        } if mode == "bamboo"
    ) || matches!(
        executor,
        ExecutorSpec::Codex {
            auth_mode: None,
            inherit_user_config,
            ..
        } if !inherit_user_config.unwrap_or(false)
    )
}

fn executor_has_read_only_permission_profile(executor: &ExecutorSpec) -> bool {
    match executor {
        ExecutorSpec::ClaudeCode {
            permission_mode, ..
        } => permission_mode
            .as_deref()
            .is_some_and(|mode| mode.eq_ignore_ascii_case("plan")),
        ExecutorSpec::Codex {
            permission_profile,
            sandbox,
            ..
        } => {
            permission_profile
                .as_deref()
                .is_some_and(|profile| profile.eq_ignore_ascii_case("read-only"))
                || sandbox
                    .as_deref()
                    .is_some_and(|value| value.eq_ignore_ascii_case("read-only"))
        }
        _ => false,
    }
}

/// Exact non-secret executor posture the host expects for one typed activation.
///
/// Echo is intentionally a transport-only smoke executor and CliAdapter is not
/// implemented by the production worker. Neither claims the typed permission
/// contract, so legacy/custom frame handling remains available only for those
/// two variants. Every executable permission-aware variant must prove the
/// mapping derived from its provisioned spec before any execution event.
fn expected_permission_executor_mapping(
    executor: &ExecutorSpec,
    resolution: bamboo_domain::PermissionModeResolution,
    has_explicit_deny: bool,
) -> Result<Option<String>, AgentError> {
    let mapping = match executor {
        ExecutorSpec::Echo | ExecutorSpec::CliAdapter { .. } => return Ok(None),
        ExecutorSpec::BambooRuntime => {
            format!("bamboo_runtime:{}", resolution.effective.as_str())
        }
        ExecutorSpec::ClaudeCode {
            permission_mode, ..
        } => {
            if has_explicit_deny {
                "claude_code:blocked_explicit_deny".to_string()
            } else {
                let mode = match resolution.effective {
                    bamboo_domain::PermissionMode::Plan => "plan",
                    bamboo_domain::PermissionMode::Auto => "bypassPermissions",
                    bamboo_domain::PermissionMode::AcceptEdits => "acceptEdits",
                    bamboo_domain::PermissionMode::DontAsk => "dontAsk",
                    bamboo_domain::PermissionMode::Default
                    | bamboo_domain::PermissionMode::BypassPermissions => {
                        permission_mode.as_deref().unwrap_or("default")
                    }
                };
                format!("claude_code:permission_mode={mode}")
            }
        }
        ExecutorSpec::Codex {
            mode,
            sandbox,
            approval_policy,
            allow_danger_bypass,
            ..
        } => match mode.as_deref().unwrap_or("exec") {
            "exec" => {
                let approval_policy = expected_codex_exec_approval_policy(
                    sandbox.as_deref(),
                    approval_policy.as_deref(),
                    allow_danger_bypass.unwrap_or(false),
                    resolution,
                )?;
                if has_explicit_deny {
                    "codex_exec:blocked_explicit_deny".to_string()
                } else {
                    format!("codex_exec:approval_policy={approval_policy}")
                }
            }
            "app_server" => {
                if !matches!(approval_policy.as_deref(), None | Some("on-request")) {
                    return Err(AgentError::LLM(
                        "invalid Codex app-server permission posture configuration".to_string(),
                    ));
                }
                if has_explicit_deny {
                    "codex_app_server:blocked_explicit_deny".to_string()
                } else {
                    let approval_policy = if resolution.suppress_approval_prompts()
                        || resolution.effective == bamboo_domain::PermissionMode::Plan
                    {
                        "never"
                    } else {
                        "on-request"
                    };
                    format!("codex_app_server:approvalPolicy={approval_policy}")
                }
            }
            _ => {
                return Err(AgentError::LLM(
                    "unsupported Codex executor mode for permission posture contract".to_string(),
                ));
            }
        },
    };
    Ok(Some(mapping))
}

fn expected_codex_exec_approval_policy(
    sandbox: Option<&str>,
    approval_policy: Option<&str>,
    allow_danger_bypass: bool,
    resolution: bamboo_domain::PermissionModeResolution,
) -> Result<&'static str, AgentError> {
    let configured = match approval_policy {
        None | Some("never") => "never",
        Some("on-failure") => "on-failure",
        Some(_) => {
            return Err(AgentError::LLM(
                "invalid Codex exec permission posture configuration".to_string(),
            ));
        }
    };
    if resolution.suppress_approval_prompts()
        || resolution.effective == bamboo_domain::PermissionMode::Plan
    {
        return Ok("never");
    }
    match sandbox {
        Some("danger-full-access") => Ok("never"),
        Some("read-only") | Some("workspace-write") => Ok(configured),
        None if allow_danger_bypass || resolution.bypass_permissions() => Ok("never"),
        None => Ok(configured),
        Some(_) => Err(AgentError::LLM(
            "invalid Codex exec permission posture configuration".to_string(),
        )),
    }
}

fn workspace_is_bamboo_owned(raw: &str) -> bool {
    let workspace = std::fs::canonicalize(raw).unwrap_or_else(|_| PathBuf::from(raw));
    let configured_root = bamboo_config::paths::resolve_workspace_root();
    let configured_root = std::fs::canonicalize(&configured_root).unwrap_or(configured_root);
    if workspace.starts_with(&configured_root) {
        return true;
    }

    // Project worktrees created by Bamboo live under
    // `<project>/.bamboo/worktree/<name>` and carry the ownership marker used
    // by the project-worktree lifecycle. A path that merely imitates the
    // directory shape is not sufficient to bypass Codex's git guard.
    workspace.ancestors().any(|candidate| {
        let Some(name) = candidate.file_name().and_then(|name| name.to_str()) else {
            return false;
        };
        let Some(worktree_root) = candidate.parent() else {
            return false;
        };
        if worktree_root.file_name() != Some(std::ffi::OsStr::new("worktree"))
            || worktree_root.parent().and_then(Path::file_name)
                != Some(std::ffi::OsStr::new(".bamboo"))
        {
            return false;
        }
        let marker = worktree_root.join(".bamboo-owned").join(name);
        std::fs::read_to_string(marker).is_ok_and(|branch| branch == format!("bamboo/{name}"))
    })
}

fn build_codex_run_secrets(
    executor: &ExecutorSpec,
    authority: Option<Arc<dyn CodexRunTokenAuthority>>,
    child_session_id: &str,
) -> Result<
    (
        bamboo_subagent::proto::RunSecrets,
        Option<CodexRunTokenGuard>,
    ),
    AgentError,
> {
    if !executor_uses_bamboo_codex(executor) {
        return Ok((bamboo_subagent::proto::RunSecrets::default(), None));
    }

    let authority = authority.ok_or_else(|| {
        AgentError::LLM(
            "Codex auth mode 'bamboo' requires the server per-run token authority".to_string(),
        )
    })?;
    let issued = authority
        .issue(child_session_id)
        .map_err(|error| AgentError::LLM(format!("mint Codex per-run provider token: {error}")))?;
    let guard = CodexRunTokenGuard {
        authority,
        token_id: issued.token_id,
    };
    Ok((
        bamboo_subagent::proto::RunSecrets {
            codex_provider_token: Some(bamboo_subagent::proto::SecretValue::new(issued.token)),
        },
        Some(guard),
    ))
}

/// A warm worker on the mailbox bus, parked for reuse between runs. It stays
/// dialed-in + subscribed to `mailbox_id`; the next interchangeable child
/// delivers its `Run` there instead of spawning a fresh process. Dropping it
/// kills a local kill-on-drop subprocess; a remote / schedulable handle is
/// process-less (`kill()` is a no-op — it self-manages via its idle timeout).
struct PooledWorker {
    worker: SpawnedChild,
    /// The bus mailbox this worker subscribes to (where its `Run`s are delivered).
    mailbox_id: String,
}

/// A role pinned to a remote resident worker (remote-actor-plan §3.4 / P1.5,
/// #193), resolved at runner-build time from `SubagentsConfig.remote_placements`:
/// the env-named bearer is already READ into `token` here (the raw token never
/// rides the config), and `ca_cert_file` is the path to a PEM pinning a
/// self-signed worker cert (`None` ⇒ default webpki roots / plaintext `ws://`).
#[derive(Debug, Clone)]
pub struct ResolvedRemotePlacement {
    pub endpoint: String,
    pub token: Option<String>,
    pub ca_cert_file: Option<PathBuf>,
    /// Display name for the machine this role runs on — the matching cluster
    /// node's `label`/host, surfaced on the UI placement badge. `None` ⇒ derive
    /// from the endpoint host.
    pub host_label: Option<String>,
}

/// A role routed to a SCHEDULED worker (remote-actor-plan §3.4 / P2b, #181),
/// resolved at runner-build time from `SubagentsConfig.schedulable_placements`.
/// Names the logical `pool` (= the bus role) whose LIVE connected workers are the
/// scheduling candidates — the runner picks one via the bus presence query
/// (`BrokerClient::list_connected`). Phase 3 retired the old HTTP registry, so a
/// pool is now just a role on the bus.
#[derive(Debug, Clone)]
pub struct ResolvedSchedulablePlacement {
    pub pool: String,
    /// Display name for the machine this pool's workers run on — the matching
    /// cluster node's `label`/host, surfaced on the UI placement badge. `None` ⇒
    /// fall back to the pool name.
    pub host_label: Option<String>,
}

/// How `execute_external_child` should obtain its worker connection, decided
/// once from `spec.placement`. Splits the divergent acquire/connect + retire
/// logic three ways while the shared middle (Run dispatch, live registration,
/// drive, close) stays identical. `Local` is the unchanged pre-#193 path;
/// `Remote` is the unchanged #194 path; `Schedulable` (#181, P2b) is new.
enum PlacementKind {
    Local,
    Remote,
    Schedulable,
}

/// Spawns and drives a child session as an independent actor: a `bamboo-subagent` worker process.
pub struct ActorChildRunner {
    approval_registry: Option<super::approval_registry::SharedApprovalRegistry>,
    permission_config: Option<Arc<bamboo_tools::permission::PermissionConfig>>,
    agent_id: String,
    worker_bin: PathBuf,
    worker_args: Vec<String>,
    fabric_dir: PathBuf,
    executor: ExecutorSpec,
    /// Per-provider credentials snapshotted from the parent config at build
    /// time; the spec carries only the ONE the child's provider needs.
    credentials: Vec<ScopedCredential>,
    /// Parent's default provider (used when the child has no explicit one).
    default_provider: String,
    /// The mailbox bus to run local children over (the unified transport). Local
    /// sub-agents require it; `None` only when no broker could be embedded.
    bus: Option<bamboo_subagent::BusEndpoint>,
    /// Backpressure: bounds the number of concurrently *running* actors; further
    /// runs wait for a slot instead of exploding the process table. (Idle pooled
    /// workers do not hold a slot.)
    concurrency: std::sync::Arc<tokio::sync::Semaphore>,
    /// Warm-worker pool keyed by a reuse fingerprint
    /// (role/provider/model/workspace/disabled-tools/baked-caps). A finished run
    /// parks its bus worker here so the next interchangeable child reuses it
    /// (delivers its `Run` to the same mailbox) instead of spawning a fresh
    /// process — collapsing N sibling sub-agents onto a few warm workers.
    pool: Arc<tokio::sync::Mutex<HashMap<String, Vec<PooledWorker>>>>,
    max_idle_per_key: usize,
    /// Host-side decision for a child's gated-tool approval request (Phase 2).
    /// `None` ⇒ fail-closed DENY (the safe default). A wired decider (policy or
    /// human-routing bridge) returns approve/deny over the actor WS.
    approval_decider: Option<Arc<dyn ChildApprovalDecider>>,
    /// Off-loop parent-agent reviewer for forced-ask requests. The root server
    /// wires a session-aware reviewer; nested workers wire their owning model
    /// reviewer directly into the per-run runner.
    approval_reviewer: Option<Arc<dyn ChildApprovalReviewer>>,
    /// Per-run escalation host bridge for non-bypass child-approval routing (#68;
    /// Phase 6, Part B). The owning worker's `run()` installs its OWN host bridge
    /// here via `set_escalation_bridge`; `execute_external_child` CAPTURES it at
    /// grandchild-spawn time and hands the owned value to `drive()`, which uses it
    /// to RE-PROXY a child's approval request UP to the parent run — chaining up
    /// every level until a bypass level (model-review) or the top orchestrator
    /// (human) decides, then relaying the reply back down. Was a process-global
    /// slot; now per-runner so a fire-and-forget grandchild that OUTLIVES the run
    /// that spawned it keeps that run's bridge for its whole lifetime instead of
    /// reading a stale/overwritten global at approval time (→ fail-closed deny).
    escalation_bridge: Arc<std::sync::Mutex<Option<bamboo_subagent::executor::HostBridge>>>,
    /// Roles pinned to a REMOTE resident worker (#193), keyed by sub-agent role
    /// (the child's `subagent_type`). A role present here routes through the
    /// dedicated remote branch in `execute_external_child` (Bearer-authenticated
    /// `wss://` connect, no spawn, no pool, no kill) instead of the local
    /// subprocess + warm-pool path. Empty (the default) = all-local behavior.
    remote_placements: HashMap<String, ResolvedRemotePlacement>,
    /// Roles routed to a REGISTRY-SCHEDULED worker (#181, P2b), keyed by sub-agent
    /// role. A role present here (AND not already in `remote_placements`, which
    /// wins) routes through the dedicated SCHEDULABLE branch in
    /// `execute_external_child`: query the registry for live workers in the pool,
    /// pick one (round-robin), connect over `wss://` — no spawn, no pool, no kill,
    /// and NO local-subprocess fallback (no live worker ⇒ a clear error). Empty
    /// (the default) = all-local behavior.
    schedulable_placements: HashMap<String, ResolvedSchedulablePlacement>,
    /// Per-pool round-robin cursor for schedulable scheduling (#181, P2b). Bumped
    /// once per pick so successive sibling spawns SPREAD across a pool's live
    /// workers instead of all landing on the first candidate. Best-effort spread,
    /// not a load balancer — the registry's live set can change between picks.
    schedule_cursor: Arc<std::sync::Mutex<HashMap<String, usize>>>,
    /// Optional server authority used only by `Codex` in `bamboo` auth mode.
    codex_run_tokens: Option<Arc<dyn CodexRunTokenAuthority>>,
    /// Canonical logical-session inbox resources, late-bound by each owning
    /// runtime. Kept per runner/runtime; never process-global.
    session_inbox_runtime: Arc<std::sync::Mutex<Option<SessionInboxRuntimeBinding>>>,
}

/// Decides how the host answers a child worker's gated-tool approval request
/// (Phase 2: child → parent approval delegation). Async so an implementation
/// can consult a policy. With no decider wired the host replies with a
/// fail-closed DENY.
///
/// NOTE: `decide` is awaited inside the per-child frame pump, so an
/// implementation must resolve promptly (e.g. a policy lookup). Model-based
/// review belongs in [`ChildApprovalReviewer`], which runs off-loop and returns
/// through the live steering channel without stalling the frame pump.
#[async_trait]
pub trait ChildApprovalDecider: Send + Sync {
    /// Decide whether `child_session_id` may perform the gated action described
    /// by `request` (`{tool_name, permission, resource}`).
    async fn decide(&self, child_session_id: &str, request: &serde_json::Value) -> bool;
}

/// Resolve a child approval request to approve/deny. Fail-closed (DENY) when no
/// decider is wired — the single, testable seam for the host-side decision.
async fn decide_child_approval(
    decider: Option<&Arc<dyn ChildApprovalDecider>>,
    child_session_id: &str,
    request: &serde_json::Value,
) -> bool {
    match decider {
        Some(decider) => decider.decide(child_session_id, request).await,
        None => false,
    }
}

/// How long a chained parent-agent review may take before the child's gated
/// tool fails closed (DENY). Bounds an unanswered request so it cannot hang the
/// worker indefinitely.
const CHILD_APPROVAL_TIMEOUT: Duration = Duration::from_secs(300);

/// Off-loop reviewer for a child's gated-tool approval request (Phase 6, Part B).
///
/// Installed (process-global) by a BYPASSED self-orchestrating worker so its
/// children's forced-ask (dangerous) gated actions — which still raise
/// `ConfirmationRequired` even under bypass — get an LLM reasonableness check
/// rather than a blind pass. `review` is an LLM call: `drive()` invokes it in a
/// SPAWNED task (NEVER in the frame pump) and delivers the verdict async via the
/// live channel, so the agent loop is never blocked.
#[async_trait]
pub trait ChildApprovalReviewer: Send + Sync {
    /// Judge whether the gated action `request` (`{tool_name, permission,
    /// resource}`) is reasonable for `child_session_id`'s task. `true` = approve.
    async fn review(
        &self,
        parent_session_id: &str,
        child_session_id: &str,
        request: &serde_json::Value,
    ) -> bool;
}

fn child_approval_reviewer_slot() -> &'static std::sync::OnceLock<Arc<dyn ChildApprovalReviewer>> {
    static SLOT: std::sync::OnceLock<Arc<dyn ChildApprovalReviewer>> = std::sync::OnceLock::new();
    &SLOT
}

/// Install the process-global child-approval reviewer (idempotent; first wins).
pub fn set_child_approval_reviewer(reviewer: Arc<dyn ChildApprovalReviewer>) {
    let _ = child_approval_reviewer_slot().set(reviewer);
}

/// The process-global child-approval reviewer, if installed.
pub fn child_approval_reviewer() -> Option<Arc<dyn ChildApprovalReviewer>> {
    child_approval_reviewer_slot().get().cloned()
}

impl ActorChildRunner {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        agent_id: String,
        worker_bin: PathBuf,
        worker_args: Vec<String>,
        fabric_dir: PathBuf,
        executor: ExecutorSpec,
        credentials: Vec<ScopedCredential>,
        default_provider: String,
        max_concurrent: usize,
    ) -> Self {
        Self {
            approval_registry: None,
            permission_config: None,
            agent_id,
            worker_bin,
            worker_args,
            fabric_dir,
            executor,
            credentials,
            default_provider,
            bus: None,
            concurrency: std::sync::Arc::new(tokio::sync::Semaphore::new(max_concurrent.max(1))),
            pool: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
            max_idle_per_key: DEFAULT_MAX_IDLE_PER_KEY,
            approval_decider: None,
            approval_reviewer: None,
            escalation_bridge: Arc::new(std::sync::Mutex::new(None)),
            remote_placements: HashMap::new(),
            schedulable_placements: HashMap::new(),
            schedule_cursor: Arc::new(std::sync::Mutex::new(HashMap::new())),
            codex_run_tokens: None,
            session_inbox_runtime: Arc::new(std::sync::Mutex::new(None)),
        }
    }

    pub fn with_approval_registry(
        mut self,
        registry: super::approval_registry::SharedApprovalRegistry,
    ) -> Self {
        self.approval_registry = Some(registry);
        self
    }

    pub fn with_permission_config(
        mut self,
        config: Arc<bamboo_tools::permission::PermissionConfig>,
    ) -> Self {
        self.permission_config = Some(config);
        self
    }

    /// Run children over the mailbox bus (the unified actor+mailbox transport).
    /// When set, local children dial this bus and are driven by mailbox id; when
    /// unset they use the legacy direct-WS path. The server passes its in-process
    /// broker here (`subagents.broker`); tests without a broker leave it unset.
    pub fn with_bus(mut self, bus: Option<bamboo_subagent::BusEndpoint>) -> Self {
        self.bus = bus.filter(|b| !b.endpoint.trim().is_empty());
        self
    }

    /// Wire the host-side decider for child gated-tool approval requests
    /// (Phase 2). Without this the host fail-closed DENYs every request.
    pub fn with_approval_decider(mut self, decider: Arc<dyn ChildApprovalDecider>) -> Self {
        self.approval_decider = Some(decider);
        self
    }

    pub fn with_approval_reviewer(mut self, reviewer: Arc<dyn ChildApprovalReviewer>) -> Self {
        self.approval_reviewer = Some(reviewer);
        self
    }

    pub fn with_codex_run_tokens(
        mut self,
        authority: Option<Arc<dyn CodexRunTokenAuthority>>,
    ) -> Self {
        self.codex_run_tokens = authority;
        self
    }

    /// Pin specific sub-agent roles to remote resident workers (#193). The map
    /// is keyed by role (`subagent_type`); a child whose role is present connects
    /// over `wss://` to the resolved endpoint instead of spawning a local
    /// subprocess. Default (empty) keeps every role on the local path — exactly
    /// today's behavior.
    pub fn with_remote_placements(
        mut self,
        placements: HashMap<String, ResolvedRemotePlacement>,
    ) -> Self {
        self.remote_placements = placements;
        self
    }

    /// Route specific sub-agent roles to a registry-SCHEDULED worker (#181, P2b).
    /// The map is keyed by role (`subagent_type`); a child whose role is present
    /// (and NOT already pinned by `remote_placements`, which takes precedence) is
    /// run on a live worker discovered from the registry instead of a local
    /// subprocess. Default (empty) keeps every role on the local path.
    pub fn with_schedulable_placements(
        mut self,
        placements: HashMap<String, ResolvedSchedulablePlacement>,
    ) -> Self {
        self.schedulable_placements = placements;
        self
    }

    /// Reuse fingerprint: two children are interchangeable on one warm worker iff
    /// they share role, provider, model, workspace, disabled-tool set, AND every
    /// capability the worker BAKES at provision time (`BambooRuntimeExecutor`
    /// stamps these once and reuses them across runs): nesting depth, nested-spawn
    /// stack, requested/effective permission modes, legacy bypass/auto flags,
    /// permission enforcement, and the depth cap. Omitting any
    /// of these lets the pool hand a run a worker baked for a DIFFERENT posture —
    /// e.g. a depth-1 worker (with its own spawn stack) reused for a depth-4
    /// child would re-stamp `spawn_depth=1` and pass the depth-cap check, breaking
    /// the recursion bound; or a bypass worker reused for a non-bypass child. So
    /// these MUST split the pool bucket. Everything else (assignment, history) is
    /// shipped per-run in the `RunSpec` and does not affect the fingerprint.
    /// Reuse fingerprint (role/provider/model/workspace/disabled-tools/baked
    /// caps): two children with the same fingerprint are interchangeable on one
    /// warm worker, so they share a pool bucket. Any axis the worker bakes ONCE
    /// at provision time MUST be in here, else a worker baked for one posture
    /// gets reused for another (see the `fingerprint_*` tests).
    fn fingerprint(spec: &ProvisionSpec) -> String {
        let role = spec.identity.role.as_str();
        let (provider, model) = spec
            .model
            .as_ref()
            .map(|m| (m.provider.as_str(), m.model.as_str()))
            .unwrap_or(("", ""));
        let workspace = spec.workspace.as_deref().unwrap_or("");
        let mut tools = spec.disabled_tools.clone().unwrap_or_default();
        tools.sort();
        let caps = &spec.capabilities;
        // The worker constructs its executor exactly once. In particular,
        // Codex exec and app-server workers are not interchangeable.
        let executor = serde_json::to_string(&spec.executor).unwrap_or_default();
        format!(
            "{role}\u{1}{provider}\u{1}{model}\u{1}{workspace}\u{1}{}\u{1}d={}\u{1}ns={}\u{1}pr={}\u{1}pe={}\u{1}by={}\u{1}auto={}\u{1}ep={}\u{1}md={}\u{1}nha={}\u{1}gro={}\u{1}executor={executor}",
            tools.join(","),
            spec.identity.depth,
            caps.nested_spawn,
            caps.permission_requested_mode,
            caps.permission_effective_mode,
            caps.bypass,
            caps.auto_approve_permissions,
            caps.enforce_permissions,
            caps.max_spawn_depth.unwrap_or(0),
            // #73 review (P1): a worker bakes `no_human_review` ONCE from this flag
            // at build() and never re-reads it per run, so the pool MUST NOT hand a
            // worker baked for one approval posture to a run of the opposite one —
            // else a scheduled-root worker reused for an interactive child would
            // silently model-review instead of asking the human (and vice-versa,
            // reintroducing the 300s-deny). Split the bucket on it.
            caps.no_human_approver,
            // #71: the read-only Bash checker is baked once at build() from this
            // flag, so a guardian-reviewer worker must NOT be reused for an
            // ordinary child (which expects unrestricted Bash), and vice-versa.
            caps.guardian_read_only,
        )
    }

    /// Check out a warm bus worker for `key`, reusing a live parked one if any,
    /// else spawning a fresh one that dials the bus. The returned worker is OWNED
    /// by the caller for the run's duration (checkout removes it from the pool, so
    /// a concurrent sibling gets a different worker or spawns its own — one run per
    /// worker at a time, matching the pre-bus pool semantics).
    async fn acquire_bus_worker(
        &self,
        key: &str,
        spec: &ProvisionSpec,
    ) -> crate::runtime::runner::Result<PooledWorker> {
        // Drain the bucket, skipping (and reaping) any worker whose process exited
        // while parked. A live one is handed straight out for reuse.
        loop {
            let candidate = {
                let mut pool = self.pool.lock().await;
                pool.get_mut(key).and_then(|bucket| bucket.pop())
            };
            let Some(mut candidate) = candidate else {
                break;
            };
            if candidate.worker.is_alive() {
                return Ok(candidate);
            }
            candidate.worker.kill().await;
        }

        let spawned = spawn_worker_on_bus(&self.worker_bin, &self.worker_args, spec)
            .await
            .map_err(|e| AgentError::LLM(format!("actor spawn (bus) failed: {e}")))?;
        let mailbox_id = spawned.record.agent_id.clone();
        Ok(PooledWorker {
            worker: spawned,
            mailbox_id,
        })
    }

    /// Park a warm bus worker for reuse after a clean run; if its bucket is full
    /// (or it died), kill it instead. The worker stays dialed-in + subscribed
    /// while parked, so a reusing child just delivers a new `Run` to its mailbox.
    async fn release_bus_worker(&self, key: &str, mut worker: PooledWorker) {
        if !worker.worker.is_alive() {
            worker.worker.kill().await;
            return;
        }
        let mut pool = self.pool.lock().await;
        let bucket = pool.entry(key.to_string()).or_default();
        if bucket.len() >= self.max_idle_per_key {
            drop(pool);
            worker.worker.kill().await;
            return;
        }
        bucket.push(worker);
    }

    /// Assemble the parent-resolved provisioning document for this child.
    fn build_spec(&self, session: &Session, job: &SpawnJob) -> ProvisionSpec {
        let mut spec = ProvisionSpec::new(
            ChildIdentity {
                child_id: job.child_session_id.clone(),
                parent_id: Some(job.parent_session_id.clone()),
                project_key: None,
                role: session
                    .metadata
                    .get("subagent_type")
                    .cloned()
                    .unwrap_or_else(|| "worker".to_string()),
                // The child session already carries the correct depth
                // (create_child_action's new_child_of did parent.spawn_depth+1);
                // stamp it so the worker can re-establish it on its run session
                // and enforce the max-depth cap across the actor boundary.
                depth: session.spawn_depth,
            },
            self.executor.clone(),
            self.fabric_dir.to_string_lossy().into_owned(),
        );
        spec.workspace = session.workspace.clone();
        if let ExecutorSpec::Codex {
            workspace_owned, ..
        } = &mut spec.executor
        {
            *workspace_owned = Some(
                spec.workspace
                    .as_deref()
                    .is_some_and(workspace_is_bamboo_owned),
            );
        }
        // Unified transport: when a bus is configured, the child dials it (no
        // listen socket / file discovery) and the parent drives it by mailbox id.
        spec.bus = self.bus.clone();
        // Final model: the session's pinned model_ref (create.model / routing already applied),
        // falling back to the job's bare model on the parent's default provider.
        spec.model = session
            .model_ref
            .as_ref()
            .map(|r| ModelRefSpec {
                provider: r.provider.clone(),
                model: r.model.clone(),
            })
            .or_else(|| {
                let m = job.model.trim();
                (!m.is_empty()).then(|| ModelRefSpec {
                    provider: self.default_provider.clone(),
                    model: m.to_string(),
                })
            });
        spec.disabled_tools = job.disabled_tools.clone();
        match &spec.executor {
            // Codex auth is independent of the session's normal Bamboo model
            // provider. Inherit/API-key/Bamboo modes need no credential-store
            // secret at provisioning; custom mode gets exactly its referenced
            // key. This prevents an unrelated upstream provider key from
            // reaching a Codex worker that only needs a per-run bcx1_ token.
            ExecutorSpec::Codex {
                auth_mode,
                provider_key_ref,
                ..
            } => {
                if auth_mode.as_deref() == Some("custom") {
                    if let Some(reference) = provider_key_ref {
                        if let Some(credential) = self.credentials.iter().find(|credential| {
                            credential.credential_ref.as_deref() == Some(reference)
                        }) {
                            spec.secrets.provider_credentials.push(credential.clone());
                        } else {
                            tracing::warn!(
                                "actor child {}: custom Codex credential reference '{}' did not resolve",
                                job.child_session_id,
                                reference
                            );
                        }
                    } else {
                        tracing::warn!(
                            "actor child {}: custom Codex executor has no credential reference",
                            job.child_session_id
                        );
                    }
                }
            }
            // Other executors keep the existing least-privilege contract: only
            // the credential for the child session's selected provider.
            _ => {
                let provider = spec
                    .model
                    .as_ref()
                    .map(|model| model.provider.as_str())
                    .filter(|provider| !provider.trim().is_empty())
                    .unwrap_or(&self.default_provider);
                if let Some(credential) = self
                    .credentials
                    .iter()
                    .find(|credential| credential.provider == provider)
                {
                    spec.secrets.provider_credentials.push(credential.clone());
                } else {
                    tracing::warn!(
                        "actor child {}: no credential found for provider '{}'",
                        job.child_session_id,
                        provider
                    );
                }
            }
        }
        // Phase 6 (direct nested execution): a worker BELOW the depth cap may
        // orchestrate its OWN children — on startup it builds its own spawn
        // stack and runs the real SubAgent tool (no host proxy). The cap (the
        // SubAgent tool refuses to spawn at/over `max_spawn_depth`) bounds the
        // recursion. Driven purely by the child's depth, so it auto-propagates
        // down the tree without any extra config threading.
        spec.capabilities.nested_spawn = session.spawn_depth < MAX_SPAWN_DEPTH;
        spec.capabilities.max_spawn_depth = Some(MAX_SPAWN_DEPTH);
        // #69: activate child-approval review. Sub-agents enforce permissions so
        // their DANGEROUS actions (the worker uses a HIGH threshold) reach the
        // parent for review — escalated to the human, or model-reviewed off-loop
        // when the parent is in bypass. The worker installs no checker without
        // this, so the whole review chain would otherwise stay dormant.
        spec.capabilities.enforce_permissions = true;
        // Propagate "bypass permissions" so a self-orchestrating worker knows it
        // is a bypassed parent and installs the off-loop model-reviewer for its
        // children's forced-ask actions (Phase 6, Part B). The child session
        // already carries the inherited flag (create_child_action seeds it).
        let requested_permission_mode = session
            .agent_runtime_state
            .as_ref()
            .map(|state| state.effective_permission_mode())
            .unwrap_or_default();
        let configured_permission_mode = self
            .permission_config
            .as_ref()
            .map(|config| config.mode())
            .unwrap_or_default();
        // #73: propagate "no interactive human approver" (headless / scheduled /
        // deployed root, inherited by the child session). When set, the worker's
        // per-run approval proxy model-reviews a gated action locally instead of
        // escalating to a human who will never answer (which would 300s-deny).
        spec.capabilities.no_human_approver = session
            .agent_runtime_state
            .as_ref()
            .is_some_and(|s| s.no_human_approver);
        // #71: mark a READ-ONLY Guardian reviewer so the worker installs the
        // read-only Bash allowlist checker. The reviewer is spawned by
        // `spawn_guardian_review` with `subagent_type == "guardian"` (the SAME
        // marker the completion coordinator branches on to parse the verdict) AND
        // the `guardian_read_only_disabled_tools` denylist. Keyed off that role
        // marker (already read above to set `identity.role`), so it rides the same
        // session-metadata path the denylist/subagent_type use — no new wire seam.
        // Without this the worker keeps an UNRESTRICTED Bash, so the reviewer could
        // still `rm -rf` / `git push` / `curl | sh`, defeating "read-only".
        spec.capabilities.guardian_read_only =
            session.metadata.get("subagent_type").map(String::as_str) == Some("guardian");
        if spec.capabilities.guardian_read_only {
            if let ExecutorSpec::Codex {
                permission_profile, ..
            } = &mut spec.executor
            {
                *permission_profile = Some("read-only".to_string());
            }
        }
        let read_only_overlay = session
            .agent_runtime_state
            .as_ref()
            .is_some_and(|state| state.plan_mode.is_some())
            || spec.capabilities.guardian_read_only
            || executor_has_read_only_permission_profile(&spec.executor);
        let permission_resolution = bamboo_domain::resolve_permission_mode_with_read_only(
            requested_permission_mode,
            configured_permission_mode,
            read_only_overlay,
        );
        spec.capabilities.bypass = permission_resolution.bypass_permissions();
        spec.capabilities.auto_approve_permissions =
            permission_resolution.suppress_approval_prompts();
        spec.capabilities.permission_requested_mode =
            permission_resolution.requested.as_str().to_string();
        spec.capabilities.permission_effective_mode =
            permission_resolution.effective.as_str().to_string();
        // #193: route this role to a REMOTE resident worker when one is pinned.
        // `spec.identity.role` was just computed from `subagent_type` above; a
        // match flips the placement to Remote and rides the worker's bearer on the
        // scoped secrets envelope (TLS handshake / Authorization header only — the
        // token is never logged). No match leaves the default `Placement::Local`,
        // so the local path is byte-for-byte unchanged for every non-pinned role.
        if let Some(placement) = self.remote_placements.get(spec.identity.role.as_str()) {
            spec.placement = Placement::Remote {
                endpoint: placement.endpoint.clone(),
            };
            spec.secrets.worker_auth_token = placement.token.clone();
        } else if let Some(placement) = self.schedulable_placements.get(spec.identity.role.as_str())
        {
            // #181 (P2b): route this role to a SCHEDULED worker — ONLY when it is
            // NOT already pinned to a fixed remote endpoint (the `else if` makes
            // remote_placements take precedence for a role in both). The concrete
            // worker is picked at run time in `execute_external_child` from the bus
            // (a live connected worker of the pool role). No per-placement bearer
            // now — the bus connection uses the bus token. No match in either map
            // leaves the default `Placement::Local`.
            spec.placement = Placement::Schedulable {
                pool: placement.pool.clone(),
            };
        }
        spec
    }

    /// The `metadata["placement"]` JSON to stamp on a child from its resolved
    /// placement, preferring the matching cluster node's `host_label` (its
    /// operator label/host) over the raw endpoint/pool. `None` for a Local child
    /// (the DTO defaults it to the backend's own host). Split out of
    /// `execute_external_child` so the role→placement→host resolution is unit-testable.
    fn placement_stamp_for(&self, spec: &ProvisionSpec) -> Option<String> {
        let host_label = match &spec.placement {
            Placement::Remote { .. } => self
                .remote_placements
                .get(spec.identity.role.as_str())
                .and_then(|p| p.host_label.as_deref()),
            Placement::Schedulable { .. } => self
                .schedulable_placements
                .get(spec.identity.role.as_str())
                .and_then(|p| p.host_label.as_deref()),
            Placement::Local => None,
        };
        placement_metadata(&spec.placement, host_label)
    }

    /// Pick a live worker for a SCHEDULABLE role from the BUS (#181, Phase 3):
    /// ask the broker which actors are connected serving the pool role (presence
    /// is connection-truth — no HTTP registry, no leases, no connect-fail
    /// failover), then round-robin one per resolve for spread. Returns the chosen
    /// worker's mailbox id. An empty pool ⇒ a terminal `AgentError` — NEVER a
    /// local-subprocess fallback (that would silently defeat the placement).
    async fn resolve_schedulable_worker(
        &self,
        role: &str,
    ) -> std::result::Result<String, AgentError> {
        let pool = self
            .schedulable_placements
            .get(role)
            .ok_or_else(|| {
                AgentError::LLM(format!(
                    "schedulable placement for role '{role}' vanished before scheduling"
                ))
            })?
            .pool
            .clone();
        let bus = self.bus.as_ref().ok_or_else(|| {
            AgentError::LLM(format!(
                "schedulable role '{role}': no mailbox bus configured (subagents.broker)"
            ))
        })?;

        // Ask the BUS who is connected serving the pool role — presence is
        // connection-truth (no HTTP registry, no leases, no stale-record failover).
        let mut q = bamboo_broker::BrokerClient::connect(
            &bus.endpoint,
            bamboo_subagent::AgentRef {
                session_id: format!("sched-q-{role}"),
                role: None,
            },
            &bus.token,
        )
        .await
        .map_err(|e| {
            AgentError::LLM(format!(
                "schedulable role '{role}': bus connect failed: {e}"
            ))
        })?;
        let candidates = q.list_connected(&pool).await.map_err(|e| {
            AgentError::LLM(format!(
                "schedulable role '{role}': bus presence query failed: {e}"
            ))
        })?;

        if candidates.is_empty() {
            return Err(AgentError::LLM(format!(
                "schedulable role '{role}': no live worker in pool '{pool}' on the bus \
                 (NOT spawning a local subprocess — a schedulable role has no local fallback)"
            )));
        }

        // Round-robin: advance a per-pool cursor once per resolve so successive
        // sibling spawns spread across the connected pool workers. No failover
        // needed — a listed worker is connected NOW (the bus only lists live
        // subscribers), so there is no stale-but-leased candidate to skip.
        let idx = {
            let mut cursors = self.schedule_cursor.lock().recover_poison();
            let cursor = cursors.entry(pool.clone()).or_insert(0);
            let i = *cursor % candidates.len();
            *cursor = cursor.wrapping_add(1);
            i
        };
        Ok(candidates[idx].clone())
    }
}

#[async_trait]
impl ExternalChildRunner for ActorChildRunner {
    async fn should_handle(&self, session: &Session) -> bool {
        session.metadata.get("runtime.kind") == Some(&"external".to_string())
            && session.metadata.get("external.protocol") == Some(&"actor".to_string())
            && session.metadata.get("external.agent_id") == Some(&self.agent_id)
    }

    fn set_escalation_bridge(&self, bridge: Option<bamboo_subagent::executor::HostBridge>) {
        *self.escalation_bridge.lock().recover_poison() = bridge;
    }

    fn set_session_inbox_runtime(&self, binding: Option<SessionInboxRuntimeBinding>) {
        *self.session_inbox_runtime.lock().recover_poison() = binding;
    }

    async fn execute_external_child(
        &self,
        session: &mut Session,
        job: &SpawnJob,
        event_tx: mpsc::Sender<AgentEvent>,
        cancel_token: CancellationToken,
    ) -> crate::runtime::runner::Result<()> {
        // #68 CORRECTNESS CRUX: capture the per-run escalation bridge HERE, at the
        // moment this grandchild is spawned — while the parent run's bridge is
        // still in our slot — into an owned local handed to `drive()` for this
        // grandchild's whole lifetime. A fire-and-forget grandchild that OUTLIVES
        // the run that spawned it must NOT re-read `self.escalation_bridge` at
        // approval time: by then `run()` may have cleared/overwritten it (a worker
        // serves runs sequentially), and re-proxying through a closed bridge
        // fail-closed denies. Capturing at spawn pins the right bridge per run.
        let escalation = self.escalation_bridge.lock().recover_poison().clone();
        let session_inbox_runtime = self.session_inbox_runtime.lock().recover_poison().clone();
        let assignment = extract_assignment(session);
        let mut spec = self.build_spec(session, job);
        // Mark the worker reusable + give it an idle timeout so it self-reaps if
        // orphaned. Warm bus workers are pooled per fingerprint and reused.
        spec.reusable = true;
        if spec.limits.idle_timeout_secs.is_none() {
            spec.limits.idle_timeout_secs = Some(POOLED_IDLE_TIMEOUT_SECS);
        }
        let pool_key = Self::fingerprint(&spec);

        // The recommended provider URL is deliberately parent-loopback. A
        // resident remote worker would interpret 127.0.0.1 as itself, not this
        // server, so reject that ambiguous deployment instead of minting a
        // credential that can never authenticate to the intended parent.
        if executor_uses_bamboo_codex(&spec.executor) && !matches!(spec.placement, Placement::Local)
        {
            return Err(AgentError::LLM(
                "Codex auth mode 'bamboo' requires local actor placement; use custom mode with a reachable URL for remote workers"
                    .to_string(),
            ));
        }
        let project_id = project_id_for_actor_run(session)?;
        let requested_permission_mode = session
            .agent_runtime_state
            .as_ref()
            .map(|state| state.effective_permission_mode())
            .unwrap_or_default();
        // Policy is captured per activation (not only when a worker is
        // provisioned), so reused local workers and resident remote/broker
        // workers observe the latest durable revision and bypass flag at the
        // next run boundary. Session grants are intentionally not inherited.
        let permission_policy = if let Some(config) = self.permission_config.as_ref() {
            ensure_no_active_scoped_session_denies(config, &session.id)?;
            let read_only_overlay = session
                .agent_runtime_state
                .as_ref()
                .is_some_and(|state| state.plan_mode.is_some())
                || spec.capabilities.guardian_read_only
                || executor_has_read_only_permission_profile(&spec.executor);
            let resolution = bamboo_domain::resolve_permission_mode_with_read_only(
                requested_permission_mode,
                config.mode(),
                read_only_overlay,
            );
            let policy = serde_json::to_value(config.to_serializable()).map_err(|error| {
                AgentError::LLM(format!(
                    "failed to serialize permission policy for external executor: {error}"
                ))
            })?;
            Some(PermissionPolicyContext {
                revision: config.policy_revision(),
                requested_mode: resolution.requested.as_str().to_string(),
                effective_mode: resolution.effective.as_str().to_string(),
                bypass_permissions: resolution.bypass_permissions(),
                auto_approve_permissions: resolution.suppress_approval_prompts(),
                session_id: session.id.clone(),
                workspace_path: session.workspace.clone(),
                inherit_session_grants: false,
                policy,
            })
        } else {
            None
        };
        let provisioned_permission =
            spec.capabilities.permission_resolution().map_err(|error| {
                AgentError::LLM(format!("invalid provisioned permission posture: {error}"))
            })?;
        let policy_resolution = permission_policy
            .as_ref()
            .map(|context| {
                context.resolved_modes().map(|(requested, effective)| {
                    bamboo_domain::PermissionModeResolution {
                        requested,
                        effective,
                    }
                })
            })
            .transpose()
            .map_err(|error| {
                AgentError::LLM(format!("invalid host permission posture: {error}"))
            })?;
        let host_audit = bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata);
        let has_explicit_deny = self.permission_config.as_ref().is_some_and(|config| {
            bamboo_tools::permission::explicit_deny_policy_reason(&config.to_serializable())
                .is_some()
        });
        let expected_executor_mapping = expected_permission_executor_mapping(
            &spec.executor,
            policy_resolution.unwrap_or(provisioned_permission),
            has_explicit_deny,
        )?;
        let expected_permission_posture =
            expected_executor_mapping.map(|executor_mapping| ExpectedPermissionPosture {
                policy_revision: permission_policy
                    .as_ref()
                    .map(|context| context.revision)
                    .or_else(|| host_audit.as_ref().map(|audit| audit.policy_revision))
                    .unwrap_or_default(),
                resolution: policy_resolution.unwrap_or(provisioned_permission),
                expected_audit_revision: host_audit.as_ref().map(|audit| audit.audit_revision),
                executor_mapping,
            });

        // Backpressure: hold a concurrency slot for the lifetime of the *run*
        // (cancellation still proceeds — the cancel branch in drive() runs while
        // we hold the permit). Released when this fn returns, i.e. once the worker
        // is parked back into the pool, so idle workers don't pin slots.
        let _slot = self
            .concurrency
            .acquire()
            .await
            .map_err(|_| AgentError::LLM("actor concurrency limiter closed".to_string()))?;

        // Bamboo-as-provider credentials are minted at the activation boundary,
        // after backpressure admits the run and never at worker provisioning.
        // This is load-bearing for warm workers: a parked process must never
        // retain a token from its previous run. The guard revokes on every return
        // path (success, error, cancellation, dispatch failure, or first-frame
        // retry exhaustion).
        let (run_secrets, _codex_token_guard) = build_codex_run_secrets(
            &spec.executor,
            self.codex_run_tokens.clone(),
            &job.child_session_id,
        )?;

        // Split LOCAL (spawn + warm-pool) from the two process-less remote paths
        // ONLY at the divergent spots — acquire/connect here and the park/retire at
        // the end. Everything between (Run dispatch, live-actor registration,
        // drive, the close) is identical for all three. `kind` is the single guard.
        //   - Local       (#0):  byte-for-byte the pre-#193 reuse-or-spawn path.
        //   - Remote       (#194): connect to a FIXED resident endpoint, no spawn.
        //   - Schedulable  (#181): resolve a live worker from the registry, connect.
        let kind = match spec.placement {
            Placement::Remote { .. } => PlacementKind::Remote,
            Placement::Schedulable { .. } => PlacementKind::Schedulable,
            Placement::Local => PlacementKind::Local,
        };
        let remote = !matches!(kind, PlacementKind::Local);

        // Stamp WHICH machine this child runs on onto its session metadata, so the
        // UI can show it (mirrored into the session index → SessionSummary.placement).
        // Only remote/scheduled placements need a stamp — a Local child falls through
        // to the DTO default (this backend's own host). Persisted by the caller with
        // the rest of the child session after we return.
        if let Some(placement_meta) = self.placement_stamp_for(&spec) {
            session
                .metadata
                .insert("placement".to_string(), placement_meta);
        }

        // Retry-once loop: a pooled local worker can die between its liveness
        // check and handling the Run (a tiny TOCTOU window) — its Run then sits
        // queued with no server. The first-frame watchdog in `drive` surfaces that
        // as `WorkerUnresponsive`; we reap the dead worker and re-acquire ONCE
        // (which spawns fresh / reuses the next live one). Remote/schedulable have
        // no spawn fallback, so they never retry.
        let mut attempt = 0u8;
        let (result, actor) = loop {
            let (actor, mut client) = match kind {
                PlacementKind::Remote => {
                    // REMOTE branch: connect to a resident worker. No spawn, no pool
                    // touch, no drain. We do not own the worker, so a connect failure
                    // has NO respawn fallback — it is a clear, terminal error.
                    let placement = self
                        .remote_placements
                        .get(spec.identity.role.as_str())
                        .ok_or_else(|| {
                            AgentError::LLM(format!(
                                "remote placement for role '{}' vanished before connect",
                                spec.identity.role
                            ))
                        })?;
                    let endpoint = placement.endpoint.clone();
                    // Build the TLS trust: a pinned CA pins a self-signed worker cert;
                    // otherwise default webpki roots (or plaintext for `ws://`).
                    let trust_cfg = match placement.ca_cert_file.as_deref() {
                        Some(path) => Some(client_config_trusting_cert(path).map_err(|e| {
                            AgentError::LLM(format!(
                                "remote worker CA cert '{}': {e}",
                                path.display()
                            ))
                        })?),
                        None => None,
                    };
                    let client = ChildClient::connect_with_auth_tls(
                        &endpoint,
                        placement.token.as_deref(),
                        trust_cfg,
                    )
                    .await
                    .map_err(|e| {
                        AgentError::LLM(format!("remote actor connect to '{endpoint}' failed: {e}"))
                    })?;
                    // Process-less handle so live-actor registration (in-band steering)
                    // works exactly as for a local worker; `kill()` is a no-op.
                    let record = AgentRecord {
                        agent_id: job.child_session_id.clone(),
                        role: spec.identity.role.clone(),
                        labels: Vec::new(),
                        endpoint: endpoint.clone(),
                        pid: 0,
                        version: String::new(),
                        started_at: chrono::Utc::now(),
                        lease_expires_at: chrono::Utc::now(),
                    };
                    let _ = endpoint;
                    let actor = PooledWorker {
                        worker: SpawnedChild::remote(record),
                        mailbox_id: job.child_session_id.clone(),
                    };
                    let client: Box<dyn bamboo_subagent::ChildLink> = Box::new(client);
                    (actor, client)
                }
                PlacementKind::Schedulable => {
                    // SCHEDULABLE branch (#181): pick a LIVE worker of the pool role
                    // from the BUS (presence = connection-truth; no HTTP registry, no
                    // leases, no failover) and drive it by mailbox id. The pool worker
                    // stays connected and is reused next time. No spawn, no kill, NO
                    // local fallback — an empty pool is a terminal error (raised in
                    // resolve_schedulable_worker).
                    let bus = self.bus.as_ref().ok_or_else(|| {
                        AgentError::LLM(
                            "schedulable sub-agents require a mailbox bus (subagents.broker)"
                                .to_string(),
                        )
                    })?;
                    let mailbox_id = self
                        .resolve_schedulable_worker(spec.identity.role.as_str())
                        .await?;
                    let parent = bamboo_subagent::AgentRef {
                        session_id: format!("p-{}", job.child_session_id),
                        role: None,
                    };
                    let link = bamboo_broker::BrokerChildLink::connect(
                        &bus.endpoint,
                        parent,
                        &bus.token,
                        mailbox_id.clone(),
                    )
                    .await
                    .map_err(|e| {
                        AgentError::LLM(format!(
                            "schedulable link connect to '{mailbox_id}' failed: {e}"
                        ))
                    })?;
                    // Process-less handle — a bus-resident pool worker is never ours to
                    // kill (remote ⇒ dropped, not pooled, after the run).
                    let actor = PooledWorker {
                        worker: SpawnedChild::remote(AgentRecord {
                            agent_id: mailbox_id.clone(),
                            role: spec.identity.role.clone(),
                            labels: Vec::new(),
                            endpoint: bus.endpoint.clone(),
                            pid: 0,
                            version: String::new(),
                            started_at: chrono::Utc::now(),
                            lease_expires_at: chrono::Utc::now(),
                        }),
                        mailbox_id,
                    };
                    let client: Box<dyn bamboo_subagent::ChildLink> = Box::new(link);
                    (actor, client)
                }
                PlacementKind::Local => {
                    // LOCAL = the mailbox bus (the unified transport): check out a warm
                    // pooled worker (reuse a live parked one, else spawn fresh) and
                    // drive it by mailbox id — no listen socket, no file discovery, no
                    // respawn-on-connect-miss (the broker queues the Run until the
                    // worker handles it). The legacy direct-WS path was retired; the bus
                    // is required.
                    let bus = self.bus.as_ref().ok_or_else(|| {
                        AgentError::LLM(
                            "local sub-agents require a mailbox bus (subagents.broker); none is \
                         configured and the bus could not be embedded"
                                .to_string(),
                        )
                    })?;
                    let actor = self.acquire_bus_worker(&pool_key, &spec).await?;
                    let parent = bamboo_subagent::AgentRef {
                        session_id: format!("p-{}", job.child_session_id),
                        role: None,
                    };
                    let link = bamboo_broker::BrokerChildLink::connect(
                        &bus.endpoint,
                        parent,
                        &bus.token,
                        actor.mailbox_id.clone(),
                    )
                    .await
                    .map_err(|e| {
                        AgentError::LLM(format!("broker child link connect failed: {e}"))
                    })?;
                    let client: Box<dyn bamboo_subagent::ChildLink> = Box::new(link);
                    (actor, client)
                }
            };

            // Publish the actor delivery owner and claim the complete bounded
            // authorized prefix before dispatching Run. These deliveries ride
            // inside RunSpec, so the worker durably enqueues them before its
            // first provider boundary rather than racing a later steer frame.
            let (delivery_tx, mut delivery_rx) = mpsc::unbounded_channel::<u64>();
            let bound_activation_run_id = match session_inbox_runtime.as_ref() {
                Some(binding) => {
                    let run_id = binding
                        .router
                        .attach_delivery_sink(&job.child_session_id, delivery_tx.clone())
                        .await;
                    if run_id.is_none() {
                        tracing::debug!(
                            session_id = %job.child_session_id,
                            "actor driver had no current SessionInbox activation owner to bind"
                        );
                    }
                    run_id
                }
                None => None,
            };
            drop(delivery_tx);
            let initial_pairs = match (
                session_inbox_runtime.as_ref(),
                bound_activation_run_id.as_deref(),
            ) {
                (Some(binding), Some(run_id)) => {
                    match claim_canonical_deliveries(binding, session, run_id, usize::MAX).await {
                        Ok(deliveries) => deliveries,
                        Err(error) => {
                            binding
                                .router
                                .detach_delivery_sink(&job.child_session_id, run_id)
                                .await;
                            if !remote {
                                actor.worker.kill().await;
                            }
                            return Err(error);
                        }
                    }
                }
                _ => Vec::new(),
            };
            let initial_session_messages = initial_pairs
                .iter()
                .map(|(_, delivery)| delivery.clone())
                .collect::<Vec<_>>();
            let initial_inflight_claims = initial_pairs
                .into_iter()
                .map(|(claim, _)| claim)
                .collect::<VecDeque<_>>();
            // Recompute after claim reconciliation: a warm retry may have had a
            // canonical receipt whose transcript proof was restored above.
            let messages = session
                .messages
                .iter()
                .filter_map(|message| serde_json::to_value(message).ok())
                .collect();

            if let Err(e) = client
                .send(ParentFrame::Run(RunSpec {
                    // Cloned (not moved) so a retry can re-dispatch to a fresh worker.
                    assignment: assignment.clone(),
                    logical_session: Some(logical_identity_for_actor_run(session, job)),
                    project_id: project_id.clone(),
                    reasoning_effort: None,
                    permission_policy: permission_policy.clone(),
                    messages,
                    activation_run_id: bound_activation_run_id.clone(),
                    initial_session_messages,
                    secrets: run_secrets.clone(),
                }))
                .await
            {
                if let (Some(binding), Some(run_id)) = (
                    session_inbox_runtime.as_ref(),
                    bound_activation_run_id.as_deref(),
                ) {
                    binding
                        .router
                        .detach_delivery_sink(&job.child_session_id, run_id)
                        .await;
                }
                if !remote {
                    actor.worker.kill().await;
                }
                return Err(AgentError::LLM(format!("actor run dispatch failed: {e}")));
            }

            // Register as a live actor so send_message (running, no interrupt) can
            // steer this child in-band over the existing WS connection. The guard
            // unregisters on every exit path.
            let (live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
            let live_guard = super::live::register(
                &job.child_session_id,
                live_tx,
                attempt as u32,
                self.approval_registry.clone(),
            );

            let result = drive(ActorDriveContext {
                client: &mut *client,
                parent_session_id: &job.parent_session_id,
                child_session_id: &job.child_session_id,
                child_attempt: attempt as u32,
                approval_registry: self.approval_registry.as_ref(),
                approval_decider: self.approval_decider.as_ref(),
                approval_reviewer: self.approval_reviewer.as_ref(),
                escalation_bridge: escalation.clone(),
                event_tx: &event_tx,
                cancel_token: &cancel_token,
                live_rx: &mut live_rx,
                delivery_rx: &mut delivery_rx,
                logical_session: session,
                expected_permission_posture: expected_permission_posture.clone(),
                session_inbox_runtime: session_inbox_runtime.as_ref(),
                activation_run_id: bound_activation_run_id.as_deref(),
                initial_inflight_claims,
                // First-frame watchdog for EVERY placement: a wedged-but-connected
                // worker (subscribed ≠ serving — e.g. stuck on a prior LLM call) emits
                // no first frame; without a deadline drive() blocks forever. Bounding it
                // turns the "running-but-unresponsive" hang into a recoverable
                // WorkerUnresponsive (reap+respawn local / re-pick schedulable / error
                // on a fixed remote endpoint).
                first_frame_timeout: Some(WORKER_FIRST_FRAME_TIMEOUT),
            })
            .await;
            if let (Some(binding), Some(run_id)) = (
                session_inbox_runtime.as_ref(),
                bound_activation_run_id.as_deref(),
            ) {
                binding
                    .router
                    .detach_delivery_sink(&job.child_session_id, run_id)
                    .await;
            }
            // Unregister IMMEDIATELY: after drive returns nobody consumes live_rx,
            // so a send_message landing in the close/park window below must see
            // "not live" and take the durable-queue fallback instead of vanishing.
            // (Even if one slipped in earlier, send_message also appends it to the
            // durable transcript, so the next activation still rehydrates it.)
            drop(live_guard);
            // Close the parent link (dropping it closes our broker connection; the
            // worker stays dialed-in + subscribed, ready for its next Run).
            drop(client);

            // No first frame ⇒ the worker is wedged. Recover ONCE before giving up:
            //   - Local: reap the dead pooled worker + respawn.
            //   - Schedulable: not ours to kill — drop it and re-select a live pool
            //     member (a wedged worker must not fail the run when the pool has others).
            //   - Remote: a FIXED endpoint has no alternative — fall through to a bounded
            //     WorkerUnresponsive error (far better than the previous infinite hang).
            if attempt == 0 && matches!(result, Err(AgentError::WorkerUnresponsive(_))) {
                match kind {
                    PlacementKind::Local => {
                        tracing::warn!(
                        "actor child {} got no first frame; reaping the worker and respawning once",
                        job.child_session_id
                    );
                        actor.worker.kill().await;
                        attempt += 1;
                        continue;
                    }
                    PlacementKind::Schedulable => {
                        tracing::warn!(
                        "scheduled actor child {} got no first frame; re-selecting a pool worker",
                        job.child_session_id
                    );
                        drop(actor);
                        attempt += 1;
                        continue;
                    }
                    PlacementKind::Remote => {}
                }
            }
            break (result, actor);
        };

        // Park the warm worker for reuse on a clean run, or kill it on
        // error/cancel (a wedged worker must not be reused). Remote / schedulable
        // workers are registry-managed — never ours to pool/kill, just drop.
        if remote {
            drop(actor);
        } else {
            match &result {
                Ok(_) => self.release_bus_worker(&pool_key, actor).await,
                Err(_) => actor.worker.kill().await,
            }
        }

        // Write-back: persist the actor's final reply onto the child session so
        // the transcript survives and the NEXT activation sees it as history.
        // (run_child_spawn saves the session right after we return.)
        match result {
            Ok(Some(text)) => {
                if !text.is_empty() {
                    session.add_message(bamboo_agent_core::Message::assistant(text, None));
                }
                Ok(())
            }
            Ok(None) => Ok(()),
            Err(e) => Err(e),
        }
    }
}

/// The `{kind,host}` placement descriptor stamped onto a child session's metadata
/// under `"placement"` — read back by the storage index → `SessionSummary.placement`
/// → the UI's machine badge. `None` for `Local` (those fall through to the DTO's
/// default of this backend's own host). The value is a JSON string matching
/// `bamboo_storage::SessionPlacement { kind, host }`.
fn placement_metadata(placement: &Placement, host_label: Option<&str>) -> Option<String> {
    // Prefer the cluster node's own label/host (its metadata) when the placement
    // maps to a node; else fall back to the raw endpoint host / pool name.
    let value = match placement {
        Placement::Local => return None,
        Placement::Remote { endpoint } => serde_json::json!({
            "kind": "remote",
            "host": host_label.map(str::to_string).unwrap_or_else(|| host_of_endpoint(endpoint)),
        }),
        Placement::Schedulable { pool } => serde_json::json!({
            "kind": "remote",
            "host": host_label.unwrap_or(pool),
        }),
    };
    serde_json::to_string(&value).ok()
}

/// Extract the host from a `ws[s]://host:port[/path]` bus endpoint, for display.
fn host_of_endpoint(endpoint: &str) -> String {
    endpoint
        .trim()
        .trim_start_matches("wss://")
        .trim_start_matches("ws://")
        .split(['/', ':'])
        .next()
        .unwrap_or(endpoint)
        .to_string()
}

async fn reconcile_already_admitted_claim(
    binding: &SessionInboxRuntimeBinding,
    session: &mut Session,
    claim: &SessionInboxClaim,
) -> crate::runtime::runner::Result<()> {
    let latest = binding
        .storage
        .load_session(&session.id)
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "load canonical SessionInbox checkpoint for {}: {error}",
                session.id
            ))
        })?
        .ok_or_else(|| {
            AgentError::LLM(format!(
                "canonical SessionInbox target disappeared: {}",
                session.id
            ))
        })?;
    let Some(message) = latest
        .messages
        .iter()
        .find(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope))
        .cloned()
    else {
        return Err(AgentError::LLM(format!(
            "canonical admitted receipt for {} exists without transcript message {}",
            session.id, claim.envelope.id
        )));
    };
    if let Some(existing) = session
        .messages
        .iter_mut()
        .find(|existing| existing.id == message.id)
    {
        *existing = message;
    } else {
        session.add_message(message);
    }
    bamboo_domain::merge_session_inbox_admission(session, &latest);
    binding
        .inbox
        .ack(&session.id, claim)
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "ack recovered canonical SessionInbox claim {}: {error}",
                claim.envelope.id
            ))
        })
}

/// Checkpoint a worker-confirmed envelope into the canonical logical Session,
/// then create the permanent host receipt/remove its exact claim. This order is
/// the actor-side equivalent of the local state_bridge crash boundary.
async fn checkpoint_and_ack_canonical_claim(
    binding: &SessionInboxRuntimeBinding,
    session: &mut Session,
    claim: &SessionInboxClaim,
) -> crate::runtime::runner::Result<()> {
    if claim.envelope.target_session_id != session.id {
        return Err(AgentError::LLM(format!(
            "canonical SessionInbox claim target {} does not match active logical session {}",
            claim.envelope.target_session_id, session.id
        )));
    }
    if binding
        .inbox
        .was_admitted(&session.id, &claim.envelope.id)
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "inspect canonical admitted receipt {}: {error}",
                claim.envelope.id
            ))
        })?
    {
        return reconcile_already_admitted_claim(binding, session, claim).await;
    }

    let transcript_has_id = session
        .messages
        .iter()
        .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope));
    if session
        .messages
        .iter()
        .any(|message| message.id == claim.envelope.id.as_str())
        && !transcript_has_id
    {
        return Err(AgentError::LLM(format!(
            "canonical SessionInbox id {} collides with a non-matching transcript message",
            claim.envelope.id
        )));
    }
    let cursor_has_id = session
        .session_inbox_admission()
        .is_some_and(|state| state.contains(&claim.envelope.id));
    if cursor_has_id && !transcript_has_id {
        return Err(AgentError::LLM(format!(
            "canonical SessionInbox cursor exists without transcript message {}",
            claim.envelope.id
        )));
    }
    let before = session.clone();
    if !transcript_has_id {
        let message = claim.envelope.to_provider_message().map_err(|error| {
            AgentError::LLM(format!(
                "translate canonical SessionInbox envelope {}: {error}",
                claim.envelope.id
            ))
        })?;
        session.add_message(message);
    }
    session
        .session_inbox_admission_mut()
        .record(claim.envelope.id.clone(), claim.generation);
    session.updated_at = chrono::Utc::now();

    if let Err(error) = binding
        .persistence
        .checkpoint_runtime_session(session)
        .await
    {
        *session = before;
        return Err(AgentError::LLM(format!(
            "checkpoint canonical SessionInbox claim {}: {error}",
            claim.envelope.id
        )));
    }
    if !session
        .messages
        .iter()
        .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope))
    {
        *session = before;
        return Err(AgentError::LLM(format!(
            "canonical SessionInbox checkpoint lost typed transcript proof for {}",
            claim.envelope.id
        )));
    }
    binding
        .inbox
        .ack(&session.id, claim)
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "ack canonical SessionInbox claim {} after checkpoint: {error}",
                claim.envelope.id
            ))
        })
}

/// Durably seed claimed typed messages into the canonical host transcript
/// before dispatching them to any actor worker, while deliberately leaving the
/// admission cursor and `cur/` claims untouched.
///
/// This is the cross-placement lost-confirmation invariant: if worker A admits
/// and reasons over the batch but its confirmations are lost, a retry on worker
/// B receives a host snapshot already containing each stable typed message
/// exactly once. Worker B's local safe boundary then records/acks the same ids
/// without appending duplicates. Only an exact worker confirmation advances the
/// host cursor; only a durable cursor checkpoint precedes host ack.
async fn checkpoint_claim_context_before_dispatch(
    binding: &SessionInboxRuntimeBinding,
    session: &mut Session,
    claims: &[SessionInboxClaim],
) -> crate::runtime::runner::Result<()> {
    if claims.is_empty() {
        return Ok(());
    }
    let before = session.clone();
    for claim in claims {
        if claim.envelope.target_session_id != session.id {
            return Err(AgentError::LLM(format!(
                "canonical SessionInbox claim target {} does not match actor session {}",
                claim.envelope.target_session_id, session.id
            )));
        }
        let matching = session
            .messages
            .iter()
            .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope));
        if session
            .messages
            .iter()
            .any(|message| message.id == claim.envelope.id.as_str())
            && !matching
        {
            return Err(AgentError::LLM(format!(
                "canonical SessionInbox id {} collides before actor dispatch",
                claim.envelope.id
            )));
        }
        if session
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&claim.envelope.id))
            && !matching
        {
            return Err(AgentError::LLM(format!(
                "canonical SessionInbox cursor exists without transcript proof for {}",
                claim.envelope.id
            )));
        }
        if !matching {
            let message = claim.envelope.to_provider_message().map_err(|error| {
                AgentError::LLM(format!(
                    "translate canonical SessionInbox envelope {} before actor dispatch: {error}",
                    claim.envelope.id
                ))
            })?;
            session.add_message(message);
        }
    }
    session.updated_at = chrono::Utc::now();
    if let Err(error) = binding
        .persistence
        .checkpoint_runtime_session(session)
        .await
    {
        *session = before;
        return Err(AgentError::LLM(format!(
            "checkpoint canonical SessionInbox actor context: {error}"
        )));
    }
    for claim in claims {
        if !session
            .messages
            .iter()
            .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope))
        {
            *session = before;
            return Err(AgentError::LLM(format!(
                "actor context checkpoint lost typed transcript proof for {}",
                claim.envelope.id
            )));
        }
    }
    Ok(())
}

async fn claim_canonical_deliveries(
    binding: &SessionInboxRuntimeBinding,
    session: &mut Session,
    activation_run_id: &str,
    limit: usize,
) -> crate::runtime::runner::Result<Vec<(SessionInboxClaim, SessionMessageDelivery)>> {
    let claims = binding
        .inbox
        .claim(&session.id, limit)
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "claim canonical SessionInbox for active actor {}: {error}",
                session.id
            ))
        })?;
    if claims.is_empty() {
        return Ok(Vec::new());
    }
    let interrupt_generation = binding
        .inbox
        .inspect(&session.id)
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "inspect canonical SessionInbox activation policy for {}: {error}",
                session.id
            ))
        })?
        .interrupt_generation;
    let mut unconfirmed = Vec::with_capacity(claims.len());
    for claim in claims {
        if binding
            .inbox
            .was_admitted(&session.id, &claim.envelope.id)
            .await
            .map_err(|error| {
                AgentError::LLM(format!(
                    "inspect canonical SessionInbox claim {}: {error}",
                    claim.envelope.id
                ))
            })?
        {
            reconcile_already_admitted_claim(binding, session, &claim).await?;
            continue;
        }
        unconfirmed.push(claim);
    }
    checkpoint_claim_context_before_dispatch(binding, session, &unconfirmed).await?;

    let mut deliveries = Vec::with_capacity(unconfirmed.len());
    for claim in unconfirmed {
        // Cursor+transcript without the permanent tombstone is the recoverable
        // crash window after an exact worker confirmation was checkpointed but
        // before host ack removed `cur/`. Finish that ack without exposing the
        // message to another provider run.
        if session
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&claim.envelope.id))
        {
            binding
                .inbox
                .ack(&session.id, &claim)
                .await
                .map_err(|error| {
                    AgentError::LLM(format!(
                        "finish confirmed canonical SessionInbox ack {}: {error}",
                        claim.envelope.id
                    ))
                })?;
            continue;
        }
        let activation_policy = if claim.generation <= interrupt_generation {
            bamboo_domain::SessionActivationPolicy::InterruptSpecificWait
        } else {
            bamboo_domain::SessionActivationPolicy::RespectSpecificWait
        };
        let delivery = SessionMessageDelivery {
            target_session_id: session.id.clone(),
            envelope: claim.envelope.clone(),
            canonical_claim_generation: claim.generation,
            activation_run_id: activation_run_id.to_string(),
            activation_policy,
        };
        deliveries.push((claim, delivery));
    }
    Ok(deliveries)
}

async fn forward_next_canonical_claim(
    client: &mut dyn bamboo_subagent::ChildLink,
    binding: &SessionInboxRuntimeBinding,
    session: &mut Session,
    activation_run_id: &str,
    inflight: &mut VecDeque<SessionInboxClaim>,
) -> crate::runtime::runner::Result<()> {
    if !inflight.is_empty() {
        return Ok(());
    }
    let Some((claim, delivery)) =
        claim_canonical_deliveries(binding, session, activation_run_id, 1)
            .await?
            .pop()
    else {
        return Ok(());
    };
    client
        .send(ParentFrame::SessionMessage { delivery })
        .await
        .map_err(|error| {
            AgentError::LLM(format!(
                "forward canonical SessionInbox claim {} to active actor: {error}",
                claim.envelope.id
            ))
        })?;
    inflight.push_back(claim);
    Ok(())
}

/// Borrowed and per-run-owned inputs for one actor frame pump.
struct ActorDriveContext<'a> {
    client: &'a mut dyn bamboo_subagent::ChildLink,
    parent_session_id: &'a str,
    child_session_id: &'a str,
    child_attempt: u32,
    approval_registry: Option<&'a super::approval_registry::SharedApprovalRegistry>,
    approval_decider: Option<&'a Arc<dyn ChildApprovalDecider>>,
    approval_reviewer: Option<&'a Arc<dyn ChildApprovalReviewer>>,
    escalation_bridge: Option<bamboo_subagent::executor::HostBridge>,
    event_tx: &'a mpsc::Sender<AgentEvent>,
    cancel_token: &'a CancellationToken,
    live_rx: &'a mut mpsc::UnboundedReceiver<ParentFrame>,
    delivery_rx: &'a mut mpsc::UnboundedReceiver<u64>,
    logical_session: &'a mut Session,
    expected_permission_posture: Option<ExpectedPermissionPosture>,
    session_inbox_runtime: Option<&'a SessionInboxRuntimeBinding>,
    activation_run_id: Option<&'a str>,
    initial_inflight_claims: VecDeque<SessionInboxClaim>,
    first_frame_timeout: Option<Duration>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ExpectedPermissionPosture {
    policy_revision: u64,
    resolution: bamboo_domain::PermissionModeResolution,
    expected_audit_revision: Option<u64>,
    executor_mapping: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PermissionPostureHandshake {
    /// Legacy/custom actors were dispatched without a typed posture contract.
    NotRequired,
    /// The host dispatched an exact posture and no matching, durably recorded
    /// worker activation has arrived yet.
    Awaiting,
    /// One worker posture matched and its host-owned audit write succeeded.
    Confirmed,
}

impl PermissionPostureHandshake {
    fn new(expected: Option<&ExpectedPermissionPosture>) -> Self {
        if expected.is_some() {
            Self::Awaiting
        } else {
            Self::NotRequired
        }
    }

    fn is_awaiting(self) -> bool {
        self == Self::Awaiting
    }

    fn posture_was_confirmed(self) -> bool {
        self == Self::Confirmed
    }
}

fn permission_posture_seed_from_event(
    session: &Session,
    event: &AgentEvent,
) -> Result<Option<bamboo_domain::PermissionAuditSeed>, String> {
    let AgentEvent::PermissionPostureActivated {
        session_id,
        policy_revision,
        requested_mode,
        effective_mode,
        executor_mapping,
    } = event
    else {
        return Ok(None);
    };
    if session_id != &session.id {
        return Err("permission posture event targets a different logical session".to_string());
    }
    let requested = bamboo_domain::SessionPermissionMode::from_audit_str(requested_mode)
        .ok_or_else(|| "permission posture event has an invalid requested mode".to_string())?;
    let effective = bamboo_domain::PermissionMode::from_audit_str(effective_mode)
        .ok_or_else(|| "permission posture event has an invalid effective mode".to_string())?;
    let resolution = bamboo_domain::PermissionModeResolution {
        requested,
        effective,
    };
    if !resolution.is_consistent() {
        return Err("permission posture event has an inconsistent mode pair".to_string());
    }
    let current_requested = session
        .agent_runtime_state
        .as_ref()
        .map(|state| state.effective_permission_mode())
        .unwrap_or_default();
    if current_requested != requested {
        return Err("permission posture event is stale for the host typed mode".to_string());
    }
    let mapping_chars = executor_mapping.chars().count();
    if mapping_chars == 0 || mapping_chars > bamboo_domain::MAX_PERMISSION_EXECUTOR_MAPPING_CHARS {
        return Err("permission posture event has an invalid executor mapping".to_string());
    }
    Ok(Some(bamboo_domain::PermissionAuditSeed::new(
        *policy_revision,
        resolution,
        executor_mapping,
    )))
}

/// Pump child frames -> parent events until a terminal frame (or cancellation).
/// On success, yields the actor's final result text (for session write-back).
/// `live_rx` carries in-band frames (steering messages) from the live registry.
///
/// `escalation_bridge` (#68) is the per-run escalation host bridge CAPTURED BY
/// VALUE at spawn time in `execute_external_child` (NOT read live here): when a
/// non-bypass child re-proxies an approval request, this owned bridge routes it
/// UP to the parent run. Owning it for the call's lifetime is what lets a
/// fire-and-forget grandchild that outlives its spawning run still escalate to
/// the correct (then-current) parent bridge rather than a stale/overwritten one.
async fn drive(context: ActorDriveContext<'_>) -> crate::runtime::runner::Result<Option<String>> {
    let ActorDriveContext {
        client,
        parent_session_id,
        child_session_id,
        child_attempt,
        approval_registry,
        approval_decider,
        approval_reviewer,
        escalation_bridge,
        event_tx,
        cancel_token,
        live_rx,
        delivery_rx,
        logical_session,
        expected_permission_posture,
        session_inbox_runtime,
        activation_run_id,
        initial_inflight_claims,
        first_frame_timeout,
    } = context;

    // First-frame watchdog: a live worker emits its first frame (run-started /
    // first token) within seconds; total silence past the deadline means the
    // worker is dead (e.g. a pooled worker that exited right after checkout), so
    // its Run sits queued forever. We trip ONLY before the first frame — once any
    // frame arrives the worker is proven live and a legitimately long run (a slow
    // tool between tokens) never trips it.
    let mut got_first_frame = false;
    let mut first_frame_watch = first_frame_timeout.map(|d| Box::pin(tokio::time::sleep(d)));
    let mut inflight_claims = initial_inflight_claims;
    let strict_permission_events = expected_permission_posture.is_some();
    let mut permission_handshake =
        PermissionPostureHandshake::new(expected_permission_posture.as_ref());
    loop {
        tokio::select! {
            _ = cancel_token.cancelled() => {
                // fall through to the cancel handling below
                break;
            }
            _ = async {
                match first_frame_watch.as_mut() {
                    Some(s) => s.as_mut().await,
                    None => std::future::pending::<()>().await,
                }
            }, if !got_first_frame => {
                return Err(AgentError::WorkerUnresponsive(format!(
                    "child {child_session_id} produced no frame within {:?}",
                    first_frame_timeout.unwrap_or_default()
                )));
            }
            Some(_generation) = delivery_rx.recv(),
                if session_inbox_runtime.is_some() && activation_run_id.is_some() =>
            {
                forward_next_canonical_claim(
                    client,
                    session_inbox_runtime.expect("guarded"),
                    logical_session,
                    activation_run_id.expect("guarded"),
                    &mut inflight_claims,
                )
                .await?;
            }
            Some(frame) = live_rx.recv() => {
                // Forward in-band steering to the worker over the existing WS.
                if client.send(frame).await.is_err() {
                    tracing::warn!("live steering frame could not be sent; connection failing");
                }
            }
            frame = client.next_frame() => {
                // Any frame (event / approval / terminal / close / error) proves
                // the worker responded — disarm the first-frame watchdog.
                got_first_frame = true;
                first_frame_watch = None;
                match frame {
                    Ok(Some(ChildFrame::Event { event })) => {
                        // AgentEvent is serialized verbatim on the wire (zero mapping).
                        let ev = match serde_json::from_value::<AgentEvent>(event) {
                            Ok(ev) => ev,
                            Err(error) if strict_permission_events => {
                                return Err(AgentError::LLM(format!(
                                    "actor emitted malformed AgentEvent under a typed permission posture contract: {error}"
                                )));
                            }
                            Err(_) => continue,
                        };
                        if matches!(&ev, AgentEvent::PermissionPostureActivated { .. }) {
                            if permission_handshake.posture_was_confirmed() {
                                return Err(AgentError::LLM(
                                    "actor emitted a duplicate permission posture activation"
                                        .to_string(),
                                ));
                            }
                            let seed = permission_posture_seed_from_event(logical_session, &ev)
                                .map_err(AgentError::LLM)?
                                .ok_or_else(|| {
                                    AgentError::LLM(
                                        "actor permission posture event did not decode as a posture"
                                            .to_string(),
                                    )
                                })?;
                            if let Some(expected) = expected_permission_posture.as_ref() {
                                if seed.policy_revision != expected.policy_revision
                                    || seed.resolution != expected.resolution
                                {
                                    return Err(AgentError::LLM(
                                        "permission posture event does not match the host-dispatched policy"
                                            .to_string(),
                                    ));
                                }
                                if seed.executor_mapping() != expected.executor_mapping {
                                    return Err(AgentError::LLM(
                                        "permission posture event does not match the host-dispatched executor mapping"
                                            .to_string(),
                                    ));
                                }
                            }
                            if let Some(binding) = session_inbox_runtime {
                                let saved = binding
                                    .persistence
                                    .record_permission_posture_activation(
                                        &logical_session.id,
                                        expected_permission_posture
                                            .as_ref()
                                            .and_then(|expected| expected.expected_audit_revision),
                                        &seed,
                                    )
                                    .await
                                    .map_err(|error| {
                                        AgentError::LLM(format!(
                                            "persist child permission posture bootstrap: {error}"
                                        ))
                                    })?
                                    .ok_or_else(|| {
                                        AgentError::LLM(
                                            "persist child permission posture bootstrap: session not found"
                                                .to_string(),
                                        )
                                    })?;
                                let snapshot = bamboo_domain::PermissionAuditSnapshot::from_metadata(
                                    &saved.metadata,
                                )
                                .ok_or_else(|| {
                                    AgentError::LLM(
                                        "persisted child permission posture audit is incomplete"
                                            .to_string(),
                                    )
                                })?;
                                snapshot.write_to(&mut logical_session.metadata);
                            } else {
                                // In-memory/custom actor embeddings still use a host-owned
                                // clock. Durable server paths always take the atomic branch.
                                bamboo_domain::record_permission_audit(
                                    &mut logical_session.metadata,
                                    &seed,
                                    None,
                                )
                                .map_err(|error| {
                                    AgentError::LLM(format!(
                                        "record in-memory child permission posture: {error}"
                                    ))
                                })?;
                            }
                            // Confirmation is deliberately last: matching alone is not
                            // enough. The host-owned audit write must succeed first.
                            permission_handshake = PermissionPostureHandshake::Confirmed;
                        } else if permission_handshake.is_awaiting() {
                            return Err(AgentError::LLM(
                                "actor emitted an execution event before permission posture confirmation"
                                    .to_string(),
                            ));
                        }
                        let _ = event_tx.send(ev).await;
                    }
                    Ok(Some(ChildFrame::ApprovalRequest { id, body })) => {
                        if permission_handshake.is_awaiting() {
                            return Err(AgentError::LLM(
                                "actor requested approval before permission posture confirmation"
                                    .to_string(),
                            ));
                        }
                        // Phase 2: a worker proxied a gated-tool approval back to
                        // the host. The WORKER side is live — its executor installs
                        // a per-run task-local `ApprovalProxy` (subagent_worker.rs)
                        // that calls `host.approval_call`, so this frame arrives
                        // when a child hits `ConfirmationRequired`.
                        if let Some(reviewer) = approval_reviewer
                            .cloned()
                            .or_else(child_approval_reviewer)
                        {
                            // Phase 6, Part B: a BYPASSED parent worker
                            // model-reviews its children's forced-ask (dangerous)
                            // actions. The review is an LLM call, so run it OFF
                            // the frame pump in a spawned task and deliver the
                            // verdict async via the live channel — the pump keeps
                            // forwarding events and the agent loop never blocks. A
                            // timeout denies a hung review so the child can't hang.
                            let child = child_session_id.to_string();
                            let parent = parent_session_id.to_string();
                            let req_id = id.clone();
                            let body = body.clone();
                            let registry = approval_registry.cloned();
                            tokio::spawn(async move {
                                let approved = tokio::time::timeout(
                                    CHILD_APPROVAL_TIMEOUT,
                                    reviewer.review(&parent, &child, &body),
                                )
                                .await
                                .unwrap_or(false);
                                super::live::deliver_approval_scoped(
                                    registry.as_ref(),
                                    &child,
                                    child_attempt,
                                    &req_id,
                                    approved,
                                );
                            });
                        } else if approval_decider.is_some() {
                            // A decider is wired (policy / auto): decide promptly
                            // and reply inline. (Must not block the pump — see the
                            // `ChildApprovalDecider` doc.)
                            let approved =
                                decide_child_approval(approval_decider, child_session_id, &body)
                                    .await;
                            if client
                                .send(ParentFrame::ApprovalReply { id, approved })
                                .await
                                .is_err()
                            {
                                tracing::warn!(
                                    "failed to answer approval_request; connection failing"
                                );
                            }
                        } else if let Some(host) = escalation_bridge.clone() {
                            // Non-bypass WORKER: ESCALATE up our own actor link
                            // (re-proxy) so the request chains to our parent — and
                            // up every level until a bypass level or the top
                            // orchestrator's model reviewer decides. With no such
                            // reviewer the top level fails closed. Off-loop so the
                            // pump never blocks; relay the reply down to the child.
                            let child = child_session_id.to_string();
                            let req_id = id.clone();
                            let body = body.clone();
                            let registry = approval_registry.cloned();
                            tokio::spawn(async move {
                                let approved = match tokio::time::timeout(
                                    CHILD_APPROVAL_TIMEOUT,
                                    host.approval_call(body),
                                )
                                .await
                                {
                                    Ok(Ok(reply)) => reply
                                        .get("approved")
                                        .and_then(|v| v.as_bool())
                                        .unwrap_or(false),
                                    // Transport error or timeout ⇒ fail closed.
                                    _ => false,
                                };
                                super::live::deliver_approval_scoped(
                                    registry.as_ref(),
                                    &child,
                                    child_attempt,
                                    &req_id,
                                    approved,
                                );
                            });
                        } else {
                            // There is no parent-agent reviewer or upstream actor
                            // to own this decision. Never open a manual/UI approval
                            // path: forced-ask is parent-reviewed or fail-closed.
                            tracing::warn!(
                                parent_session_id,
                                child_session_id,
                                request_id = %id,
                                "forced-ask request has no parent-agent reviewer; denying"
                            );
                            if client
                                .send(ParentFrame::ApprovalReply {
                                    id,
                                    approved: false,
                                })
                                .await
                                .is_err()
                            {
                                tracing::warn!(
                                    "failed to send fail-closed approval reply; connection failing"
                                );
                            }
                        }
                    }
                    Ok(Some(ChildFrame::SessionMessageAdmitted { confirmation })) => {
                        let Some(binding) = session_inbox_runtime else {
                            tracing::warn!(
                                child_session_id,
                                "ignoring SessionInbox confirmation without a runtime binding"
                            );
                            continue;
                        };
                        let Some(bound_run_id) = activation_run_id else {
                            tracing::warn!(
                                child_session_id,
                                "ignoring SessionInbox confirmation without an activation owner"
                            );
                            continue;
                        };
                        let Some(claim) = inflight_claims.front() else {
                            tracing::warn!(
                                child_session_id,
                                envelope_id = %confirmation.envelope_id,
                                "rejecting stale SessionInbox confirmation with no in-flight canonical claim"
                            );
                            continue;
                        };
                        let exact = confirmation.target_session_id == logical_session.id
                            && confirmation.envelope_id == claim.envelope.id.as_str()
                            && confirmation.canonical_claim_generation == claim.generation
                            && confirmation.activation_run_id == bound_run_id;
                        if !exact
                            || !binding
                                .router
                                .owns_run(&logical_session.id, bound_run_id)
                                .await
                        {
                            tracing::warn!(
                                child_session_id,
                                expected_target = %logical_session.id,
                                received_target = %confirmation.target_session_id,
                                expected_envelope_id = %claim.envelope.id,
                                received_envelope_id = %confirmation.envelope_id,
                                expected_generation = claim.generation,
                                received_generation = confirmation.canonical_claim_generation,
                                expected_run_id = bound_run_id,
                                received_run_id = %confirmation.activation_run_id,
                                "rejecting stale or mismatched SessionInbox admission confirmation"
                            );
                            continue;
                        }
                        let claim = inflight_claims
                            .pop_front()
                            .expect("validated in-flight canonical claim");
                        // On failure the durable canonical cur file remains
                        // recoverable for the next owner.
                        checkpoint_and_ack_canonical_claim(binding, logical_session, &claim)
                            .await?;
                        // Ordered single-consumer: only after the exact prior
                        // claim is checkpointed+acked may the driver claim and
                        // forward the next envelope.
                        if inflight_claims.is_empty() {
                            forward_next_canonical_claim(
                                client,
                                binding,
                                logical_session,
                                bound_run_id,
                                &mut inflight_claims,
                            )
                            .await?;
                        }
                    }
                    Ok(Some(ChildFrame::Terminal { status, result, error, .. })) => {
                        if permission_handshake.is_awaiting() {
                            return Err(AgentError::LLM(
                                "actor terminated before permission posture confirmation"
                                    .to_string(),
                            ));
                        }
                        if let Some(claim) = inflight_claims.front() {
                            return Err(AgentError::LLM(format!(
                                "actor terminated before durably admitting SessionInbox message {}; canonical claim remains recoverable",
                                claim.envelope.id
                            )));
                        }
                        return match status {
                            TerminalStatus::Completed => Ok(result),
                            TerminalStatus::Cancelled => Err(AgentError::Cancelled),
                            TerminalStatus::Error => Err(AgentError::LLM(
                                error.unwrap_or_else(|| "actor child errored".to_string()),
                            )),
                            // The suspend/resume round-trip (host re-dispatch of a
                            // nested parent) is not wired here yet; a worker in
                            // this build never emits Suspended, so this is
                            // unreachable in practice.
                            TerminalStatus::Suspended => Err(AgentError::LLM(
                                "nested sub-agent suspend received but resume transport is not wired"
                                    .to_string(),
                            )),
                        };
                    }
                    Ok(None) => {
                        return Err(AgentError::LLM(
                            "actor child closed before terminal".to_string(),
                        ));
                    }
                    Err(e) => {
                        return Err(AgentError::LLM(format!("actor transport error: {e}")));
                    }
                }
            }
        }
    }

    // Only reached on cancellation: ask the child to stop (best-effort), then report cancelled.
    let _ = client.send(ParentFrame::Cancel).await;
    Err(AgentError::Cancelled)
}

/// The assignment text = the child session's latest user message (falls back to its title).
fn project_id_for_actor_run(
    session: &Session,
) -> Result<Option<bamboo_domain::ProjectId>, AgentError> {
    match crate::project_context::ProjectContextResolver::session_project_identity(session) {
        crate::project_context::SessionProjectIdentity::Assigned(project_id) => {
            Ok(Some(project_id))
        }
        crate::project_context::SessionProjectIdentity::Unassigned => Ok(None),
        crate::project_context::SessionProjectIdentity::Invalid { raw, message } => {
            Err(AgentError::LLM(format!(
                "child session carries an invalid Project identity '{raw}': {message}"
            )))
        }
    }
}

fn logical_identity_for_actor_run(session: &Session, job: &SpawnJob) -> LogicalSessionIdentity {
    LogicalSessionIdentity {
        session_id: session.id.clone(),
        parent_session_id: session
            .parent_session_id
            .clone()
            .or_else(|| Some(job.parent_session_id.clone())),
        root_session_id: if session.root_session_id.trim().is_empty() {
            job.parent_session_id.clone()
        } else {
            session.root_session_id.clone()
        },
    }
}

fn extract_assignment(session: &Session) -> String {
    session
        .messages
        .iter()
        .rev()
        .find(|m| matches!(m.role, Role::User))
        .map(|m| m.content.clone())
        .unwrap_or_else(|| {
            session
                .metadata
                .get("title")
                .cloned()
                .unwrap_or_else(|| "Execute task".to_string())
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SessionActivationRouter;
    use bamboo_domain::{RuntimeSessionPersistence, SessionInboxPort, Storage};

    #[test]
    fn actor_preflight_counts_only_current_session_scoped_denies() {
        let config = bamboo_tools::permission::PermissionConfig::new();
        let secret_matcher = "TOP_SECRET_ACTOR_DENY_MATCHER";
        config.deny_scoped_session_permission(
            "target-session",
            bamboo_tools::permission::PermissionType::ExecuteCommand,
            secret_matcher,
        );
        config.deny_scoped_session_permission(
            "other-session",
            bamboo_tools::permission::PermissionType::WriteFile,
            "/other/**",
        );

        assert_eq!(
            active_scoped_session_deny_count(&config, "target-session"),
            1
        );
        assert_eq!(
            active_scoped_session_deny_count(&config, "clean-session"),
            0
        );
        let error = ensure_no_active_scoped_session_denies(&config, "target-session")
            .unwrap_err()
            .to_string();
        assert!(!error.contains(secret_matcher));
        ensure_no_active_scoped_session_denies(&config, "clean-session")
            .expect("another session's deny must not block this activation");
    }

    #[test]
    fn permission_posture_event_rejects_oversized_executor_mapping() {
        let session = Session::new("mapping-bound", "model");
        let event = AgentEvent::PermissionPostureActivated {
            session_id: session.id.clone(),
            policy_revision: 1,
            requested_mode: "default".to_string(),
            effective_mode: "default".to_string(),
            executor_mapping: "x".repeat(bamboo_domain::MAX_PERMISSION_EXECUTOR_MAPPING_CHARS + 1),
        };

        assert!(permission_posture_seed_from_event(&session, &event)
            .unwrap_err()
            .contains("executor mapping"));
    }

    #[test]
    fn remote_audit_revision_and_timestamp_fields_cannot_poison_host_audit() {
        let mut session = Session::new("host-resigns-audit", "model");
        let hostile_timestamp = "9".repeat(1024);
        let event: AgentEvent = serde_json::from_value(serde_json::json!({
            "type": "permission_posture_activated",
            "session_id": session.id.clone(),
            "policy_revision": 31,
            "requested_mode": "default",
            "effective_mode": "default",
            "executor_mapping": "codex_exec:approval_policy=never",
            "audit_revision": u64::MAX,
            "transitioned_at": hostile_timestamp,
        }))
        .expect("unknown remote audit fields are ignored by the typed event");
        let seed = permission_posture_seed_from_event(&session, &event)
            .unwrap()
            .expect("permission event");

        let host_revision =
            bamboo_domain::record_permission_audit(&mut session.metadata, &seed, None).unwrap();
        let host_audit = bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata)
            .expect("host-generated complete audit");
        assert_eq!(host_audit.audit_revision, host_revision);
        assert!(host_audit.audit_revision < bamboo_domain::MAX_PERMISSION_AUDIT_REVISION);
        assert_ne!(host_audit.transitioned_at, hostile_timestamp);
        assert!(chrono::DateTime::parse_from_rfc3339(&host_audit.transitioned_at).is_ok());
    }

    struct ActorFaultingPersistence {
        inner: Arc<bamboo_storage::LockedSessionStore>,
        fail_checkpoint_once: std::sync::atomic::AtomicBool,
    }

    #[async_trait]
    impl RuntimeSessionPersistence for ActorFaultingPersistence {
        async fn save_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
            self.inner.merge_save_runtime(session).await
        }

        async fn checkpoint_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
            if self
                .fail_checkpoint_once
                .swap(false, std::sync::atomic::Ordering::SeqCst)
            {
                return Err(std::io::Error::other("injected actor checkpoint failure"));
            }
            self.inner.checkpoint_runtime_session(session).await
        }

        async fn load_runtime_session(&self, session_id: &str) -> std::io::Result<Option<Session>> {
            self.inner.storage().load_session(session_id).await
        }
    }

    struct ActorFailBeforeAckInbox {
        inner: Arc<dyn SessionInboxPort>,
        fail_once: std::sync::atomic::AtomicBool,
    }

    #[async_trait]
    impl SessionInboxPort for ActorFailBeforeAckInbox {
        async fn deliver(
            &self,
            envelope: &bamboo_domain::SessionMessageEnvelope,
        ) -> Result<bamboo_domain::SessionInboxReceipt, bamboo_domain::SessionInboxError> {
            self.inner.deliver(envelope).await
        }

        async fn mark_activation_eligible(
            &self,
            target_session_id: &str,
            generation: u64,
            policy: bamboo_domain::SessionActivationPolicy,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            self.inner
                .mark_activation_eligible(target_session_id, generation, policy)
                .await
        }

        async fn claim(
            &self,
            target_session_id: &str,
            limit: usize,
        ) -> Result<Vec<SessionInboxClaim>, bamboo_domain::SessionInboxError> {
            self.inner.claim(target_session_id, limit).await
        }

        async fn was_admitted(
            &self,
            target_session_id: &str,
            id: &bamboo_domain::SessionMessageId,
        ) -> Result<bool, bamboo_domain::SessionInboxError> {
            self.inner.was_admitted(target_session_id, id).await
        }

        async fn ack(
            &self,
            target_session_id: &str,
            claim: &SessionInboxClaim,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            if self
                .fail_once
                .swap(false, std::sync::atomic::Ordering::SeqCst)
            {
                return Err(bamboo_domain::SessionInboxError::Storage(
                    "injected actor pre-ack failure".to_string(),
                ));
            }
            self.inner.ack(target_session_id, claim).await
        }

        async fn inspect(
            &self,
            target_session_id: &str,
        ) -> Result<bamboo_domain::SessionInboxBacklog, bamboo_domain::SessionInboxError> {
            self.inner.inspect(target_session_id).await
        }
    }

    async fn actor_inbox_fixture(
        session_id: &str,
    ) -> (
        tempfile::TempDir,
        Arc<bamboo_storage::SessionStoreV2>,
        Arc<bamboo_storage::LockedSessionStore>,
        Arc<dyn SessionInboxPort>,
        Session,
        SessionInboxClaim,
    ) {
        let temp = tempfile::tempdir().unwrap();
        let store = Arc::new(
            bamboo_storage::SessionStoreV2::new(temp.path().to_path_buf())
                .await
                .unwrap(),
        );
        let storage: Arc<dyn Storage> = store.clone();
        let locked = Arc::new(bamboo_storage::LockedSessionStore::new(storage));
        let inbox: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let session = Session::new(session_id, "model");
        store.save_session(&session).await.unwrap();
        let mut envelope =
            bamboo_domain::SessionMessageEnvelope::user_input(session_id, "actor follow-up");
        envelope.id =
            bamboo_domain::SessionMessageId::parse(format!("{session_id}-message")).unwrap();
        let receipt = inbox.deliver(&envelope).await.unwrap();
        inbox
            .mark_activation_eligible(
                session_id,
                receipt.generation,
                bamboo_domain::SessionActivationPolicy::InterruptSpecificWait,
            )
            .await
            .unwrap();
        let claim = inbox.claim(session_id, 1).await.unwrap().remove(0);
        (temp, store, locked, inbox, session, claim)
    }

    fn actor_binding(
        store: Arc<bamboo_storage::SessionStoreV2>,
        inbox: Arc<dyn SessionInboxPort>,
        persistence: Arc<dyn RuntimeSessionPersistence>,
    ) -> SessionInboxRuntimeBinding {
        let storage: Arc<dyn Storage> = store;
        SessionInboxRuntimeBinding {
            router: SessionActivationRouter::new(),
            inbox,
            storage,
            persistence,
        }
    }

    #[tokio::test]
    async fn actor_mismatched_typed_marker_id_collision_never_acks() {
        let (_temp, store, locked, inbox, mut session, claim) =
            actor_inbox_fixture("actor-live-id-collision").await;
        let mut forged = claim.envelope.to_provider_message().unwrap();
        forged.metadata = Some(serde_json::json!({
            "session_message": {
                "id": claim.envelope.id,
                "target_session_id": "different-session"
            }
        }));
        session.add_message(forged);
        let persistence: Arc<dyn RuntimeSessionPersistence> = locked;
        let binding = actor_binding(store, inbox.clone(), persistence);

        assert!(
            checkpoint_and_ack_canonical_claim(&binding, &mut session, &claim)
                .await
                .is_err()
        );
        assert_eq!(inbox.inspect(&session.id).await.unwrap().claimed, 1);
        assert!(!inbox
            .was_admitted(&session.id, &claim.envelope.id)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn actor_concurrent_durable_id_collision_after_claim_never_acks() {
        let (_temp, store, locked, inbox, mut session, claim) =
            actor_inbox_fixture("actor-durable-id-collision").await;
        let mut concurrent = store.load_session(&session.id).await.unwrap().unwrap();
        let mut forged = bamboo_agent_core::Message::user("concurrent actor collision");
        forged.id = claim.envelope.id.to_string();
        concurrent.add_message(forged);
        store.save_session(&concurrent).await.unwrap();
        let persistence: Arc<dyn RuntimeSessionPersistence> = locked;
        let binding = actor_binding(store.clone(), inbox.clone(), persistence);

        assert!(
            checkpoint_and_ack_canonical_claim(&binding, &mut session, &claim)
                .await
                .is_err()
        );
        assert_eq!(inbox.inspect(&session.id).await.unwrap().claimed, 1);
        assert!(!inbox
            .was_admitted(&session.id, &claim.envelope.id)
            .await
            .unwrap());
        let durable = store.load_session(&session.id).await.unwrap().unwrap();
        assert!(!durable.messages.iter().any(|message| {
            bamboo_domain::is_matching_session_message(message, &claim.envelope)
        }));
    }

    #[tokio::test]
    async fn actor_concurrent_durable_typed_body_mismatch_never_acks() {
        let (_temp, store, locked, inbox, mut session, claim) =
            actor_inbox_fixture("actor-durable-typed-body-collision").await;
        let mut different = claim.envelope.clone();
        different.body = bamboo_domain::SessionMessageBody::Content(
            bamboo_domain::SessionMessageContent::text("forged actor body"),
        );
        let mut concurrent = store.load_session(&session.id).await.unwrap().unwrap();
        concurrent.add_message(different.to_provider_message().unwrap());
        store.save_session(&concurrent).await.unwrap();
        let persistence: Arc<dyn RuntimeSessionPersistence> = locked;
        let binding = actor_binding(store.clone(), inbox.clone(), persistence);

        assert!(
            checkpoint_and_ack_canonical_claim(&binding, &mut session, &claim)
                .await
                .is_err()
        );
        assert_eq!(inbox.inspect(&session.id).await.unwrap().claimed, 1);
        assert!(!inbox
            .was_admitted(&session.id, &claim.envelope.id)
            .await
            .unwrap());
        let durable = store.load_session(&session.id).await.unwrap().unwrap();
        assert!(!durable
            .messages
            .iter()
            .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope)));
    }

    #[tokio::test]
    async fn actor_checkpoint_failure_rolls_back_and_restart_admits_once() {
        let (_temp, store, locked, inbox, mut session, claim) =
            actor_inbox_fixture("actor-checkpoint-failure").await;
        let envelope_id = claim.envelope.id.clone();
        let fault: Arc<dyn RuntimeSessionPersistence> = Arc::new(ActorFaultingPersistence {
            inner: locked.clone(),
            fail_checkpoint_once: std::sync::atomic::AtomicBool::new(true),
        });
        let binding = actor_binding(store.clone(), inbox.clone(), fault);

        assert!(
            checkpoint_and_ack_canonical_claim(&binding, &mut session, &claim)
                .await
                .is_err()
        );
        assert!(!session
            .messages
            .iter()
            .any(|message| message.id == envelope_id.as_str()));
        assert_eq!(inbox.inspect(&session.id).await.unwrap().claimed, 1);
        assert!(!inbox.was_admitted(&session.id, &envelope_id).await.unwrap());

        let reopened: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let recovered = reopened.claim(&session.id, 1).await.unwrap().remove(0);
        let persistence: Arc<dyn RuntimeSessionPersistence> = locked;
        let binding = actor_binding(store.clone(), reopened.clone(), persistence);
        let mut restarted = store.load_session(&session.id).await.unwrap().unwrap();
        checkpoint_and_ack_canonical_claim(&binding, &mut restarted, &recovered)
            .await
            .unwrap();
        assert_eq!(
            restarted
                .messages
                .iter()
                .filter(|message| message.id == envelope_id.as_str())
                .count(),
            1
        );
        assert!(reopened
            .was_admitted(&session.id, &envelope_id)
            .await
            .unwrap());
        let backlog = reopened.inspect(&session.id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
    }

    #[tokio::test]
    async fn actor_checkpoint_success_pre_ack_failure_recovers_without_duplicate() {
        let (_temp, store, locked, real_inbox, mut session, claim) =
            actor_inbox_fixture("actor-pre-ack-failure").await;
        let envelope_id = claim.envelope.id.clone();
        let faulted: Arc<dyn SessionInboxPort> = Arc::new(ActorFailBeforeAckInbox {
            inner: real_inbox.clone(),
            fail_once: std::sync::atomic::AtomicBool::new(true),
        });
        let persistence: Arc<dyn RuntimeSessionPersistence> = locked.clone();
        let binding = actor_binding(store.clone(), faulted, persistence);

        assert!(
            checkpoint_and_ack_canonical_claim(&binding, &mut session, &claim)
                .await
                .is_err()
        );
        let durable = store.load_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            durable
                .messages
                .iter()
                .filter(|message| message.id == envelope_id.as_str())
                .count(),
            1
        );
        assert_eq!(real_inbox.inspect(&session.id).await.unwrap().claimed, 1);
        assert!(!real_inbox
            .was_admitted(&session.id, &envelope_id)
            .await
            .unwrap());

        let reopened: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let recovered = reopened.claim(&session.id, 1).await.unwrap().remove(0);
        let persistence: Arc<dyn RuntimeSessionPersistence> = locked;
        let binding = actor_binding(store.clone(), reopened.clone(), persistence);
        let mut restarted = durable;
        checkpoint_and_ack_canonical_claim(&binding, &mut restarted, &recovered)
            .await
            .unwrap();
        assert_eq!(
            restarted
                .messages
                .iter()
                .filter(|message| message.id == envelope_id.as_str())
                .count(),
            1
        );
        assert!(reopened
            .was_admitted(&session.id, &envelope_id)
            .await
            .unwrap());
        let backlog = reopened.inspect(&session.id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
    }

    struct ConfirmationSequenceLink {
        frames: VecDeque<ChildFrame>,
        sent: Vec<ParentFrame>,
    }

    #[async_trait]
    impl bamboo_subagent::ChildLink for ConfirmationSequenceLink {
        async fn send(&mut self, frame: ParentFrame) -> bamboo_subagent::TransportResult<()> {
            self.sent.push(frame);
            Ok(())
        }

        async fn next_frame(&mut self) -> bamboo_subagent::TransportResult<Option<ChildFrame>> {
            match self.frames.pop_front() {
                Some(frame) => Ok(Some(frame)),
                None => std::future::pending().await,
            }
        }
    }

    fn admission_confirmation(
        session_id: &str,
        claim: &SessionInboxClaim,
        run_id: &str,
    ) -> bamboo_subagent::proto::SessionMessageAdmissionConfirmation {
        bamboo_subagent::proto::SessionMessageAdmissionConfirmation {
            target_session_id: session_id.to_string(),
            envelope_id: claim.envelope.id.to_string(),
            canonical_claim_generation: claim.generation,
            activation_run_id: run_id.to_string(),
        }
    }

    fn expected_default_permission_posture(policy_revision: u64) -> ExpectedPermissionPosture {
        ExpectedPermissionPosture {
            policy_revision,
            resolution: bamboo_domain::PermissionModeResolution {
                requested: bamboo_domain::SessionPermissionMode::Default,
                effective: bamboo_domain::PermissionMode::Default,
            },
            expected_audit_revision: None,
            executor_mapping: "test_actor:permission_mode=default".to_string(),
        }
    }

    fn permission_posture_frame(session_id: &str, policy_revision: u64) -> ChildFrame {
        ChildFrame::Event {
            event: serde_json::to_value(AgentEvent::PermissionPostureActivated {
                session_id: session_id.to_string(),
                policy_revision,
                requested_mode: "default".to_string(),
                effective_mode: "default".to_string(),
                executor_mapping: "test_actor:permission_mode=default".to_string(),
            })
            .expect("serialize permission posture event"),
        }
    }

    fn actor_event_frame(event: AgentEvent) -> ChildFrame {
        ChildFrame::Event {
            event: serde_json::to_value(event).expect("serialize actor event"),
        }
    }

    fn completed_actor_frame() -> ChildFrame {
        ChildFrame::Terminal {
            status: TerminalStatus::Completed,
            result: Some("done".to_string()),
            error: None,
            transcript: Vec::new(),
        }
    }

    async fn drive_permission_handshake_frames(
        session_id: &str,
        frames: impl IntoIterator<Item = ChildFrame>,
        expected: ExpectedPermissionPosture,
    ) -> (
        crate::runtime::runner::Result<Option<String>>,
        Session,
        Vec<AgentEvent>,
        Vec<ParentFrame>,
    ) {
        let mut link = ConfirmationSequenceLink {
            frames: frames.into_iter().collect(),
            sent: Vec::new(),
        };
        let (event_tx, mut event_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();
        let (_live_tx, mut live_rx) = mpsc::unbounded_channel();
        let (_delivery_tx, mut delivery_rx) = mpsc::unbounded_channel();
        let mut session = Session::new(session_id, "model");
        let result = drive(ActorDriveContext {
            client: &mut link,
            parent_session_id: "permission-parent",
            child_session_id: session_id,
            child_attempt: 0,
            approval_registry: None,
            approval_decider: None,
            approval_reviewer: None,
            escalation_bridge: None,
            event_tx: &event_tx,
            cancel_token: &cancel,
            live_rx: &mut live_rx,
            delivery_rx: &mut delivery_rx,
            logical_session: &mut session,
            expected_permission_posture: Some(expected),
            session_inbox_runtime: None,
            activation_run_id: None,
            initial_inflight_claims: VecDeque::new(),
            first_frame_timeout: Some(Duration::from_secs(1)),
        })
        .await;
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect();
        (result, session, events, link.sent)
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_terminal_without_posture() {
        let session_id = "permission-missing";
        let (result, session, events, _) = drive_permission_handshake_frames(
            session_id,
            [completed_actor_frame()],
            expected_default_permission_posture(7),
        )
        .await;

        assert!(result
            .unwrap_err()
            .to_string()
            .contains("terminated before permission posture confirmation"));
        assert!(events.is_empty());
        assert!(bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata).is_none());
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_malformed_agent_event() {
        let session_id = "permission-malformed";
        let (result, session, events, _) = drive_permission_handshake_frames(
            session_id,
            [ChildFrame::Event {
                event: serde_json::json!({"type": "token", "content": 42}),
            }],
            expected_default_permission_posture(7),
        )
        .await;

        assert!(result
            .unwrap_err()
            .to_string()
            .contains("malformed AgentEvent"));
        assert!(events.is_empty());
        assert!(bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata).is_none());
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_execution_event_before_posture() {
        let session_id = "permission-early-event";
        let early_events = [
            (
                "progress",
                AgentEvent::RunnerProgress {
                    session_id: session_id.to_string(),
                    round_count: 1,
                },
            ),
            (
                "token",
                AgentEvent::Token {
                    content: "must-not-forward".to_string(),
                },
            ),
            (
                "tool",
                AgentEvent::ToolStart {
                    tool_call_id: "early-tool".to_string(),
                    tool_name: "Read".to_string(),
                    arguments: serde_json::json!({"file_path": "README.md"}),
                },
            ),
        ];
        for (kind, event) in early_events {
            let (result, session, events, _) = drive_permission_handshake_frames(
                session_id,
                [
                    actor_event_frame(event),
                    permission_posture_frame(session_id, 7),
                    completed_actor_frame(),
                ],
                expected_default_permission_posture(7),
            )
            .await;

            assert!(
                result
                    .unwrap_err()
                    .to_string()
                    .contains("execution event before permission posture confirmation"),
                "{kind} must fail closed before posture"
            );
            assert!(events.is_empty(), "{kind} must not be forwarded");
            assert!(
                bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata).is_none(),
                "{kind} must not advance the permission audit"
            );
        }
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_approval_before_posture() {
        let session_id = "permission-early-approval";
        let (result, session, events, sent) = drive_permission_handshake_frames(
            session_id,
            [ChildFrame::ApprovalRequest {
                id: "approval-before-posture".to_string(),
                body: serde_json::json!({
                    "tool_name": "Bash",
                    "permission": "execute",
                    "resource": "echo must-not-run"
                }),
            }],
            expected_default_permission_posture(7),
        )
        .await;

        assert!(result
            .unwrap_err()
            .to_string()
            .contains("requested approval before permission posture confirmation"));
        assert!(events.is_empty());
        assert!(
            sent.is_empty(),
            "an unconfirmed actor must receive no approval reply"
        );
        assert!(bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata).is_none());
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_mismatched_posture() {
        let session_id = "permission-mismatch";
        let (result, session, events, _) = drive_permission_handshake_frames(
            session_id,
            [permission_posture_frame(session_id, 8)],
            expected_default_permission_posture(7),
        )
        .await;

        assert!(result
            .unwrap_err()
            .to_string()
            .contains("does not match the host-dispatched policy"));
        assert!(events.is_empty());
        assert!(bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata).is_none());
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_untrusted_executor_mapping() {
        let session_id = "permission-hostile-mapping";
        for hostile_mapping in [
            "wrong_executor:permission_mode=default",
            "test_actor:permission_mode=default;credential=must-not-persist",
        ] {
            let frame = ChildFrame::Event {
                event: serde_json::to_value(AgentEvent::PermissionPostureActivated {
                    session_id: session_id.to_string(),
                    policy_revision: 7,
                    requested_mode: "default".to_string(),
                    effective_mode: "default".to_string(),
                    executor_mapping: hostile_mapping.to_string(),
                })
                .expect("serialize hostile posture fixture"),
            };
            let (result, session, events, _) = drive_permission_handshake_frames(
                session_id,
                [frame],
                expected_default_permission_posture(7),
            )
            .await;

            let error = result.unwrap_err().to_string();
            assert!(error.contains("host-dispatched executor mapping"));
            assert!(
                !error.contains(hostile_mapping),
                "untrusted mapping must not be reflected in host errors"
            );
            assert!(events.is_empty());
            assert!(
                bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata).is_none(),
                "untrusted mapping must not reach durable or in-memory audit state"
            );
        }
    }

    #[tokio::test]
    async fn actor_permission_handshake_rejects_duplicate_posture() {
        let session_id = "permission-duplicate";
        let (result, session, events, _) = drive_permission_handshake_frames(
            session_id,
            [
                permission_posture_frame(session_id, 7),
                permission_posture_frame(session_id, 7),
                completed_actor_frame(),
            ],
            expected_default_permission_posture(7),
        )
        .await;

        assert!(result
            .unwrap_err()
            .to_string()
            .contains("duplicate permission posture activation"));
        assert_eq!(
            events.len(),
            1,
            "only the confirmed posture may be forwarded"
        );
        assert!(matches!(
            events[0],
            AgentEvent::PermissionPostureActivated { .. }
        ));
        let audit = bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata)
            .expect("the first matching posture must be recorded");
        assert_eq!(audit.policy_revision, 7);
    }

    #[tokio::test]
    async fn actor_permission_handshake_happy_path_persists_before_forwarding_execution() {
        let session_id = "permission-happy";
        let (result, session, events, _) = drive_permission_handshake_frames(
            session_id,
            [
                permission_posture_frame(session_id, 7),
                actor_event_frame(AgentEvent::RunnerProgress {
                    session_id: session_id.to_string(),
                    round_count: 1,
                }),
                actor_event_frame(AgentEvent::Token {
                    content: "working".to_string(),
                }),
                actor_event_frame(AgentEvent::ToolStart {
                    tool_call_id: "tool-1".to_string(),
                    tool_name: "Read".to_string(),
                    arguments: serde_json::json!({"file_path": "README.md"}),
                }),
                completed_actor_frame(),
            ],
            expected_default_permission_posture(7),
        )
        .await;

        assert_eq!(result.unwrap().as_deref(), Some("done"));
        assert!(matches!(
            events.as_slice(),
            [
                AgentEvent::PermissionPostureActivated { .. },
                AgentEvent::RunnerProgress { .. },
                AgentEvent::Token { .. },
                AgentEvent::ToolStart { .. }
            ]
        ));
        let audit = bamboo_domain::PermissionAuditSnapshot::from_metadata(&session.metadata)
            .expect("matching posture must be recorded before execution events are accepted");
        assert_eq!(audit.policy_revision, 7);
        assert_eq!(audit.executor_mapping, "test_actor:permission_mode=default");
    }

    #[tokio::test]
    async fn actor_initial_batch_acks_in_order_and_rejects_stale_confirmation() {
        let temp = tempfile::tempdir().unwrap();
        let store = Arc::new(
            bamboo_storage::SessionStoreV2::new(temp.path().to_path_buf())
                .await
                .unwrap(),
        );
        let storage: Arc<dyn Storage> = store.clone();
        let locked = Arc::new(bamboo_storage::LockedSessionStore::new(storage.clone()));
        let inbox: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let session_id = "actor-confirmation-order";
        let run_id = "actor-run-current";
        let mut session = Session::new(session_id, "model");
        store.save_session(&session).await.unwrap();
        for (id, text) in [("actor-first", "first"), ("actor-second", "second")] {
            let mut envelope = bamboo_domain::SessionMessageEnvelope::user_input(session_id, text);
            envelope.id = bamboo_domain::SessionMessageId::parse(id).unwrap();
            inbox.deliver(&envelope).await.unwrap();
        }
        inbox
            .mark_activation_eligible(
                session_id,
                2,
                bamboo_domain::SessionActivationPolicy::InterruptSpecificWait,
            )
            .await
            .unwrap();
        let router = SessionActivationRouter::new();
        let mut owner_registration = router.register_run(session_id, run_id).await.unwrap();
        let binding = SessionInboxRuntimeBinding {
            router,
            inbox: inbox.clone(),
            storage,
            persistence: locked,
        };
        let pairs = claim_canonical_deliveries(&binding, &mut session, run_id, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            pairs
                .iter()
                .map(|(claim, _)| claim.envelope.id.as_str())
                .collect::<Vec<_>>(),
            vec!["actor-first", "actor-second"]
        );
        let seeded = store.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(
            seeded
                .messages
                .iter()
                .filter(|message| matches!(message.id.as_str(), "actor-first" | "actor-second"))
                .map(|message| message.id.as_str())
                .collect::<Vec<_>>(),
            vec!["actor-first", "actor-second"],
            "host context must be durable before actor dispatch"
        );
        for (claim, _) in &pairs {
            assert_eq!(
                seeded
                    .messages
                    .iter()
                    .filter(|message| bamboo_domain::is_matching_session_message(
                        message,
                        &claim.envelope
                    ))
                    .count(),
                1,
                "pre-dispatch host checkpoint must contain exactly one canonical marker for {}",
                claim.envelope.id
            );
        }
        assert!(
            seeded.session_inbox_admission().is_none_or(|cursor| {
                !cursor.contains(&pairs[0].0.envelope.id)
                    && !cursor.contains(&pairs[1].0.envelope.id)
            }),
            "pre-dispatch transcript seeding must not forge worker confirmation"
        );
        assert_eq!(inbox.inspect(session_id).await.unwrap().claimed, 2);
        let claims = pairs
            .into_iter()
            .map(|(claim, _)| claim)
            .collect::<VecDeque<_>>();
        let first = claims[0].clone();
        let second = claims[1].clone();
        let mut stale = admission_confirmation(session_id, &first, "stale-run");
        stale.canonical_claim_generation = second.generation;
        let mut link = ConfirmationSequenceLink {
            frames: VecDeque::from([
                ChildFrame::SessionMessageAdmitted {
                    confirmation: stale,
                },
                ChildFrame::SessionMessageAdmitted {
                    confirmation: admission_confirmation(session_id, &first, run_id),
                },
                ChildFrame::SessionMessageAdmitted {
                    confirmation: admission_confirmation(session_id, &second, run_id),
                },
                ChildFrame::Terminal {
                    status: TerminalStatus::Completed,
                    result: Some("done".to_string()),
                    error: None,
                    transcript: Vec::new(),
                },
            ]),
            sent: Vec::new(),
        };
        let (event_tx, _event_rx) = mpsc::channel(8);
        let cancel = CancellationToken::new();
        let (_live_tx, mut live_rx) = mpsc::unbounded_channel();
        let (_delivery_tx, mut delivery_rx) = mpsc::unbounded_channel();
        let result = drive(ActorDriveContext {
            client: &mut link,
            parent_session_id: "parent",
            child_session_id: session_id,
            child_attempt: 0,
            approval_registry: None,
            approval_decider: None,
            approval_reviewer: None,
            escalation_bridge: None,
            event_tx: &event_tx,
            cancel_token: &cancel,
            live_rx: &mut live_rx,
            delivery_rx: &mut delivery_rx,
            logical_session: &mut session,
            expected_permission_posture: None,
            session_inbox_runtime: Some(&binding),
            activation_run_id: Some(run_id),
            initial_inflight_claims: claims,
            first_frame_timeout: Some(Duration::from_secs(1)),
        })
        .await
        .unwrap();
        assert_eq!(result.as_deref(), Some("done"));
        assert_eq!(
            session
                .messages
                .iter()
                .filter(|message| matches!(message.id.as_str(), "actor-first" | "actor-second"))
                .map(|message| message.id.as_str())
                .collect::<Vec<_>>(),
            vec!["actor-first", "actor-second"]
        );
        let backlog = inbox.inspect(session_id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
        let confirmed = store.load_session(session_id).await.unwrap().unwrap();
        let cursor = confirmed
            .session_inbox_admission()
            .expect("exact worker confirmation must checkpoint the admission cursor");
        assert!(cursor.contains(&first.envelope.id));
        assert!(cursor.contains(&second.envelope.id));
        for claim in [&first, &second] {
            assert_eq!(
                confirmed
                    .messages
                    .iter()
                    .filter(|message| bamboo_domain::is_matching_session_message(
                        message,
                        &claim.envelope
                    ))
                    .count(),
                1,
                "confirmation must retain one exact canonical marker for {}",
                claim.envelope.id
            );
        }
        assert!(inbox
            .was_admitted(session_id, &first.envelope.id)
            .await
            .unwrap());
        assert!(inbox
            .was_admitted(session_id, &second.envelope.id)
            .await
            .unwrap());
        owner_registration.begin_finalization().await;
        owner_registration.finish(2).await.unwrap();
    }

    #[derive(Default)]
    struct RecordingCodexTokenAuthority {
        issued_for: std::sync::Mutex<Vec<String>>,
        revoked: std::sync::Mutex<Vec<String>>,
    }

    impl CodexRunTokenAuthority for RecordingCodexTokenAuthority {
        fn issue(&self, session_id: &str) -> Result<IssuedCodexRunToken, String> {
            self.issued_for
                .lock()
                .expect("issued fixture lock")
                .push(session_id.to_string());
            Ok(IssuedCodexRunToken {
                token_id: format!("id-{session_id}"),
                token: format!("bcx1_secret-{session_id}"),
            })
        }

        fn revoke(&self, token_id: &str) {
            self.revoked
                .lock()
                .expect("revoked fixture lock")
                .push(token_id.to_string());
        }
    }

    fn codex_executor(auth_mode: Option<&str>, inherit_user_config: Option<bool>) -> ExecutorSpec {
        let bamboo_mode = auth_mode == Some("bamboo")
            || (auth_mode.is_none() && !inherit_user_config.unwrap_or(false));
        ExecutorSpec::Codex {
            binary: None,
            model: None,
            mode: None,
            sandbox: None,
            inherit_user_config,
            auth_mode: auth_mode.map(str::to_string),
            base_url: bamboo_mode.then(|| "http://127.0.0.1:9562/openai/v1".to_string()),
            wire_api: Some("responses".to_string()),
            provider_key_ref: None,
            forward_env: None,
            approval_policy: None,
            network_access: None,
            allow_danger_bypass: None,
            permission_profile: None,
            workspace_owned: None,
        }
    }

    fn permission_resolution(
        requested: bamboo_domain::SessionPermissionMode,
        effective: bamboo_domain::PermissionMode,
    ) -> bamboo_domain::PermissionModeResolution {
        bamboo_domain::PermissionModeResolution {
            requested,
            effective,
        }
    }

    #[test]
    fn permission_posture_mapping_contract_is_exact_for_supported_executors() {
        use bamboo_domain::{PermissionMode, SessionPermissionMode};

        let default =
            permission_resolution(SessionPermissionMode::Default, PermissionMode::Default);
        assert_eq!(
            expected_permission_executor_mapping(&ExecutorSpec::BambooRuntime, default, false)
                .unwrap()
                .as_deref(),
            Some("bamboo_runtime:default")
        );
        assert_eq!(
            expected_permission_executor_mapping(&ExecutorSpec::Echo, default, false).unwrap(),
            None,
            "transport-only Echo must not claim the typed permission contract"
        );
        assert_eq!(
            expected_permission_executor_mapping(
                &ExecutorSpec::CliAdapter {
                    command: "must-not-appear-in-contract".to_string(),
                    args: vec!["credential-like-argument".to_string()],
                },
                default,
                false,
            )
            .unwrap(),
            None,
            "unimplemented CliAdapter must not leak command data into a contract"
        );

        let claude = ExecutorSpec::ClaudeCode {
            binary: None,
            model: None,
            permission_mode: Some("default".to_string()),
            inherit_user_config: None,
            forward_env: None,
        };
        for (resolution, mapping) in [
            (
                permission_resolution(SessionPermissionMode::Default, PermissionMode::Plan),
                "claude_code:permission_mode=plan",
            ),
            (
                permission_resolution(SessionPermissionMode::Auto, PermissionMode::Auto),
                "claude_code:permission_mode=bypassPermissions",
            ),
            (
                permission_resolution(SessionPermissionMode::Default, PermissionMode::AcceptEdits),
                "claude_code:permission_mode=acceptEdits",
            ),
            (
                permission_resolution(SessionPermissionMode::Default, PermissionMode::DontAsk),
                "claude_code:permission_mode=dontAsk",
            ),
            (
                permission_resolution(
                    SessionPermissionMode::Bypass,
                    PermissionMode::BypassPermissions,
                ),
                "claude_code:permission_mode=default",
            ),
        ] {
            assert_eq!(
                expected_permission_executor_mapping(&claude, resolution, false)
                    .unwrap()
                    .as_deref(),
                Some(mapping)
            );
        }
        assert_eq!(
            expected_permission_executor_mapping(&claude, default, true)
                .unwrap()
                .as_deref(),
            Some("claude_code:blocked_explicit_deny")
        );

        let mut codex_exec = codex_executor(Some("inherit"), Some(true));
        if let ExecutorSpec::Codex {
            approval_policy, ..
        } = &mut codex_exec
        {
            *approval_policy = Some("on-failure".to_string());
        }
        assert_eq!(
            expected_permission_executor_mapping(&codex_exec, default, false)
                .unwrap()
                .as_deref(),
            Some("codex_exec:approval_policy=on-failure")
        );
        assert_eq!(
            expected_permission_executor_mapping(
                &codex_exec,
                permission_resolution(SessionPermissionMode::Auto, PermissionMode::Auto),
                false,
            )
            .unwrap()
            .as_deref(),
            Some("codex_exec:approval_policy=never")
        );
        assert_eq!(
            expected_permission_executor_mapping(&codex_exec, default, true)
                .unwrap()
                .as_deref(),
            Some("codex_exec:blocked_explicit_deny")
        );

        let mut codex_app_server = codex_executor(Some("inherit"), Some(true));
        if let ExecutorSpec::Codex {
            mode,
            approval_policy,
            ..
        } = &mut codex_app_server
        {
            *mode = Some("app_server".to_string());
            *approval_policy = Some("on-request".to_string());
        }
        assert_eq!(
            expected_permission_executor_mapping(&codex_app_server, default, false)
                .unwrap()
                .as_deref(),
            Some("codex_app_server:approvalPolicy=on-request")
        );
        assert_eq!(
            expected_permission_executor_mapping(
                &codex_app_server,
                permission_resolution(SessionPermissionMode::Auto, PermissionMode::Auto),
                false,
            )
            .unwrap()
            .as_deref(),
            Some("codex_app_server:approvalPolicy=never")
        );
        assert_eq!(
            expected_permission_executor_mapping(&codex_app_server, default, true)
                .unwrap()
                .as_deref(),
            Some("codex_app_server:blocked_explicit_deny")
        );
    }

    #[test]
    fn only_bamboo_managed_non_git_workspaces_are_marked_owned() {
        let project = tempfile::tempdir().unwrap();
        let managed = project.path().join(".bamboo/worktree/child-571");
        std::fs::create_dir_all(&managed).unwrap();
        assert!(!workspace_is_bamboo_owned(managed.to_str().unwrap()));
        let marker = project
            .path()
            .join(".bamboo/worktree/.bamboo-owned/child-571");
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(&marker, "bamboo/child-571").unwrap();
        assert!(workspace_is_bamboo_owned(managed.to_str().unwrap()));
        let nested = managed.join("nested/path");
        std::fs::create_dir_all(&nested).unwrap();
        assert!(workspace_is_bamboo_owned(nested.to_str().unwrap()));

        let arbitrary = tempfile::tempdir().unwrap();
        assert!(!workspace_is_bamboo_owned(
            arbitrary.path().to_str().unwrap()
        ));
    }

    #[test]
    fn bamboo_codex_token_is_per_run_redacted_and_revoked_on_guard_drop() {
        let authority = Arc::new(RecordingCodexTokenAuthority::default());
        let authority_dyn: Arc<dyn CodexRunTokenAuthority> = authority.clone();

        let (secrets, guard) = build_codex_run_secrets(
            &codex_executor(Some("bamboo"), None),
            Some(authority_dyn),
            "child-570",
        )
        .unwrap();

        let token = secrets
            .codex_provider_token
            .as_ref()
            .expect("bamboo mode mints a token");
        assert_eq!(token.expose(), "bcx1_secret-child-570");
        assert!(!format!("{token:?}").contains("secret-child-570"));
        assert_eq!(
            authority.issued_for.lock().unwrap().as_slice(),
            ["child-570"]
        );
        assert!(authority.revoked.lock().unwrap().is_empty());

        drop(guard);
        assert_eq!(
            authority.revoked.lock().unwrap().as_slice(),
            ["id-child-570"]
        );
    }

    #[test]
    fn non_bamboo_codex_never_mints_and_bamboo_fails_closed_without_authority() {
        let authority = Arc::new(RecordingCodexTokenAuthority::default());
        let authority_dyn: Arc<dyn CodexRunTokenAuthority> = authority.clone();
        let (secrets, guard) = build_codex_run_secrets(
            &codex_executor(Some("custom"), None),
            Some(authority_dyn),
            "child-custom",
        )
        .unwrap();
        assert!(secrets.codex_provider_token.is_none());
        assert!(guard.is_none());
        assert!(authority.issued_for.lock().unwrap().is_empty());

        let error = build_codex_run_secrets(
            &codex_executor(Some("bamboo"), None),
            None,
            "child-no-authority",
        )
        .err()
        .expect("bamboo mode without an authority must fail closed");
        assert!(error.to_string().contains("per-run token authority"));
    }

    #[test]
    fn codex_provisioning_never_leaks_the_session_provider_credential() {
        let credentials = vec![ScopedCredential {
            provider: "openai".to_string(),
            api_key: "upstream-secret-must-not-cross".to_string(),
            base_url: None,
            provider_type: Some("openai".to_string()),
            credential_ref: Some("provider.openai.api_key".to_string()),
        }];

        for (mode, label) in [
            (Some("inherit"), "inherit"),
            (Some("api_key"), "api_key"),
            (Some("bamboo"), "bamboo"),
            (None, "default-bamboo"),
        ] {
            let runner = ActorChildRunner::new(
                format!("codex-{label}-test"),
                PathBuf::from("/bin/false"),
                Vec::new(),
                std::env::temp_dir().join(format!("bamboo-codex-{label}-570")),
                codex_executor(mode, None),
                credentials.clone(),
                "openai".to_string(),
                1,
            );
            let mut session = Session::new(format!("child-{label}"), "model");
            session.add_message(bamboo_agent_core::Message::user("test"));
            let spec = runner.build_spec(
                &session,
                &crate::runtime::execution::SpawnJob {
                    parent_session_id: "parent".to_string(),
                    child_session_id: format!("child-{label}"),
                    model: "gpt-5.4".to_string(),
                    disabled_tools: None,
                },
            );
            assert!(
                spec.secrets.provider_credentials.is_empty(),
                "{label} Codex must not receive the session provider key"
            );
        }
    }

    #[test]
    fn non_codex_provisioning_still_receives_only_its_selected_provider_credential() {
        let credentials = vec![
            ScopedCredential {
                provider: "openai".to_string(),
                api_key: "selected-openai-secret".to_string(),
                base_url: None,
                provider_type: Some("openai".to_string()),
                credential_ref: Some("provider.openai.api_key".to_string()),
            },
            ScopedCredential {
                provider: "other".to_string(),
                api_key: "unrelated-secret".to_string(),
                base_url: None,
                provider_type: Some("openai".to_string()),
                credential_ref: Some("provider.other.api_key".to_string()),
            },
        ];
        let runner = ActorChildRunner::new(
            "echo-test".to_string(),
            PathBuf::from("/bin/false"),
            Vec::new(),
            std::env::temp_dir().join("bamboo-echo-provider-570"),
            ExecutorSpec::Echo,
            credentials,
            "openai".to_string(),
            1,
        );
        let spec = runner.build_spec(
            &Session::new("child-echo", "model"),
            &crate::runtime::execution::SpawnJob {
                parent_session_id: "parent".to_string(),
                child_session_id: "child-echo".to_string(),
                model: "gpt-5.4".to_string(),
                disabled_tools: None,
            },
        );

        assert_eq!(spec.secrets.provider_credentials.len(), 1);
        assert_eq!(
            spec.secrets.provider_credentials[0].api_key,
            "selected-openai-secret"
        );
    }

    #[test]
    fn custom_codex_provisioning_scopes_only_the_referenced_credential() {
        let mut executor = codex_executor(Some("custom"), None);
        if let ExecutorSpec::Codex {
            base_url,
            provider_key_ref,
            ..
        } = &mut executor
        {
            *base_url = Some("https://provider.example/v1".to_string());
            *provider_key_ref = Some("provider.custom.api_key".to_string());
        }
        let credentials = vec![
            ScopedCredential {
                provider: "openai".to_string(),
                api_key: "session-provider-secret".to_string(),
                base_url: None,
                provider_type: Some("openai".to_string()),
                credential_ref: Some("provider.openai.api_key".to_string()),
            },
            ScopedCredential {
                provider: "custom".to_string(),
                api_key: "selected-secret".to_string(),
                base_url: None,
                provider_type: Some("openai".to_string()),
                credential_ref: Some("provider.custom.api_key".to_string()),
            },
            ScopedCredential {
                provider: "other".to_string(),
                api_key: "unrelated-secret".to_string(),
                base_url: None,
                provider_type: Some("openai".to_string()),
                credential_ref: Some("provider.other.api_key".to_string()),
            },
        ];
        let runner = ActorChildRunner::new(
            "codex-test".to_string(),
            PathBuf::from("/bin/false"),
            Vec::new(),
            std::env::temp_dir().join("bamboo-codex-570"),
            executor,
            credentials,
            "openai".to_string(),
            1,
        );
        let mut session = Session::new("child-custom", "model");
        session.add_message(bamboo_agent_core::Message::user("test"));
        let spec = runner.build_spec(
            &session,
            &crate::runtime::execution::SpawnJob {
                parent_session_id: "parent".to_string(),
                child_session_id: "child-custom".to_string(),
                model: "gpt-5.4".to_string(),
                disabled_tools: None,
            },
        );

        assert_eq!(spec.secrets.provider_credentials.len(), 1);
        assert_eq!(
            spec.secrets.provider_credentials[0]
                .credential_ref
                .as_deref(),
            Some("provider.custom.api_key")
        );
        assert_eq!(
            spec.secrets.provider_credentials[0].api_key,
            "selected-secret"
        );
    }

    fn spec_with(
        role: &str,
        provider: &str,
        model: &str,
        workspace: Option<&str>,
        disabled: Option<Vec<&str>>,
    ) -> ProvisionSpec {
        let mut spec = ProvisionSpec::new(
            ChildIdentity {
                child_id: "c".into(),
                parent_id: None,
                project_key: None,
                role: role.into(),
                depth: 0,
            },
            ExecutorSpec::Echo,
            "/tmp/fab".into(),
        );
        spec.workspace = workspace.map(|w| w.to_string());
        spec.model = Some(ModelRefSpec {
            provider: provider.into(),
            model: model.into(),
        });
        spec.disabled_tools = disabled.map(|d| d.into_iter().map(String::from).collect());
        spec
    }

    #[test]
    fn fingerprint_matches_interchangeable_children() {
        // Same role/provider/model/workspace and equal tool sets (order-insensitive)
        // are interchangeable on one warm worker — and differ only in child_id.
        let a = spec_with(
            "explorer",
            "p",
            "m",
            Some("/ws"),
            Some(vec!["Bash", "Edit"]),
        );
        let mut b = spec_with(
            "explorer",
            "p",
            "m",
            Some("/ws"),
            Some(vec!["Edit", "Bash"]),
        );
        b.identity.child_id = "other".into();
        assert_eq!(
            ActorChildRunner::fingerprint(&a),
            ActorChildRunner::fingerprint(&b)
        );
    }

    #[test]
    fn logical_identity_is_invariant_across_local_remote_scheduled_and_warm_reuse() {
        let mut session =
            Session::new_child("logical-child-681", "logical-parent-681", "model", "child");
        session.root_session_id = "logical-root-681".to_string();
        let job = SpawnJob {
            parent_session_id: "logical-parent-681".to_string(),
            child_session_id: "logical-child-681".to_string(),
            model: "model".to_string(),
            disabled_tools: None,
        };
        let expected = LogicalSessionIdentity {
            session_id: "logical-child-681".to_string(),
            parent_session_id: Some("logical-parent-681".to_string()),
            root_session_id: "logical-root-681".to_string(),
        };

        let placements_and_transport_ids = [
            (Placement::Local, "local-mailbox-first"),
            (
                Placement::Remote {
                    endpoint: "wss://remote.example/actor".to_string(),
                },
                "remote-process-44",
            ),
            (
                Placement::Schedulable {
                    pool: "gpu-pool".to_string(),
                },
                "scheduled-mailbox-9",
            ),
            // Same logical child reactivated on a different pooled mailbox.
            (Placement::Local, "warm-mailbox-reused-77"),
        ];
        for (placement, transport_id) in placements_and_transport_ids {
            let mut provision = spec_with("worker", "provider", "model", None, None);
            provision.placement = placement;
            provision.identity.child_id = transport_id.to_string();
            assert_eq!(logical_identity_for_actor_run(&session, &job), expected);
            assert_ne!(
                provision.identity.child_id, expected.session_id,
                "test fixture must prove transport identity is independent"
            );
        }
    }

    #[test]
    fn fingerprint_separates_distinct_runtimes() {
        let base = spec_with("explorer", "p", "m", Some("/ws"), None);
        let base_fp = ActorChildRunner::fingerprint(&base);
        // Each axis that is baked into the worker must split the pool bucket.
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&spec_with("writer", "p", "m", Some("/ws"), None))
        );
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&spec_with("explorer", "p2", "m", Some("/ws"), None))
        );
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&spec_with("explorer", "p", "m2", Some("/ws"), None))
        );
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&spec_with("explorer", "p", "m", Some("/ws2"), None))
        );
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&spec_with(
                "explorer",
                "p",
                "m",
                Some("/ws"),
                Some(vec!["Bash"])
            ))
        );
    }

    #[test]
    fn fingerprint_splits_on_baked_capabilities() {
        // Every capability baked once at provision time must split the pool
        // bucket, else a worker baked for one posture gets reused for another
        // (e.g. a depth-1 worker re-stamping spawn_depth onto a depth-4 child,
        // breaking the depth cap; or a bypass worker reused for a non-bypass one).
        let base_fp =
            ActorChildRunner::fingerprint(&spec_with("explorer", "p", "m", Some("/ws"), None));

        let mut depth = spec_with("explorer", "p", "m", Some("/ws"), None);
        depth.identity.depth = 2;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&depth),
            "depth must split"
        );

        let mut nested = spec_with("explorer", "p", "m", Some("/ws"), None);
        nested.capabilities.nested_spawn = true;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&nested),
            "nested_spawn must split"
        );

        let mut bypass = spec_with("explorer", "p", "m", Some("/ws"), None);
        bypass.capabilities.bypass = true;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&bypass),
            "bypass must split"
        );

        let mut auto = spec_with("explorer", "p", "m", Some("/ws"), None);
        auto.capabilities.auto_approve_permissions = true;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&auto),
            "auto_approve_permissions must split"
        );

        let mut global_auto = spec_with("explorer", "p", "m", Some("/ws"), None);
        global_auto.capabilities.permission_requested_mode = "default".to_string();
        global_auto.capabilities.permission_effective_mode = "auto".to_string();
        global_auto.capabilities.auto_approve_permissions = true;
        let mut explicit_auto = global_auto.clone();
        explicit_auto.capabilities.permission_requested_mode = "auto".to_string();
        assert_ne!(
            ActorChildRunner::fingerprint(&global_auto),
            ActorChildRunner::fingerprint(&explicit_auto),
            "permission_requested_mode must split global and explicit Auto"
        );

        let mut plan_overlay = explicit_auto.clone();
        plan_overlay.capabilities.permission_effective_mode = "plan".to_string();
        assert_ne!(
            ActorChildRunner::fingerprint(&explicit_auto),
            ActorChildRunner::fingerprint(&plan_overlay),
            "permission_effective_mode must split Plan overlay from Auto"
        );

        let mut enforce = spec_with("explorer", "p", "m", Some("/ws"), None);
        enforce.capabilities.enforce_permissions = true;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&enforce),
            "enforce_permissions must split"
        );

        let mut cap = spec_with("explorer", "p", "m", Some("/ws"), None);
        cap.capabilities.max_spawn_depth = Some(8);
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&cap),
            "max_spawn_depth must split"
        );

        // #73 (P1): the worker bakes `no_human_review` from this flag once at
        // build(), so it MUST split the pool or a worker baked for one approval
        // posture is reused for the opposite one.
        let mut nha = spec_with("explorer", "p", "m", Some("/ws"), None);
        nha.capabilities.no_human_approver = true;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&nha),
            "no_human_approver must split"
        );

        // #71: the read-only Bash checker is baked once at build() from this flag,
        // so a guardian reviewer worker must not be reused for an ordinary child.
        let mut gro = spec_with("explorer", "p", "m", Some("/ws"), None);
        gro.capabilities.guardian_read_only = true;
        assert_ne!(
            base_fp,
            ActorChildRunner::fingerprint(&gro),
            "guardian_read_only must split"
        );
    }

    #[test]
    fn fingerprint_splits_codex_exec_and_app_server_workers() {
        let mut exec = spec_with("explorer", "p", "m", Some("/ws"), None);
        exec.executor = codex_executor(Some("inherit"), None);
        let mut app_server = exec.clone();
        if let ExecutorSpec::Codex { mode, .. } = &mut app_server.executor {
            *mode = Some("app_server".to_string());
        }
        assert_ne!(
            ActorChildRunner::fingerprint(&exec),
            ActorChildRunner::fingerprint(&app_server)
        );
    }

    struct StaticDecider(bool);

    #[async_trait]
    impl ChildApprovalDecider for StaticDecider {
        async fn decide(&self, _child: &str, _req: &serde_json::Value) -> bool {
            self.0
        }
    }

    struct RecordingReviewer {
        reviewed: mpsc::UnboundedSender<(String, String, serde_json::Value)>,
    }

    #[async_trait]
    impl ChildApprovalReviewer for RecordingReviewer {
        async fn review(&self, parent: &str, child: &str, request: &serde_json::Value) -> bool {
            let _ = self
                .reviewed
                .send((parent.to_string(), child.to_string(), request.clone()));
            true
        }
    }

    // ---- first-frame watchdog (dead-pooled-worker recovery) -----------------

    /// A link that never yields a frame — models a worker that died (or never
    /// subscribed) so its Run sits queued with no server.
    struct SilentLink;
    #[async_trait]
    impl bamboo_subagent::ChildLink for SilentLink {
        async fn send(&mut self, _: ParentFrame) -> bamboo_subagent::TransportResult<()> {
            Ok(())
        }
        async fn next_frame(&mut self) -> bamboo_subagent::TransportResult<Option<ChildFrame>> {
            std::future::pending().await
        }
    }

    /// A link that immediately yields one terminal frame (a healthy fast worker).
    struct InstantTerminalLink {
        done: bool,
    }

    struct ApprovalRoundTripLink {
        step: u8,
        approval_reply: Option<(String, bool)>,
    }

    #[async_trait]
    impl bamboo_subagent::ChildLink for ApprovalRoundTripLink {
        async fn send(&mut self, frame: ParentFrame) -> bamboo_subagent::TransportResult<()> {
            if let ParentFrame::ApprovalReply { id, approved } = frame {
                self.approval_reply = Some((id, approved));
                self.step = 2;
            }
            Ok(())
        }

        async fn next_frame(&mut self) -> bamboo_subagent::TransportResult<Option<ChildFrame>> {
            match self.step {
                0 => {
                    self.step = 1;
                    Ok(Some(ChildFrame::ApprovalRequest {
                        id: "approval-1".into(),
                        body: serde_json::json!({
                            "tool_name": "Bash",
                            "permission": "execute",
                            "resource": "rm -rf target",
                            "permission_request": {"reason_code": "hard_dangerous"}
                        }),
                    }))
                }
                1 => std::future::pending().await,
                2 => {
                    self.step = 3;
                    Ok(Some(ChildFrame::Terminal {
                        status: TerminalStatus::Completed,
                        result: Some("done".into()),
                        error: None,
                        transcript: vec![],
                    }))
                }
                _ => std::future::pending().await,
            }
        }
    }

    #[tokio::test]
    async fn drive_routes_forced_ask_to_parent_reviewer_without_human_event() {
        let (event_tx, mut event_rx) = mpsc::channel::<AgentEvent>(8);
        let (review_tx, mut review_rx) = mpsc::unbounded_channel();
        let reviewer: Arc<dyn ChildApprovalReviewer> = Arc::new(RecordingReviewer {
            reviewed: review_tx,
        });
        let cancel = CancellationToken::new();
        let (live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
        let (_delivery_tx, mut delivery_rx) = mpsc::unbounded_channel();
        let mut logical_session = Session::new("child-reviewer", "model");
        let live_guard = crate::external_agents::live::register("child-reviewer", live_tx, 0, None);
        let mut link = ApprovalRoundTripLink {
            step: 0,
            approval_reply: None,
        };

        let result = tokio::time::timeout(
            Duration::from_secs(1),
            drive(ActorDriveContext {
                client: &mut link,
                parent_session_id: "parent-reviewer",
                child_session_id: "child-reviewer",
                child_attempt: 0,
                approval_registry: None,
                approval_decider: None,
                approval_reviewer: Some(&reviewer),
                escalation_bridge: None,
                event_tx: &event_tx,
                cancel_token: &cancel,
                live_rx: &mut live_rx,
                delivery_rx: &mut delivery_rx,
                logical_session: &mut logical_session,
                expected_permission_posture: None,
                session_inbox_runtime: None,
                activation_run_id: None,
                initial_inflight_claims: VecDeque::new(),
                first_frame_timeout: None,
            }),
        )
        .await
        .expect("worker must receive the reviewer verdict before terminating");

        assert_eq!(result.ok().flatten().as_deref(), Some("done"));
        assert_eq!(
            link.approval_reply,
            Some(("approval-1".to_string(), true)),
            "reviewer verdict must traverse the live route back to the worker"
        );
        let (parent, child, body) = tokio::time::timeout(Duration::from_secs(1), review_rx.recv())
            .await
            .expect("reviewer should be invoked off-loop")
            .expect("review channel should remain open");
        assert_eq!(parent, "parent-reviewer");
        assert_eq!(child, "child-reviewer");
        assert_eq!(
            body.pointer("/permission_request/reason_code")
                .and_then(serde_json::Value::as_str),
            Some("hard_dangerous")
        );
        assert!(
            event_rx.try_recv().is_err(),
            "must not emit a human-review event"
        );
        drop(live_guard);
    }

    #[tokio::test]
    async fn drive_denies_forced_ask_without_parent_reviewer_or_manual_event() {
        let (event_tx, mut event_rx) = mpsc::channel::<AgentEvent>(8);
        let cancel = CancellationToken::new();
        let (_live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
        let (_delivery_tx, mut delivery_rx) = mpsc::unbounded_channel();
        let mut logical_session = Session::new("child-no-reviewer", "model");
        let mut link = ApprovalRoundTripLink {
            step: 0,
            approval_reply: None,
        };

        let result = tokio::time::timeout(
            Duration::from_secs(1),
            drive(ActorDriveContext {
                client: &mut link,
                parent_session_id: "parent-no-reviewer",
                child_session_id: "child-no-reviewer",
                child_attempt: 0,
                approval_registry: None,
                approval_decider: None,
                approval_reviewer: None,
                escalation_bridge: None,
                event_tx: &event_tx,
                cancel_token: &cancel,
                live_rx: &mut live_rx,
                delivery_rx: &mut delivery_rx,
                logical_session: &mut logical_session,
                expected_permission_posture: None,
                session_inbox_runtime: None,
                activation_run_id: None,
                initial_inflight_claims: VecDeque::new(),
                first_frame_timeout: None,
            }),
        )
        .await
        .expect("fail-closed reply must unblock the child immediately");

        assert_eq!(result.ok().flatten().as_deref(), Some("done"));
        assert_eq!(link.approval_reply, Some(("approval-1".to_string(), false)));
        assert!(
            event_rx.try_recv().is_err(),
            "missing parent review must not surface a manual approval event"
        );
    }
    #[async_trait]
    impl bamboo_subagent::ChildLink for InstantTerminalLink {
        async fn send(&mut self, _: ParentFrame) -> bamboo_subagent::TransportResult<()> {
            Ok(())
        }
        async fn next_frame(&mut self) -> bamboo_subagent::TransportResult<Option<ChildFrame>> {
            if self.done {
                std::future::pending().await
            } else {
                self.done = true;
                Ok(Some(ChildFrame::Terminal {
                    status: TerminalStatus::Completed,
                    result: Some("done".into()),
                    error: None,
                    transcript: vec![],
                }))
            }
        }
    }

    #[tokio::test]
    async fn drive_trips_first_frame_watchdog_on_a_silent_worker() {
        let (event_tx, _rx) = mpsc::channel::<AgentEvent>(8);
        let cancel = CancellationToken::new();
        let (_live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
        let (_delivery_tx, mut delivery_rx) = mpsc::unbounded_channel();
        let mut logical_session = Session::new("child-x", "model");
        let mut link = SilentLink;
        let r = drive(ActorDriveContext {
            client: &mut link,
            parent_session_id: "parent-x",
            child_session_id: "child-x",
            child_attempt: 0,
            approval_registry: None,
            approval_decider: None,
            approval_reviewer: None,
            escalation_bridge: None,
            event_tx: &event_tx,
            cancel_token: &cancel,
            live_rx: &mut live_rx,
            delivery_rx: &mut delivery_rx,
            logical_session: &mut logical_session,
            expected_permission_posture: None,
            session_inbox_runtime: None,
            activation_run_id: None,
            initial_inflight_claims: VecDeque::new(),
            first_frame_timeout: Some(Duration::from_millis(100)),
        })
        .await;
        assert!(
            matches!(r, Err(AgentError::WorkerUnresponsive(_))),
            "a silent worker must trip the first-frame watchdog, got {r:?}"
        );
    }

    #[tokio::test]
    async fn drive_does_not_trip_when_a_frame_arrives() {
        let (event_tx, _rx) = mpsc::channel::<AgentEvent>(8);
        let cancel = CancellationToken::new();
        let (_live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
        let (_delivery_tx, mut delivery_rx) = mpsc::unbounded_channel();
        let mut logical_session = Session::new("child-y", "model");
        let mut link = InstantTerminalLink { done: false };
        // Even a tiny timeout must NOT trip: the terminal frame arrives first and
        // disarms the watchdog.
        let r = drive(ActorDriveContext {
            client: &mut link,
            parent_session_id: "parent-y",
            child_session_id: "child-y",
            child_attempt: 0,
            approval_registry: None,
            approval_decider: None,
            approval_reviewer: None,
            escalation_bridge: None,
            event_tx: &event_tx,
            cancel_token: &cancel,
            live_rx: &mut live_rx,
            delivery_rx: &mut delivery_rx,
            logical_session: &mut logical_session,
            expected_permission_posture: None,
            session_inbox_runtime: None,
            activation_run_id: None,
            initial_inflight_claims: VecDeque::new(),
            first_frame_timeout: Some(Duration::from_millis(50)),
        })
        .await;
        assert_eq!(r.ok().flatten().as_deref(), Some("done"));
    }

    #[tokio::test]
    async fn child_approval_fails_closed_without_decider() {
        // No decider wired ⇒ the host denies (safe default), unchanged behavior.
        let body = serde_json::json!({"tool_name":"Bash","permission":"run","resource":"rm -rf /"});
        assert!(!decide_child_approval(None, "child-1", &body).await);
    }

    #[tokio::test]
    async fn child_approval_honors_wired_decider() {
        let body =
            serde_json::json!({"tool_name":"Write","permission":"write","resource":"/tmp/x"});
        let approve: Arc<dyn ChildApprovalDecider> = Arc::new(StaticDecider(true));
        let deny: Arc<dyn ChildApprovalDecider> = Arc::new(StaticDecider(false));
        assert!(decide_child_approval(Some(&approve), "child-1", &body).await);
        assert!(!decide_child_approval(Some(&deny), "child-1", &body).await);
    }

    // ---- #193: remote placement routing -------------------------------------

    use crate::runtime::execution::SpawnJob;
    use bamboo_agent_core::Session;

    /// A runner with a BOGUS worker_bin (`/bin/false`): a local spawn here would
    /// FAIL, so a passing remote test proves the remote path never spawns.
    fn bogus_runner(placements: HashMap<String, ResolvedRemotePlacement>) -> ActorChildRunner {
        ActorChildRunner::new(
            "test-actor".into(),
            PathBuf::from("/bin/false"),
            vec![],
            std::env::temp_dir().join("bamboo-test-fab-193"),
            ExecutorSpec::Echo,
            vec![],
            "anthropic".into(),
            4,
        )
        .with_remote_placements(placements)
    }

    /// A child session of the given role (the role rides `subagent_type`, the
    /// path build_spec + the remote lookup both read).
    fn session_of_role(role: &str, assignment: &str) -> Session {
        let mut s = Session::new("child-1", "test-model");
        s.metadata
            .insert("subagent_type".to_string(), role.to_string());
        s.add_message(bamboo_agent_core::Message::user(assignment));
        s
    }

    fn job_for(child: &str) -> SpawnJob {
        SpawnJob {
            parent_session_id: "parent-1".into(),
            child_session_id: child.into(),
            model: String::new(),
            disabled_tools: None,
        }
    }

    #[derive(Default)]
    struct RecordingChildSessionPort {
        saved: std::sync::Mutex<Option<Session>>,
    }

    impl RecordingChildSessionPort {
        fn saved_child(&self) -> Session {
            self.saved
                .lock()
                .expect("saved-child fixture lock")
                .clone()
                .expect("create_child_action must save the child")
        }
    }

    #[async_trait]
    impl crate::session_app::child_session::ChildSessionPort for RecordingChildSessionPort {
        async fn load_root_session(
            &self,
            _root_id: &str,
        ) -> Result<Session, crate::session_app::child_session::ChildSessionError> {
            unreachable!("create_child_action does not load the root")
        }

        async fn load_child_for_parent(
            &self,
            _parent_id: &str,
            _child_id: &str,
        ) -> Result<Session, crate::session_app::child_session::ChildSessionError> {
            unreachable!("create_child_action does not reload the child")
        }

        async fn save_child_session(
            &self,
            child: &mut Session,
        ) -> Result<(), crate::session_app::child_session::ChildSessionError> {
            *self.saved.lock().expect("saved-child fixture lock") = Some(child.clone());
            Ok(())
        }

        async fn save_child_session_authoritative_flags(
            &self,
            _child: &mut Session,
        ) -> Result<(), crate::session_app::child_session::ChildSessionError> {
            unreachable!("new-child creation uses the ordinary save")
        }

        async fn is_child_running(&self, _child_id: &str) -> bool {
            false
        }

        async fn list_children(
            &self,
            _parent_id: &str,
        ) -> Vec<crate::session_app::child_session::ChildSessionEntry> {
            Vec::new()
        }

        async fn enqueue_child_run(
            &self,
            _parent: &Session,
            _child: &Session,
        ) -> Result<(), crate::session_app::child_session::ChildSessionError> {
            unreachable!("fixture creates the child with auto_run=false")
        }

        async fn cancel_child_run_and_wait(
            &self,
            _child_id: &str,
        ) -> Result<(), crate::session_app::child_session::ChildSessionError> {
            unreachable!("create_child_action does not cancel")
        }

        async fn delete_child_session(
            &self,
            _parent_id: &str,
            _child_id: &str,
        ) -> Result<
            crate::session_app::child_session::DeleteChildResult,
            crate::session_app::child_session::ChildSessionError,
        > {
            unreachable!("create_child_action does not delete")
        }

        async fn get_child_runner_info(
            &self,
            _child_id: &str,
        ) -> Option<crate::session_app::child_session::ChildRunnerInfo> {
            None
        }

        async fn register_parent_wait_for_child(
            &self,
            _parent_session_id: &str,
            _child_session_id: &str,
            _tool_call_id: Option<&str>,
        ) -> Result<(), crate::session_app::child_session::ChildSessionError> {
            unreachable!("create_child_action does not register a wait")
        }

        async fn register_parent_wait_for_children(
            &self,
            _parent_session_id: &str,
            _child_session_ids: &[String],
            _policy: bamboo_domain::session::runtime_state::ChildWaitPolicy,
        ) -> Result<usize, crate::session_app::child_session::ChildSessionError> {
            unreachable!("create_child_action does not register a wait")
        }

        async fn active_child_ids(&self, _parent_session_id: &str) -> Vec<String> {
            Vec::new()
        }

        async fn find_resident_child(
            &self,
            _root_session_id: &str,
            _resident_name: &str,
        ) -> Option<String> {
            None
        }

        async fn ensure_child_indexed(&self, _child_session_id: &str) {}
    }

    #[test]
    fn build_spec_sets_remote_placement_for_matching_role() {
        let mut placements = HashMap::new();
        placements.insert(
            "explorer".to_string(),
            ResolvedRemotePlacement {
                endpoint: "wss://gpu-host:8443".into(),
                token: Some("T-secret".into()),
                ca_cert_file: None,
                host_label: None,
            },
        );
        let runner = bogus_runner(placements);

        // Matching role -> Placement::Remote + the bearer on the secrets envelope.
        let s = session_of_role("explorer", "do the thing");
        let spec = runner.build_spec(&s, &job_for("child-1"));
        match &spec.placement {
            Placement::Remote { endpoint } => assert_eq!(endpoint, "wss://gpu-host:8443"),
            other => panic!("expected Remote, got {other:?}"),
        }
        assert_eq!(spec.secrets.worker_auth_token.as_deref(), Some("T-secret"));
    }

    #[test]
    fn build_spec_leaves_local_for_unmatched_role() {
        let mut placements = HashMap::new();
        placements.insert(
            "explorer".to_string(),
            ResolvedRemotePlacement {
                endpoint: "wss://gpu-host:8443".into(),
                token: Some("T".into()),
                ca_cert_file: None,
                host_label: None,
            },
        );
        let runner = bogus_runner(placements);

        // A DIFFERENT role keeps the default Local placement + no bearer.
        let s = session_of_role("writer", "do the thing");
        let spec = runner.build_spec(&s, &job_for("child-1"));
        assert_eq!(spec.placement, Placement::Local);
        assert!(spec.secrets.worker_auth_token.is_none());
    }

    #[test]
    fn build_spec_local_when_no_placements() {
        let runner = bogus_runner(HashMap::new());
        let s = session_of_role("explorer", "do the thing");
        let spec = runner.build_spec(&s, &job_for("child-1"));
        assert_eq!(spec.placement, Placement::Local);
        assert!(spec.secrets.worker_auth_token.is_none());
    }

    #[tokio::test]
    async fn build_spec_preserves_exact_inherited_permission_mode_for_child_worker() {
        // Exercise the real creation path instead of pre-seeding the child by
        // hand: both legacy Bypass and zero-prompt Auto must survive child
        // creation and the actor provisioning boundary without collapsing.
        for (label, mode) in [
            ("bypass", bamboo_domain::SessionPermissionMode::Bypass),
            ("auto", bamboo_domain::SessionPermissionMode::Auto),
        ] {
            let runner = bogus_runner(HashMap::new());
            let mut parent = Session::new(format!("parent-{label}"), "test-model");
            parent
                .agent_runtime_state
                .get_or_insert_with(bamboo_domain::AgentRuntimeState::default)
                .set_permission_mode(mode);
            let workspace = tempfile::tempdir().expect("workspace fixture");
            let port = RecordingChildSessionPort::default();
            let child_id = format!("child-{label}-{}", uuid::Uuid::new_v4());
            crate::session_app::child_session::create_child_action(
                &port,
                crate::session_app::child_session::CreateChildInput {
                    parent_session: parent,
                    child_id: child_id.clone(),
                    title: format!("{label} child"),
                    responsibility: "Run ordinary commands".to_string(),
                    assignment_prompt: "run an ordinary command".to_string(),
                    subagent_type: "explorer".to_string(),
                    workspace: workspace.path().to_string_lossy().into_owned(),
                    workspace_source: crate::project_context::WorkspaceSource::Explicit,
                    model_override: None,
                    model_ref_override: None,
                    runtime_metadata: HashMap::new(),
                    auto_run: false,
                    reasoning_effort: None,
                    lifecycle: None,
                    resident_name: None,
                    resident_context: None,
                    disabled_tools: None,
                    context_fork: None,
                },
            )
            .await
            .expect("create inherited-permission child");
            let child = port.saved_child();

            assert_eq!(
                child
                    .agent_runtime_state
                    .as_ref()
                    .map(bamboo_domain::AgentRuntimeState::effective_permission_mode),
                Some(mode),
                "create_child_action must inherit {label} from the parent"
            );

            let spec = runner.build_spec(&child, &job_for(&child_id));

            assert_eq!(
                spec.capabilities.bypass,
                mode == bamboo_domain::SessionPermissionMode::Bypass
            );
            assert_eq!(
                spec.capabilities.auto_approve_permissions,
                mode == bamboo_domain::SessionPermissionMode::Auto
            );
            assert!(
                spec.capabilities.enforce_permissions,
                "policy evaluation must remain active under {label}"
            );
        }
    }

    #[tokio::test]
    async fn child_resident_and_guardian_inherit_project_through_actor_run_spec() {
        let project_id = bamboo_domain::ProjectId::parse("project-inherited").expect("Project id");
        let workspace = tempfile::tempdir().expect("workspace fixture");

        for (role, lifecycle, resident_name) in [
            ("explorer", None, None),
            ("resident", Some("resident"), Some("stable-reviewer")),
            ("guardian", None, None),
        ] {
            let mut parent = Session::new(format!("parent-{role}"), "test-model");
            parent.set_project_id_meta(project_id.to_string());
            let port = RecordingChildSessionPort::default();
            let child_id = format!("child-{role}-{}", uuid::Uuid::new_v4());
            crate::session_app::child_session::create_child_action(
                &port,
                crate::session_app::child_session::CreateChildInput {
                    parent_session: parent,
                    child_id: child_id.clone(),
                    title: format!("{role} child"),
                    responsibility: "Review the assigned work".to_string(),
                    assignment_prompt: "inspect the change".to_string(),
                    subagent_type: role.to_string(),
                    workspace: workspace.path().to_string_lossy().into_owned(),
                    workspace_source: crate::project_context::WorkspaceSource::Explicit,
                    model_override: None,
                    model_ref_override: None,
                    runtime_metadata: HashMap::new(),
                    auto_run: false,
                    reasoning_effort: None,
                    lifecycle: lifecycle.map(str::to_string),
                    resident_name: resident_name.map(str::to_string),
                    resident_context: None,
                    disabled_tools: None,
                    context_fork: None,
                },
            )
            .await
            .expect("create Project-inheriting child");
            let child = port.saved_child();
            assert_eq!(
                crate::project_context::ProjectContextResolver::project_id_from_session(&child),
                Some(project_id.clone()),
                "{role} child must inherit its parent's Project"
            );

            assert_eq!(
                project_id_for_actor_run(&child).expect("valid actor Project identity"),
                Some(project_id.clone()),
                "{role} actor RunSpec must preserve inherited Project identity"
            );
        }
    }

    #[test]
    fn placement_metadata_stamps_remote_and_schedulable_not_local() {
        // Local children carry no stamp — the DTO defaults them to the backend host.
        assert_eq!(placement_metadata(&Placement::Local, None), None);

        // Remote, no node label → host derived from the endpoint.
        let r = placement_metadata(
            &Placement::Remote {
                endpoint: "wss://10.0.0.5:8443/stream".into(),
            },
            None,
        )
        .unwrap();
        assert!(r.contains(r#""kind":"remote""#), "{r}");
        assert!(r.contains(r#""host":"10.0.0.5""#), "{r}");

        // A cluster node's label (its metadata) OVERRIDES the raw endpoint host.
        let labeled = placement_metadata(
            &Placement::Remote {
                endpoint: "ws://169.254.230.101:8899".into(),
            },
            Some("mini"),
        )
        .unwrap();
        assert!(labeled.contains(r#""host":"mini""#), "{labeled}");

        // Schedulable → {kind:"remote", host:<node label, else pool>}.
        let s = placement_metadata(
            &Placement::Schedulable {
                pool: "explorers".into(),
            },
            Some("mini"),
        )
        .unwrap();
        assert!(s.contains(r#""kind":"remote""#), "{s}");
        assert!(s.contains(r#""host":"mini""#), "{s}");

        // The stamp round-trips through the storage placement type.
        let p: bamboo_storage::SessionPlacement = serde_json::from_str(&labeled).unwrap();
        assert_eq!(p.kind, "remote");
        assert_eq!(p.host, "mini");
    }

    /// End-to-end remote run through `execute_external_child`: a resident worker
    /// (Bearer-gated `WsServer` + `EchoExecutor`) serves the role; the runner is
    /// built with a `remote_placements` entry pointing at it AND a BOGUS
    /// worker_bin (`/bin/false`). A passing test proves the remote path CONNECTS
    /// to the resident worker and NEVER spawns (a spawn would fail on /bin/false),
    /// and that a terminal/echo result flows back.
    #[tokio::test]
    async fn execute_external_child_routes_role_to_remote_worker_without_spawning() {
        // 1. Stand up the resident worker on loopback with a required bearer.
        let token = "remote-test-token";
        let server = bamboo_subagent::transport::WsServer::bind_with_token(
            (std::net::Ipv4Addr::LOCALHOST, 0).into(),
            Some(token.to_string()),
        )
        .await
        .expect("bind resident worker");
        let endpoint = server.ws_endpoint(); // ws://127.0.0.1:<port>
        let srv = tokio::spawn(async move {
            // serve() loops connection-after-connection; the test exits, dropping it.
            let _ = server
                .serve(Arc::new(bamboo_subagent::executor::EchoExecutor))
                .await;
        });

        // 2. Build the runner: role "explorer" pinned remote, bogus worker_bin.
        let mut placements = HashMap::new();
        placements.insert(
            "explorer".to_string(),
            ResolvedRemotePlacement {
                endpoint: endpoint.clone(),
                token: Some(token.to_string()),
                ca_cert_file: None,
                host_label: Some("mini-e2e".into()), // node label, surfaced on the badge
            },
        );
        let runner = bogus_runner(placements);

        // 3. Drive a real run for that role.
        let mut session = session_of_role("explorer", "hello remote");
        let job = job_for("child-1");
        let (event_tx, mut event_rx) = mpsc::channel::<AgentEvent>(64);
        let cancel = CancellationToken::new();

        let result = tokio::time::timeout(
            Duration::from_secs(10),
            runner.execute_external_child(&mut session, &job, event_tx, cancel),
        )
        .await
        .expect("run did not hang")
        .expect("remote run succeeded (connected to resident worker, did not spawn)");

        let _ = result;
        // The EchoExecutor's reply is written back onto the child session as an
        // assistant message — proof a terminal result flowed back over the link.
        let last = session
            .messages
            .iter()
            .rev()
            .find(|m| matches!(m.role, Role::Assistant))
            .expect("an assistant reply was written back");
        assert!(
            last.content.contains("echo:"),
            "expected echo reply, got {:?}",
            last.content
        );

        // A remote run must stamp WHICH machine it ran on onto the child session
        // (mirrored to the UI badge) using the placement's node label.
        let placement = session
            .metadata
            .get("placement")
            .expect("remote child session stamped with a placement");
        assert!(placement.contains(r#""kind":"remote""#), "{placement}");
        assert!(placement.contains(r#""host":"mini-e2e""#), "{placement}");

        // Drain a couple of streamed events to confirm the event pipe carried the
        // worker's tokens too (best-effort; the reply assertion above is primary).
        let mut saw_event = false;
        while let Ok(Some(_ev)) =
            tokio::time::timeout(Duration::from_millis(50), event_rx.recv()).await
        {
            saw_event = true;
        }
        let _ = saw_event;

        srv.abort();
    }

    // ---- #181 (P2b): schedulable placement routing --------------------------

    /// A bogus-worker_bin runner carrying SCHEDULABLE placements (and optionally
    /// remote ones, to test precedence). A local spawn here would fail on
    /// `/bin/false`, so a passing schedulable test proves no subprocess spawned.
    fn bogus_sched_runner(
        remote: HashMap<String, ResolvedRemotePlacement>,
        sched: HashMap<String, ResolvedSchedulablePlacement>,
    ) -> ActorChildRunner {
        ActorChildRunner::new(
            "test-actor".into(),
            PathBuf::from("/bin/false"),
            vec![],
            std::env::temp_dir().join("bamboo-test-fab-181"),
            ExecutorSpec::Echo,
            vec![],
            "anthropic".into(),
            4,
        )
        .with_remote_placements(remote)
        .with_schedulable_placements(sched)
    }

    fn sched_placement(
        pool: &str,
        _registry_url: impl Into<String>,
    ) -> ResolvedSchedulablePlacement {
        ResolvedSchedulablePlacement {
            pool: pool.into(),
            host_label: None,
        }
    }

    #[test]
    fn build_spec_sets_schedulable_placement_for_matching_role() {
        let mut sched = HashMap::new();
        sched.insert(
            "explorer".to_string(),
            sched_placement("gpu-pool", "unused"),
        );
        let runner = bogus_sched_runner(HashMap::new(), sched);

        let s = session_of_role("explorer", "do the thing");
        let spec = runner.build_spec(&s, &job_for("child-1"));
        match &spec.placement {
            Placement::Schedulable { pool } => assert_eq!(pool, "gpu-pool"),
            other => panic!("expected Schedulable, got {other:?}"),
        }
        // No per-placement bearer now — the bus connection carries the bus token.
        assert!(spec.secrets.worker_auth_token.is_none());
    }

    #[test]
    fn build_spec_remote_wins_when_role_in_both_maps() {
        // A role present in BOTH remote_placements and schedulable_placements must
        // resolve to the FIXED remote placement (documented precedence).
        let mut remote = HashMap::new();
        remote.insert(
            "explorer".to_string(),
            ResolvedRemotePlacement {
                endpoint: "wss://fixed-host:8443".into(),
                token: Some("T-remote".into()),
                ca_cert_file: None,
                host_label: None,
            },
        );
        let mut sched = HashMap::new();
        sched.insert(
            "explorer".to_string(),
            sched_placement("gpu-pool", "https://control-plane:9562"),
        );
        let runner = bogus_sched_runner(remote, sched);

        let s = session_of_role("explorer", "do the thing");
        let spec = runner.build_spec(&s, &job_for("child-1"));
        match &spec.placement {
            Placement::Remote { endpoint } => assert_eq!(endpoint, "wss://fixed-host:8443"),
            other => panic!("expected Remote (precedence), got {other:?}"),
        }
        assert_eq!(spec.secrets.worker_auth_token.as_deref(), Some("T-remote"));
    }

    #[test]
    fn build_spec_local_for_unmatched_schedulable_role() {
        let mut sched = HashMap::new();
        sched.insert(
            "explorer".to_string(),
            sched_placement("gpu-pool", "https://control-plane:9562"),
        );
        let runner = bogus_sched_runner(HashMap::new(), sched);
        let s = session_of_role("writer", "do the thing");
        let spec = runner.build_spec(&s, &job_for("child-1"));
        assert_eq!(spec.placement, Placement::Local);
        assert!(spec.secrets.worker_auth_token.is_none());
    }

    /// The full role → resolved-placement → badge-host chain: a child routed to a
    /// remote/schedulable placement carrying a cluster node's `host_label` stamps
    /// that label; without a label it falls back to the endpoint host / pool; a
    /// Local child gets no stamp (the DTO defaults it to the backend host).
    #[test]
    fn placement_stamp_uses_node_label_for_remote_and_schedulable() {
        // Remote WITH a node label → {remote, <label>}, overriding the raw IP.
        let mut remote = HashMap::new();
        remote.insert(
            "explorer".to_string(),
            ResolvedRemotePlacement {
                endpoint: "ws://169.254.230.101:8899".into(),
                token: None,
                ca_cert_file: None,
                host_label: Some("mini".into()),
            },
        );
        let runner = bogus_runner(remote);
        let spec = runner.build_spec(&session_of_role("explorer", "go"), &job_for("c1"));
        let stamp = runner
            .placement_stamp_for(&spec)
            .expect("remote child is stamped");
        assert!(stamp.contains(r#""kind":"remote""#), "{stamp}");
        assert!(stamp.contains(r#""host":"mini""#), "{stamp}");

        // Remote WITHOUT a node label → falls back to the endpoint host.
        let mut remote_nolabel = HashMap::new();
        remote_nolabel.insert(
            "explorer".to_string(),
            ResolvedRemotePlacement {
                endpoint: "ws://169.254.230.101:8899".into(),
                token: None,
                ca_cert_file: None,
                host_label: None,
            },
        );
        let r2 = bogus_runner(remote_nolabel);
        let spec2 = r2.build_spec(&session_of_role("explorer", "go"), &job_for("c1"));
        assert!(r2
            .placement_stamp_for(&spec2)
            .unwrap()
            .contains(r#""host":"169.254.230.101""#));

        // Schedulable WITH a node label → {remote, <label>} (a node, not a pool name).
        let mut sched = HashMap::new();
        sched.insert(
            "mac-mini-monitor".to_string(),
            ResolvedSchedulablePlacement {
                pool: "mac-mini-monitor".into(),
                host_label: Some("mini".into()),
            },
        );
        let sr = bogus_sched_runner(HashMap::new(), sched);
        let spec3 = sr.build_spec(&session_of_role("mac-mini-monitor", "go"), &job_for("c1"));
        let stamp3 = sr
            .placement_stamp_for(&spec3)
            .expect("scheduled child is stamped");
        assert!(stamp3.contains(r#""kind":"remote""#), "{stamp3}");
        assert!(stamp3.contains(r#""host":"mini""#), "{stamp3}");

        // A Local (unmatched) child gets NO stamp.
        let local = bogus_runner(HashMap::new());
        let spec4 = local.build_spec(&session_of_role("writer", "go"), &job_for("c1"));
        assert_eq!(local.placement_stamp_for(&spec4), None);
    }

    // ---- #181: schedulable selection over the BUS (Phase 3 cutover) ----------

    async fn start_bus() -> (String, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let core = std::sync::Arc::new(bamboo_broker::BrokerCore::new(dir.path()));
        let server = std::sync::Arc::new(bamboo_broker::BrokerServer::new(core, "t"));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = server.serve(listener).await;
        });
        (format!("ws://{addr}"), dir)
    }

    async fn join_pool(endpoint: &str, id: &str, pool: &str) -> bamboo_broker::BrokerClient {
        let mut c = bamboo_broker::BrokerClient::connect(
            endpoint,
            bamboo_subagent::AgentRef {
                session_id: id.into(),
                role: Some(pool.into()),
            },
            "t",
        )
        .await
        .unwrap();
        c.subscribe().await.unwrap();
        c
    }

    fn sched_runner_on_bus(endpoint: &str, child_role: &str, pool: &str) -> ActorChildRunner {
        let mut sched = HashMap::new();
        sched.insert(child_role.to_string(), sched_placement(pool, "unused"));
        bogus_sched_runner(HashMap::new(), sched).with_bus(Some(bamboo_subagent::BusEndpoint {
            endpoint: endpoint.into(),
            token: "t".into(),
        }))
    }

    #[tokio::test]
    async fn resolve_schedulable_picks_a_live_bus_worker() {
        let (endpoint, _dir) = start_bus().await;
        let _w = join_pool(&endpoint, "w-gpu", "gpu-pool").await;
        let runner = sched_runner_on_bus(&endpoint, "explorer", "gpu-pool");

        let mailbox = runner
            .resolve_schedulable_worker("explorer")
            .await
            .expect("a live pool worker is found on the bus");
        assert_eq!(mailbox, "w-gpu");
    }

    #[tokio::test]
    async fn resolve_schedulable_round_robins_over_pool_workers() {
        let (endpoint, _dir) = start_bus().await;
        let _a = join_pool(&endpoint, "w-a", "gpu-pool").await;
        let _b = join_pool(&endpoint, "w-b", "gpu-pool").await;
        let runner = sched_runner_on_bus(&endpoint, "explorer", "gpu-pool");

        // Successive resolves spread across both connected workers.
        let mut picked = std::collections::HashSet::new();
        for _ in 0..6 {
            picked.insert(runner.resolve_schedulable_worker("explorer").await.unwrap());
        }
        assert_eq!(
            picked,
            ["w-a".to_string(), "w-b".to_string()].into_iter().collect(),
            "round-robin must cover every connected pool worker"
        );
    }

    #[tokio::test]
    async fn resolve_schedulable_errors_on_empty_pool() {
        let (endpoint, _dir) = start_bus().await;
        // No worker subscribes to "gpu-pool".
        let runner = sched_runner_on_bus(&endpoint, "explorer", "gpu-pool");

        let err = runner
            .resolve_schedulable_worker("explorer")
            .await
            .expect_err("an empty pool is terminal — no local fallback")
            .to_string();
        assert!(err.contains("no live worker in pool"), "got: {err}");
        assert!(err.contains("NOT spawning"), "got: {err}");
    }

    /// FULL schedulable run over the bus: a worker SERVING `EchoExecutor` joins the
    /// pool by role; `execute_external_child` with a Schedulable placement resolves
    /// it from the bus (no local subprocess — the worker_bin is `/bin/false`),
    /// drives the run, gets the echo back, AND stamps the child session with the
    /// pool's cluster-node label — `{kind:remote, host:"mini"}`. The end-to-end
    /// analogue of the live `mac-mini-monitor`→mini run.
    #[tokio::test]
    async fn execute_external_child_runs_schedulable_over_bus_and_stamps_node_label() {
        let (endpoint, _dir) = start_bus().await;

        // A bus worker SERVING runs (not just presence), joined to the pool by role.
        let ep = endpoint.clone();
        let worker = tokio::spawn(async move {
            let _ = bamboo_broker::serve_executor(
                &ep,
                bamboo_subagent::AgentRef {
                    session_id: "mmm-worker".into(),
                    role: Some("mac-mini-monitor".into()),
                },
                "t",
                std::sync::Arc::new(bamboo_subagent::executor::EchoExecutor),
            )
            .await;
        });

        // Wait until the worker is visible on the bus so the pool is non-empty
        // when execute_external_child resolves it (serve_executor connects async).
        let mut probe = bamboo_broker::BrokerClient::connect(
            &endpoint,
            bamboo_subagent::AgentRef {
                session_id: "probe".into(),
                role: None,
            },
            "t",
        )
        .await
        .unwrap();
        let mut ready = false;
        for _ in 0..100 {
            if probe
                .list_connected("mac-mini-monitor")
                .await
                .unwrap()
                .iter()
                .any(|id| id == "mmm-worker")
            {
                ready = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(30)).await;
        }
        assert!(ready, "worker never joined the pool");

        // Runner: child role → schedulable pool "mac-mini-monitor" carrying the
        // cluster node's label "mini"; bogus worker_bin so any local spawn fails.
        let mut sched = HashMap::new();
        sched.insert(
            "mac-mini-monitor".to_string(),
            ResolvedSchedulablePlacement {
                pool: "mac-mini-monitor".into(),
                host_label: Some("mini".into()),
            },
        );
        let runner = bogus_sched_runner(HashMap::new(), sched).with_bus(Some(
            bamboo_subagent::BusEndpoint {
                endpoint: endpoint.clone(),
                token: "t".into(),
            },
        ));

        let mut session = session_of_role("mac-mini-monitor", "hello scheduled");
        let job = job_for("child-1");
        let (event_tx, _rx) = mpsc::channel::<AgentEvent>(64);
        let cancel = CancellationToken::new();

        tokio::time::timeout(
            Duration::from_secs(10),
            runner.execute_external_child(&mut session, &job, event_tx, cancel),
        )
        .await
        .expect("run did not hang")
        .expect("schedulable run succeeded over the bus (no local spawn)");

        // Echo reply flowed back — proves it routed to the bus worker, not local.
        let last = session
            .messages
            .iter()
            .rev()
            .find(|m| matches!(m.role, Role::Assistant))
            .expect("an assistant reply was written back");
        assert!(last.content.contains("echo:"), "got {:?}", last.content);

        // ...and the child is stamped with the pool's cluster-node label.
        let placement = session
            .metadata
            .get("placement")
            .expect("scheduled child session stamped with a placement");
        assert!(placement.contains(r#""kind":"remote""#), "{placement}");
        assert!(placement.contains(r#""host":"mini""#), "{placement}");

        worker.abort();
    }
}