bamboo-engine 2026.10.16

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
//! Bridge between structured [`AgentRuntimeState`] and session metadata.
//!
//! The read path prefers the structured `session.agent_runtime_state` field
//! and falls back to the legacy `session.metadata["agent.runtime.state"]` key.
//! The write path writes only to the structured field; the legacy metadata
//! mirror is no longer maintained.

use std::sync::Arc;

use bamboo_agent_core::{AgentError, Message, Session};
use bamboo_domain::{
    AgentRuntimeState, SessionInboxPort, SessionMessageBody, SessionMessageContent,
    SessionMessageEnvelope, SessionMessageId, SessionMessageKind, SessionMessageSource,
    SessionRuntimeInstruction,
};

const METADATA_KEY: &str = "agent.runtime.state";
const INBOX_ACK_UNRESOLVED: &str =
    "SessionInbox ACK unresolved; durable input is preserved; retry this activation";
const INBOX_CLAIM_UNRESOLVED: &str =
    "SessionInbox claim unresolved; durable input is preserved; retry with its current owner";
/// Original scalar data borrowed without Message, image or Source retention.
#[derive(Clone, Copy)]
pub struct BorrowedInputRequestRecord<'a> {
    pub input_id: &'a str,
    pub source: &'a SessionMessageSource,
    pub kind: SessionMessageKind,
    pub wrapper: Option<&'a str>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub request: Option<&'a bamboo_domain::SessionSkillRequest>,
}

// Private deterministic measurement, never a wire/persistence format or decoder.
#[derive(serde::Serialize)]
struct InputRequestMeasurement<'a, T> {
    session_id: &'a str,
    execution_id: &'a str,
    records: T,
}
struct InputRequestRecordsMeasurement<'a>(&'a [BorrowedInputRequestRecord<'a>]);
impl serde::Serialize for InputRequestRecordsMeasurement<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeSeq;
        let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
        for record in self.0 {
            sequence.serialize_element(&(
                record.input_id,
                record.source,
                record.kind,
                record.wrapper,
                record.created_at,
                record.request,
            ))?;
        }
        sequence.end()
    }
}

/// Validate all borrowed data and charge the whole batch before any owned copy.
/// Success does not classify input as New, authorize it or publish anything.
pub fn project_input_request_batch(
    session_id: &str,
    execution_id: &str,
    records: &[BorrowedInputRequestRecord<'_>],
) -> crate::runtime::managers::lifecycle::InputRequestProjection {
    use crate::runtime::managers::lifecycle::{
        BoundedInputRequestBatch,
        InputRequestProjection::{Available, Unavailable},
        InputRequestUnavailable, ProjectedInputRequest,
    };
    const LIMIT: usize = 262144;
    if records.len() > 128 {
        return Unavailable(InputRequestUnavailable::RecordLimit {
            count: records.len(),
            limit: 128,
        });
    }
    for record in records {
        let id = record.input_id;
        if id.trim().is_empty()
            || id.trim() != id
            || id.len() > 256
            || id.contains('/')
            || id.contains('\\')
            || id.contains("..")
            || record
                .request
                .is_some_and(|request| request.validate().is_err())
        {
            return Unavailable(InputRequestUnavailable::InvalidData);
        }
    }
    let Some(compact_bytes) = measure_input_request_view(
        session_id,
        execution_id,
        InputRequestRecordsMeasurement(records),
    ) else {
        return Unavailable(InputRequestUnavailable::CompactLimit { limit: LIMIT });
    };
    let records = records
        .iter()
        .map(|record| ProjectedInputRequest {
            input_id: record.input_id.into(),
            source: match record.source {
                SessionMessageSource::User => SessionMessageSource::User,
                SessionMessageSource::Session { session_id } => SessionMessageSource::Session {
                    session_id: session_id.as_str().into(),
                },
                SessionMessageSource::Runtime { subsystem } => SessionMessageSource::Runtime {
                    subsystem: subsystem.as_str().into(),
                },
            },
            kind: record.kind,
            wrapper: record.wrapper.map(String::from),
            created_at: record.created_at,
            request: record
                .request
                .map(|request| bamboo_domain::SessionSkillRequest {
                    mode: request.mode.as_deref().map(String::from),
                    selections: request
                        .selections
                        .iter()
                        .map(|selection| bamboo_domain::SessionSkillSelection {
                            id: selection.id.as_str().into(),
                            source: selection.source.as_str().into(),
                            revision: selection.revision,
                            args: copy_input_request_value(&selection.args),
                        })
                        .collect::<Vec<_>>()
                        .into_boxed_slice()
                        .into_vec(),
                }),
        })
        .collect::<Vec<_>>()
        .into_boxed_slice();
    Available(BoundedInputRequestBatch {
        session_id: session_id.into(),
        execution_id: execution_id.into(),
        records,
        compact_bytes,
    })
}

fn measure_input_request_view(
    session_id: &str,
    execution_id: &str,
    records: impl serde::Serialize,
) -> Option<usize> {
    struct CountingWrite(usize);
    impl std::io::Write for CountingWrite {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0 = self
                .0
                .checked_add(bytes.len())
                .filter(|n| *n <= 262144)
                .ok_or_else(|| std::io::Error::other("compact input byte limit"))?;
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut count = CountingWrite(0);
    serde_json::to_writer(
        &mut count,
        &InputRequestMeasurement {
            session_id,
            execution_id,
            records,
        },
    )
    .ok()?;
    Some(count.0)
}

// Borrow the canonical request representation, including absent/default fields.
// Serde counts the same keys/scalars as Q-B without copying any args tree.
#[derive(serde::Serialize)]
struct RawRequest<'a> {
    selections: RawSelections<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    mode: Option<&'a str>,
}
struct RawSelections<'a>(&'a [serde_json::Value]);
#[derive(serde::Serialize)]
struct RawSelection<'a> {
    id: &'a str,
    source: &'a str,
    revision: u64,
    args: &'a serde_json::Value,
}
fn raw_selection(value: &serde_json::Value) -> Option<RawSelection<'_>> {
    let fields = value.as_object()?;
    if fields
        .keys()
        .any(|k| !matches!(k.as_str(), "id" | "source" | "revision" | "args"))
    {
        return None;
    }
    Some(RawSelection {
        id: value.get("id")?.as_str()?,
        source: value.get("source")?.as_str()?,
        revision: value.get("revision")?.as_u64()?,
        args: value.get("args").unwrap_or(&serde_json::Value::Null),
    })
}
impl serde::Serialize for RawSelections<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeSeq;
        let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
        for value in self.0 {
            sequence.serialize_element(
                &raw_selection(value)
                    .ok_or_else(|| serde::ser::Error::custom("invalid checked selection"))?,
            )?;
        }
        sequence.end()
    }
}
fn raw_request(value: &serde_json::Value) -> Option<RawRequest<'_>> {
    let fields = value.as_object()?;
    if fields
        .keys()
        .any(|k| !matches!(k.as_str(), "selections" | "mode"))
    {
        return None;
    }
    let selections = value.get("selections")?.as_array()?;
    if selections.is_empty() || selections.len() > 32 {
        return None;
    }
    let mode = match value.get("mode") {
        None | Some(serde_json::Value::Null) => None,
        Some(value) => Some(value.as_str()?),
    };
    if mode.is_some_and(|mode| {
        mode.is_empty()
            || mode.len() > 64
            || !mode
                .bytes()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
    }) {
        return None;
    }
    for (index, value) in selections.iter().enumerate() {
        let selection = raw_selection(value)?;
        bamboo_domain::SessionSkillSelection::validate_borrowed(
            selection.id,
            selection.source,
            selection.revision,
            selection.args,
        )
        .ok()?;
        if selections[..index]
            .iter()
            .any(|prior| prior.get("id").and_then(|v| v.as_str()) == Some(selection.id))
        {
            return None;
        }
    }
    Some(RawRequest {
        selections: RawSelections(selections),
        mode,
    })
}
#[derive(serde::Serialize)]
struct RawInputRecord<'a>(
    &'a str,
    &'a serde_json::Value,
    SessionMessageKind,
    Option<&'static str>,
    chrono::DateTime<chrono::Utc>,
    Option<RawRequest<'a>>,
);

// Private caller precondition: ONLY this completed boundary's New/ACKed prefix.
// Never call on transcript history or use this projection as a provenance test.
fn project_new_committed_inputs(
    session_id: &str,
    execution_id: &str,
    messages: &[Message],
) -> crate::runtime::managers::lifecycle::InputRequestProjection {
    use crate::runtime::managers::lifecycle::{
        BoundedInputRequestBatch,
        InputRequestProjection::{Available, Unavailable},
        InputRequestUnavailable, ProjectedInputRequest,
    };
    if messages.len() > 128 {
        return Unavailable(InputRequestUnavailable::RecordLimit {
            count: messages.len(),
            limit: 128,
        });
    }
    let parse = || -> Option<Vec<RawInputRecord<'_>>> {
        let mut records = Vec::with_capacity(messages.len());
        for message in messages {
            let proof = message.metadata.as_ref()?.get("session_message")?;
            let source = proof.get("source")?;
            let body = proof.get("body")?;
            let (kind, wrapper, content) =
                match (source.get("type")?.as_str()?, proof.get("kind")?.as_str()?) {
                    ("user", "user_input")
                        if source.as_object()?.len() == 1
                            && body.get("type")?.as_str()? == "content" =>
                    {
                        (SessionMessageKind::UserInput, None, body)
                    }
                    ("runtime", "runtime_instruction")
                        if source.as_object()?.len() == 2
                            && source.get("subsystem")?.as_str()? == "chat"
                            && body.get("type")?.as_str()? == "runtime_instruction"
                            && body.get("instruction")?.as_str()? == "root_chat_turn_v1" =>
                    {
                        (
                            SessionMessageKind::RuntimeInstruction,
                            Some("root_chat_turn_v1"),
                            body.get("content")?,
                        )
                    }
                    _ => return None,
                };
            let id = message.id.as_str();
            if proof.get("id")?.as_str()? != id
                || proof.get("target_session_id")?.as_str()? != session_id
                || id.is_empty()
                || id.len() > 256
                || id.trim() != id
                || id.contains('/')
                || id.contains('\\')
                || id.contains("..")
            {
                return None;
            }
            let time = proof
                .get("created_at")?
                .as_str()?
                .parse::<chrono::DateTime<chrono::Utc>>()
                .ok()?;
            if time != message.created_at {
                return None;
            }
            let request = match content.get("skill_request").filter(|v| !v.is_null()) {
                Some(value) => Some(raw_request(value)?),
                None => None,
            };
            records.push(RawInputRecord(id, source, kind, wrapper, time, request));
        }
        Some(records)
    };
    let Some(records) = parse() else {
        return Unavailable(InputRequestUnavailable::InvalidData);
    };
    let Some(compact_bytes) = measure_input_request_view(session_id, execution_id, &records) else {
        return Unavailable(InputRequestUnavailable::CompactLimit { limit: 262144 });
    };
    let records = records
        .iter()
        .map(|record| ProjectedInputRequest {
            input_id: record.0.into(),
            source: if record.2 == SessionMessageKind::UserInput {
                SessionMessageSource::User
            } else {
                SessionMessageSource::Runtime {
                    subsystem: "chat".into(),
                }
            },
            kind: record.2,
            wrapper: record.3.map(String::from),
            created_at: record.4,
            request: record
                .5
                .as_ref()
                .map(|request| bamboo_domain::SessionSkillRequest {
                    mode: request.mode.map(String::from),
                    selections: request
                        .selections
                        .0
                        .iter()
                        .map(|value| {
                            let selection =
                                raw_selection(value).expect("validated borrowed selection");
                            bamboo_domain::SessionSkillSelection {
                                id: selection.id.into(),
                                source: selection.source.into(),
                                revision: selection.revision,
                                args: copy_input_request_value(selection.args),
                            }
                        })
                        .collect::<Vec<_>>()
                        .into_boxed_slice()
                        .into_vec(),
                }),
        })
        .collect::<Vec<_>>()
        .into_boxed_slice();
    Available(BoundedInputRequestBatch {
        session_id: session_id.into(),
        execution_id: execution_id.into(),
        records,
        compact_bytes,
    })
}

// Called only after accepted I-W depth64/node8192/byte validation and full fit.
// Copy lengths, including nested strings/keys/arrays, never source capacities.
fn copy_input_request_value(value: &serde_json::Value) -> serde_json::Value {
    use serde_json::Value;
    match value {
        Value::String(value) => Value::String(value.as_str().into()),
        Value::Array(values) => Value::Array(
            values
                .iter()
                .map(copy_input_request_value)
                .collect::<Vec<_>>()
                .into_boxed_slice()
                .into_vec(),
        ),
        Value::Object(values) => Value::Object(
            values
                .iter()
                .map(|(key, value)| (key.as_str().into(), copy_input_request_value(value)))
                .collect(),
        ),
        scalar => scalar.clone(),
    }
}

#[cfg(test)]
const PENDING_INJECTED_MESSAGES_KEY: &str = "pending_injected_messages";

fn adopt_root_tool_authority(session: &mut Session, latest: &Session) -> Result<(), AgentError> {
    check_conversation_readback(session, Some(latest))?;
    session
        .adopt_root_tool_authority_from(latest)
        .map_err(|error| {
            AgentError::Tool(format!(
                "authoritative Root tool authority refresh failed closed: {error}"
            ))
        })
}

/// Validate the original operation before adopting any canonical fields. A
/// nonzero conversation requires an available canonical read; absence remains
/// compatible only with an original zero-generation in-memory Session.
pub(crate) fn check_conversation_readback(
    original: &Session,
    canonical: Option<&Session>,
) -> Result<(), AgentError> {
    let conflict =
        |reason: String| AgentError::Tool(format!("session_conversation_changed: {reason}"));
    original
        .validate_conversation_state()
        .map_err(|error| conflict(error.to_string()))?;
    match canonical {
        Some(canonical) => original
            .check_conversation_generation(canonical)
            .map_err(|error| conflict(error.to_string())),
        None if original.conversation_reset.is_some() => Err(conflict(
            "canonical conversation unavailable; reload required".into(),
        )),
        None => Ok(()),
    }
}

fn ordinary_root_uses_tool_authority_proof(session: &Session) -> bool {
    session.kind == bamboo_domain::SessionKind::Root
        && session.parent_session_id.is_none()
        && session.authority_identity.is_ordinary()
}

/// Publish a genuinely new SDK Root through the Storage creation contract
/// before the first provider round. Storage must reject an old snapshot from a
/// deleted lifetime; a subsequent strict read binds the running snapshot to
/// the durable authority. Server-created Roots are already present here.
pub async fn ensure_initial_root_tool_authority(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
) -> Result<(), AgentError> {
    if !ordinary_root_uses_tool_authority_proof(session) {
        return Ok(());
    }
    let Some(storage) = storage else {
        return Ok(());
    };
    let mut latest = storage
        .load_runtime_control_plane(&session.id)
        .await
        .map_err(|error| {
            AgentError::Tool(format!(
                "initial Root tool authority read failed closed: {error}"
            ))
        })?;
    check_conversation_readback(session, latest.as_ref())?;
    if latest.is_none() {
        storage.save_session(session).await.map_err(|error| {
            AgentError::Tool(format!(
                "initial Root authority publication failed closed: {error}"
            ))
        })?;
        latest = storage
            .load_runtime_control_plane(&session.id)
            .await
            .map_err(|error| {
                AgentError::Tool(format!(
                    "initial Root tool authority read failed closed: {error}"
                ))
            })?;
    }
    let latest = latest.ok_or_else(|| {
        AgentError::Tool("initial Root tool authority read failed closed: session missing".into())
    })?;
    adopt_root_tool_authority(session, &latest)
}

/// Recheck a Root before constructing its next provider catalog. Tool-boundary
/// checks protect execution, while this bounded control-plane read also removes
/// tools that were revoked after the prior round's last call. A Supervisor uses
/// its existing strict management-proof read, not the ordinary Root path.
pub async fn refresh_round_root_tool_authority(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
) -> Result<(), AgentError> {
    if session.kind != bamboo_domain::SessionKind::Root || session.parent_session_id.is_some() {
        return Ok(());
    }
    let Some(storage) = storage else {
        return Ok(());
    };
    let latest_read = if session.authority_identity.is_ordinary() {
        storage.load_runtime_control_plane(&session.id).await
    } else {
        storage.load_root_authority(&session.id).await
    };
    let latest = latest_read.map_err(|error| {
        AgentError::Tool(format!(
            "authoritative Root tool authority refresh failed closed: {error}"
        ))
    })?;
    let latest = latest.ok_or_else(|| {
        AgentError::Tool(
            "authoritative Root tool authority refresh failed closed: session missing".to_string(),
        )
    })?;
    adopt_root_tool_authority(session, &latest)
}

/// Read `AgentRuntimeState` from session.
///
/// Tries the structured field first, falls back to the metadata key.
#[allow(dead_code)]
pub fn read_runtime_state(session: &Session) -> Option<AgentRuntimeState> {
    session.agent_runtime_state.clone().or_else(|| {
        session
            .metadata
            .get(METADATA_KEY)
            .and_then(|raw| serde_json::from_str::<AgentRuntimeState>(raw).ok())
    })
}

/// Write `AgentRuntimeState` to the structured session field.
///
/// Only writes to `session.agent_runtime_state`. The legacy metadata mirror
/// was removed after the migration completed.
pub fn write_runtime_state(session: &mut Session, state: &AgentRuntimeState) {
    session.agent_runtime_state = Some(state.clone());
}

/// Sync runtime state fields from existing metadata keys.
///
/// This extracts values that are currently stored as individual metadata
/// entries into the structured runtime state.
pub fn sync_from_metadata(session: &Session, state: &mut AgentRuntimeState) {
    // LLM info
    if state.llm.model_name.is_none() {
        state.llm.model_name = Some(session.model.clone());
    }
    if state.llm.provider_name.is_none() {
        state.llm.provider_name = session.provider_name();
    }
    if state.llm.responses_previous_id.is_none() {
        state.llm.responses_previous_id = session
            .metadata
            .get("responses.previous_response_id")
            .cloned();
    }

    // Prompt info
    if state.prompt.composer_version.is_none() {
        state.prompt.composer_version = session
            .metadata
            .get("runtime_prompt_composer_version")
            .cloned();
    }
    if state.prompt.section_flags.is_none() {
        state.prompt.section_flags = session
            .metadata
            .get("runtime_prompt_component_flags")
            .cloned();
    }
    if state.prompt.section_lengths.is_none() {
        state.prompt.section_lengths = session
            .metadata
            .get("runtime_prompt_component_lengths")
            .cloned();
    }
    if state.prompt.section_layout.is_none() {
        state.prompt.section_layout = session
            .metadata
            .get("runtime_prompt_section_layout")
            .cloned();
    }
}

/// Result of a turn-boundary disk refresh: how many injected messages were
/// merged, which newly appended messages have a durable transcript checkpoint,
/// and the live per-session permission mode as it stands on disk (the
/// authoritative writer is `PATCH /sessions`).
#[derive(Debug, Default, Clone)]
pub struct TurnBoundaryRefresh {
    pub merged: usize,
    /// Newly appended messages whose transcript checkpoint completed at this
    /// boundary. Callers may publish these only after this function returns;
    /// recovery of an already-committed message is intentionally excluded.
    pub committed_messages: Vec<Message>,
    /// An unresolved ACK stops this activation even if its transcript and
    /// permanent receipt are already durable. Neither is proof that ACK returned
    /// successfully; the next safe boundary can retry existing recovery.
    pub admission_error: Option<String>,
    /// `None` when there was no storage / no on-disk session to read.
    pub disk_permission_mode: Option<bamboo_domain::SessionPermissionMode>,
}

/// Refresh the authoritative permission posture and Root tool authority at a
/// tool-dispatch safe boundary.
///
/// Unlike [`refresh_turn_boundary_with_inbox`], this deliberately never merges
/// messages, SessionInbox claims, or any other control-plane field. Sequential
/// tool calls may have externally visible side effects, so a configured durable
/// store must be readable before the next call is admitted: keeping an old Auto
/// posture after an Auto -> Default transition would execute without the newly
/// required approval. SDK/in-memory runtimes with no store retain their current
/// posture.
pub async fn refresh_tool_boundary_authorities(
    session: &mut Session,
    runtime_state: &mut AgentRuntimeState,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
) -> Result<(), AgentError> {
    let Some(storage) = storage else {
        return check_conversation_readback(session, None);
    };
    let latest = storage
        .load_runtime_control_plane(&session.id)
        .await
        .map_err(|error| {
            AgentError::Tool(format!(
                "authoritative permission posture refresh failed closed: {error}"
            ))
        })?
        .ok_or_else(|| {
            AgentError::Tool(
                "authoritative permission posture refresh failed closed: session missing"
                    .to_string(),
            )
        })?;
    check_conversation_readback(session, Some(&latest))?;
    let disk_mode = latest
        .agent_runtime_state
        .as_ref()
        .map(AgentRuntimeState::effective_permission_mode)
        .ok_or_else(|| {
            AgentError::Tool(
                "authoritative permission posture refresh failed closed: typed mode missing"
                    .to_string(),
            )
        })?;
    let current_mode = session
        .agent_runtime_state
        .as_ref()
        .map(AgentRuntimeState::effective_permission_mode)
        .unwrap_or_else(|| runtime_state.effective_permission_mode());

    let should_adopt_audit = bamboo_domain::disk_permission_posture_is_fresher(
        current_mode,
        &session.metadata,
        disk_mode,
        &latest.metadata,
    );
    let fresher_audit = bamboo_domain::fresher_disk_permission_audit(
        current_mode,
        &session.metadata,
        disk_mode,
        &latest.metadata,
    );
    if should_adopt_audit && fresher_audit.is_none() {
        return Err(AgentError::Tool(
            "authoritative permission posture refresh failed closed: complete audit unavailable"
                .to_string(),
        ));
    }

    // Commit the coherent pair only after every fallible validation above. A
    // failed refresh leaves the owned snapshot untouched and dispatch never
    // enters the executor.
    adopt_root_tool_authority(session, &latest)?;
    if let Some(audit) = fresher_audit {
        audit.write_to(&mut session.metadata);
    }
    runtime_state.set_permission_mode(disk_mode);
    session
        .agent_runtime_state
        .get_or_insert_with(AgentRuntimeState::default)
        .set_permission_mode(disk_mode);
    Ok(())
}

/// Result of migrating only the rolling-upgrade legacy ingress queue.
///
/// Terminal execution paths use this without claiming the typed inbox: every
/// returned generation still needs a successor reasoning turn.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct LegacyPendingMigration {
    pub delivered: usize,
    pub source_cleared: bool,
    pub highest_generation: Option<u64>,
}

/// Merge any queued follow-up messages that were injected via `send_message`
/// while a session is running.
///
/// Thin wrapper over [`refresh_turn_boundary_from_disk`] kept for callers that
/// only need the merge count. Returns the number of messages merged.
#[cfg(test)]
pub async fn merge_pending_injected_messages(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
) -> usize {
    refresh_turn_boundary_from_disk(session, storage, persistence)
        .await
        .merged
}

fn legacy_envelope(
    session_id: &str,
    index: usize,
    value: &serde_json::Value,
) -> SessionMessageEnvelope {
    let content = value
        .get("content")
        .and_then(serde_json::Value::as_str)
        .map(ToOwned::to_owned)
        .unwrap_or_else(|| value.to_string());
    SessionMessageEnvelope {
        id: SessionMessageId::legacy(session_id, index, value),
        source: SessionMessageSource::Runtime {
            subsystem: "legacy_pending_injected_messages".to_string(),
        },
        target_session_id: session_id.to_string(),
        kind: SessionMessageKind::RuntimeInstruction,
        body: SessionMessageBody::RuntimeInstruction(SessionRuntimeInstruction {
            instruction: "legacy_pending_injected_message".to_string(),
            content: Some(SessionMessageContent::text(content)),
            // Preserve the complete legacy value for audit/replay even when it
            // contained fields the old bridge ignored.
            data: Some(value.clone()),
            provider_message: None,
        }),
        created_at: chrono::Utc::now(),
        thread_id: None,
        in_reply_to: None,
        attempt: None,
        correlation_id: Some("legacy_pending_injected_messages".to_string()),
    }
}

async fn migrate_legacy_pending_messages(
    session_id: &str,
    messages: &[serde_json::Value],
    inbox: &Arc<dyn SessionInboxPort>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
) -> LegacyPendingMigration {
    if persistence.is_some_and(|p| p.root_inbox_receipt().is_some()) {
        return LegacyPendingMigration::default();
    }
    if messages.is_empty() {
        return LegacyPendingMigration {
            source_cleared: true,
            ..LegacyPendingMigration::default()
        };
    }
    tracing::info!(
        telemetry_event = "session_inbox.legacy_pending_ingress",
        session_id,
        count = messages.len(),
        "observed rolling-upgrade legacy pending-message ingress"
    );
    let mut migration = LegacyPendingMigration::default();
    for (index, value) in messages.iter().enumerate() {
        let envelope = legacy_envelope(session_id, index, value);
        match inbox.deliver(&envelope).await {
            Ok(receipt) => {
                migration.delivered += 1;
                // The legacy source is the only restart signal until its
                // coordinated CAS-clear. Authorize every durable prefix before
                // that source can be removed, so a crash after clear can never
                // leave a pending typed message behind an activation watermark
                // of zero. Marking does not itself start another loop: the
                // live caller claims below, while terminal callers hand the
                // generation to the activation router.
                if let Err(error) = inbox
                    .mark_activation_eligible(
                        session_id,
                        receipt.generation,
                        bamboo_domain::SessionActivationPolicy::InterruptSpecificWait,
                    )
                    .await
                {
                    tracing::warn!(
                        session_id,
                        message_id = %envelope.id,
                        generation = receipt.generation,
                        %error,
                        "legacy pending message migration stopped before source cleanup because activation authorization failed"
                    );
                    return migration;
                }
                migration.highest_generation = Some(
                    migration
                        .highest_generation
                        .map_or(receipt.generation, |current| {
                            current.max(receipt.generation)
                        }),
                );
            }
            Err(error) => {
                // Some earlier entries may already be durable. Their
                // deterministic ids make the next bounded retry safe; never
                // clear the source queue unless every enqueue completed.
                tracing::warn!(
                    session_id,
                    message_id = %envelope.id,
                    %error,
                    "legacy pending message migration stopped before source cleanup"
                );
                return migration;
            }
        }
    }

    let Some(persistence) = persistence else {
        tracing::warn!(
            session_id,
            "legacy pending messages were delivered but cannot be cleared without coordinated persistence"
        );
        return migration;
    };
    match persistence
        .clear_legacy_pending_messages(session_id, messages)
        .await
    {
        Ok(true) => {
            tracing::info!(
                session_id,
                count = messages.len(),
                "migrated legacy pending messages into SessionInbox"
            );
            migration.source_cleared = true;
        }
        Ok(false) => {
            tracing::debug!(
                session_id,
                "legacy pending source changed during migration; leaving it for a deterministic retry"
            );
        }
        Err(error) => {
            tracing::warn!(
                session_id,
                %error,
                "legacy pending messages are durable but source cleanup failed"
            );
        }
    }
    migration
}

/// Terminal-window compatibility migration.
///
/// Loads the latest durable legacy queue, enqueues it into the typed inbox and
/// clears it with the same CAS protocol as a normal turn boundary, but never
/// claims or acknowledges typed work. The caller must hand
/// `highest_generation` to the activation router before finalization.
pub async fn migrate_legacy_pending_only(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
    inbox: Option<&Arc<dyn SessionInboxPort>>,
) -> LegacyPendingMigration {
    let (Some(storage), Some(inbox)) = (storage, inbox) else {
        return LegacyPendingMigration::default();
    };
    let latest = match storage.load_session(&session.id).await {
        Ok(Some(latest)) => latest,
        Ok(None) => return LegacyPendingMigration::default(),
        Err(error) => {
            tracing::warn!(
                session_id = %session.id,
                %error,
                "terminal legacy SessionInbox migration could not load session"
            );
            return LegacyPendingMigration::default();
        }
    };
    if let Err(error) = check_conversation_readback(session, Some(&latest)) {
        tracing::warn!(session_id = %session.id, %error, "legacy migration refused another conversation");
        return LegacyPendingMigration::default();
    }
    let Some(messages) = latest.pending_injected_messages() else {
        return LegacyPendingMigration::default();
    };
    let migration =
        migrate_legacy_pending_messages(&session.id, &messages, inbox, persistence).await;
    if migration.source_cleared
        && session.pending_injected_messages().as_deref() == Some(messages.as_slice())
    {
        session.clear_pending_injected_messages();
    }
    migration
}

#[derive(Debug, Default)]
struct InboxAdmission {
    observation_complete: bool,
    merged: usize,
    committed_messages: Vec<Message>,
    admission_error: Option<String>,
}

async fn admit_session_inbox(
    session: &mut Session,
    inbox: &Arc<dyn SessionInboxPort>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
    active_run_id: Option<&str>,
) -> InboxAdmission {
    let Some(persistence) = persistence else {
        tracing::warn!(
            session_id = %session.id,
            "SessionInbox cannot admit without durable runtime persistence"
        );
        return InboxAdmission {
            admission_error: Some(INBOX_CLAIM_UNRESOLVED.to_string()),
            ..Default::default()
        };
    };
    match persistence
        .admit_root_inbox(session, inbox.clone(), active_run_id)
        .await
    {
        Ok(Some(admission)) => {
            if let Some(error) = &admission.admission_error {
                tracing::warn!(session_id = %session.id, %error, "owned Root Inbox admission stopped");
            }
            return InboxAdmission {
                observation_complete: admission.admission_error.is_none(),
                merged: admission.merged,
                committed_messages: admission.committed_messages,
                admission_error: admission
                    .admission_error
                    .map(|_| INBOX_CLAIM_UNRESOLVED.to_string()),
            };
        }
        Err(error) => {
            tracing::warn!(session_id = %session.id, %error, "owned Root Inbox admission failed");
            return InboxAdmission {
                admission_error: Some(INBOX_CLAIM_UNRESOLVED.to_string()),
                ..Default::default()
            };
        }
        Ok(None) => {}
    }
    let claims = match inbox.claim_for_turn(&session.id, 128, active_run_id).await {
        Ok(claims) => claims,
        Err(error) => {
            tracing::warn!(session_id = %session.id, %error, "failed to claim SessionInbox");
            return InboxAdmission {
                admission_error: Some(INBOX_CLAIM_UNRESOLVED.to_string()),
                ..Default::default()
            };
        }
    };

    let count = claims.len();
    let mut admission = InboxAdmission {
        observation_complete: count == 0,
        ..Default::default()
    };
    for (index, claim) in claims.into_iter().enumerate() {
        let permanently_admitted = match inbox.was_admitted(&session.id, &claim.envelope.id).await {
            Ok(value) => value,
            Err(error) => {
                tracing::warn!(
                    session_id = %session.id,
                    message_id = %claim.envelope.id,
                    %error,
                    "failed to inspect SessionInbox admitted receipt"
                );
                break;
            }
        };
        if permanently_admitted {
            let durable = match persistence.load_runtime_session(&session.id).await {
                Ok(Some(durable)) => durable,
                Ok(None) => {
                    tracing::error!(
                        session_id = %session.id,
                        message_id = %claim.envelope.id,
                        "permanent SessionInbox receipt has no durable transcript to verify; leaving claim recoverable"
                    );
                    break;
                }
                Err(error) => {
                    tracing::warn!(
                        session_id = %session.id,
                        message_id = %claim.envelope.id,
                        %error,
                        "failed to load durable transcript for permanent SessionInbox receipt"
                    );
                    break;
                }
            };
            if let Err(error) = check_conversation_readback(session, Some(&durable)) {
                tracing::warn!(session_id = %session.id, %error, "permanent receipt belongs to another conversation; leaving claim recoverable");
                admission.admission_error = Some(error.to_string());
                break;
            }
            let Some(message) = durable
                .messages
                .iter()
                .find(|message| {
                    bamboo_domain::is_matching_session_message(message, &claim.envelope)
                })
                .cloned()
            else {
                // Receipt-without-transcript is a damaged/incomplete commit.
                // Keep cur as the only recoverable copy. Cursor membership is
                // not required here because it is intentionally bounded.
                tracing::error!(
                    session_id = %session.id,
                    message_id = %claim.envelope.id,
                    "permanent SessionInbox receipt lacks matching typed transcript proof; leaving claim recoverable"
                );
                break;
            };
            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, &durable);
            if let Err(error) = inbox.ack(&session.id, &claim).await {
                tracing::warn!(
                    session_id = %session.id,
                    message_id = %claim.envelope.id,
                    %error,
                    "failed to remove permanently admitted duplicate"
                );
                admission.admission_error = Some(INBOX_ACK_UNRESOLVED.to_string());
                break;
            }
            admission.observation_complete = index + 1 == count;
            continue;
        }

        let transcript_has_id = session
            .messages
            .iter()
            .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope));
        let transcript_has_conflicting_id = session
            .messages
            .iter()
            .any(|message| message.id == claim.envelope.id.as_str())
            && !transcript_has_id;
        if transcript_has_conflicting_id {
            tracing::error!(
                session_id = %session.id,
                message_id = %claim.envelope.id,
                "SessionInbox id collides with a non-matching transcript message; leaving claim recoverable"
            );
            break;
        }
        let cursor_has_id = session
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&claim.envelope.id));
        if cursor_has_id && !transcript_has_id {
            // Fail closed: an admitted cursor without its transcript message is
            // an invariant violation. Never establish a permanent tombstone
            // that could discard the only recoverable queue copy.
            tracing::error!(
                session_id = %session.id,
                message_id = %claim.envelope.id,
                "SessionInbox cursor exists without transcript message; leaving claim recoverable"
            );
            break;
        }

        let before = session.clone();
        if !transcript_has_id {
            match claim.envelope.to_provider_message() {
                Ok(message) => session.add_message(message),
                Err(error) => {
                    tracing::warn!(
                        session_id = %session.id,
                        message_id = %claim.envelope.id,
                        %error,
                        "typed SessionInbox envelope failed provider translation"
                    );
                    break;
                }
            }
        }
        session
            .session_inbox_admission_mut()
            .record(claim.envelope.id.clone(), claim.generation);
        session.updated_at = chrono::Utc::now();

        // The provider-valid Message and bounded cursor live in the same
        // session.json atomic checkpoint. Only after that succeeds may ack
        // create the permanent admitted-id receipt and remove the claim.
        if let Err(error) = persistence.checkpoint_runtime_session(session).await {
            *session = before;
            tracing::warn!(
                session_id = %session.id,
                message_id = %claim.envelope.id,
                %error,
                "SessionInbox checkpoint failed; claim remains recoverable"
            );
            break;
        }
        if !session
            .messages
            .iter()
            .any(|message| bamboo_domain::is_matching_session_message(message, &claim.envelope))
        {
            *session = before;
            tracing::error!(
                session_id = %session.id,
                message_id = %claim.envelope.id,
                "SessionInbox checkpoint lost typed transcript proof to a concurrent id collision; leaving claim recoverable"
            );
            break;
        }
        // Capture only the message appended by this checkpoint. A recovered
        // transcript entry is already represented by its original append and
        // must not mint a duplicate durable change-feed coordinate.
        if !transcript_has_id {
            if let Some(message) = session
                .messages
                .iter()
                .find(|message| {
                    bamboo_domain::is_matching_session_message(message, &claim.envelope)
                })
                .cloned()
            {
                admission.committed_messages.push(message);
            }
        }
        if let Err(error) = inbox.ack(&session.id, &claim).await {
            tracing::warn!(
                session_id = %session.id,
                message_id = %claim.envelope.id,
                %error,
                "SessionInbox checkpoint succeeded but ack failed; dedupe will recover"
            );
            admission.admission_error = Some(INBOX_ACK_UNRESOLVED.to_string());
            break;
        }
        if !transcript_has_id {
            admission.merged += 1;
        }
        admission.observation_complete = index + 1 == count;
    }
    admission
}

/// Turn-boundary refresh from the on-disk session: a SINGLE load that both
/// merges queued `send_message` injections AND reads the live typed permission
/// mode.
///
/// The mode read is what makes a mid-run
/// `PATCH /sessions {permission_mode|bypass_permissions}` take effect on the
/// CURRENT run: the run owns a `Session` value taken at spawn and never
/// otherwise re-reads storage, so the caller applies the returned
/// `disk_permission_mode` to the live runtime state at each round boundary. The
/// posture is folded into the existing per-round load so large parent sessions
/// aren't deserialized twice.
#[cfg(test)]
pub async fn refresh_turn_boundary_from_disk(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
) -> TurnBoundaryRefresh {
    refresh_turn_boundary_with_inbox(session, storage, persistence, None).await
}

/// Turn-boundary refresh with the first-class durable SessionInbox enabled.
pub async fn refresh_turn_boundary_with_inbox(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
    inbox: Option<&Arc<dyn SessionInboxPort>>,
) -> TurnBoundaryRefresh {
    refresh_turn_boundary_with_inbox_for_run(session, storage, persistence, inbox, None).await
}

pub(crate) async fn refresh_turn_boundary_with_inbox_for_run(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
    inbox: Option<&Arc<dyn SessionInboxPort>>,
    active_run_id: Option<&str>,
) -> TurnBoundaryRefresh {
    refresh_turn_boundary_inner(session, storage, persistence, inbox, active_run_id, None).await
}

pub(crate) async fn refresh_turn_boundary_with_observation(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
    inbox: Option<&Arc<dyn SessionInboxPort>>,
    active_run_id: Option<&str>,
    execution_id: &str,
) -> (
    TurnBoundaryRefresh,
    crate::runtime::managers::lifecycle::InputObservation,
) {
    let mut observation = crate::runtime::managers::lifecycle::InputObservation::default();
    let refresh = refresh_turn_boundary_inner(
        session,
        storage,
        persistence,
        inbox,
        active_run_id,
        Some((execution_id, &mut observation)),
    )
    .await;
    (refresh, observation)
}

async fn refresh_turn_boundary_inner(
    session: &mut Session,
    storage: Option<&Arc<dyn bamboo_agent_core::storage::Storage>>,
    persistence: Option<&Arc<dyn bamboo_domain::RuntimeSessionPersistence>>,
    inbox: Option<&Arc<dyn SessionInboxPort>>,
    active_run_id: Option<&str>,
    capture: Option<(
        &str,
        &mut crate::runtime::managers::lifecycle::InputObservation,
    )>,
) -> TurnBoundaryRefresh {
    let mut read_complete = true;
    let latest = match storage {
        Some(storage) => match storage.load_session(&session.id).await {
            Ok(latest) => latest,
            Err(error) => {
                tracing::warn!(
                    session_id = %session.id,
                    %error,
                    "turn-boundary session refresh failed"
                );
                read_complete = false;
                None
            }
        },
        None => None,
    };
    if let Err(error) = check_conversation_readback(session, latest.as_ref()) {
        return TurnBoundaryRefresh {
            admission_error: Some(error.to_string()),
            ..Default::default()
        };
    }

    // A disk copy with no runtime state carries no authoritative permission
    // mode — report `None` (unknown) so the caller leaves the live posture
    // untouched rather than force-disabling a legitimately permissive run.
    // #540/#770.
    let disk_permission_posture = latest
        .as_ref()
        .and_then(|latest| {
            latest
                .agent_runtime_state
                .as_ref()
                .map(|state| (latest, state.effective_permission_mode()))
        })
        .and_then(|(latest, disk_mode)| {
            let current_mode = session
                .agent_runtime_state
                .as_ref()
                .map(|state| state.effective_permission_mode())
                .unwrap_or_default();
            bamboo_domain::fresher_disk_permission_audit(
                current_mode,
                &session.metadata,
                disk_mode,
                &latest.metadata,
            )
            .map(|audit| (disk_mode, audit))
        });
    let disk_permission_mode = disk_permission_posture
        .as_ref()
        .map(|(disk_mode, _)| *disk_mode);

    if let Some(latest) = latest.as_ref() {
        // Keep the live snapshot's bounded audit record in the same revision as
        // the typed mode returned below. Runtime persistence also adopts these
        // keys under its session lock, so both the current round and any later
        // checkpoint observe one coherent permission transition.
        if let Some((_, audit)) = disk_permission_posture.as_ref() {
            audit.write_to(&mut session.metadata);
        }
        // A previous activation may have checkpointed and acked the claim
        // before this live snapshot was loaded/refreshed. Carry its durable
        // cursor forward so finalization never mistakes an admitted duplicate
        // for work requiring a successor activation.
        bamboo_domain::merge_session_inbox_admission(session, latest);
    }

    if let (Some(inbox), Some(messages)) = (
        inbox,
        latest
            .as_ref()
            .and_then(|latest| latest.pending_injected_messages()),
    ) {
        let migration =
            migrate_legacy_pending_messages(&session.id, &messages, inbox, persistence).await;
        if let Some(generation) = migration.highest_generation {
            // Migration durably authorized this prefix before it was allowed
            // to CAS-clear the compatibility source. Carry the generation on
            // the live snapshot to the owning entry point's terminal
            // handshake if admission below cannot checkpoint it.
            session.session_inbox_admission_mut().observe(generation);
        }
        // The coordinated CAS cleared the latest durable source, but this
        // running snapshot may still carry the same compatibility queue. Clear
        // that exact stale copy before the inbox checkpoint, otherwise it would
        // resurrect the source queue in session.json/runtime sidecar.
        if migration.source_cleared
            && session.pending_injected_messages().as_deref() == Some(messages.as_slice())
        {
            session.clear_pending_injected_messages();
        }
    }

    if let Some(inbox) = inbox {
        let admission = admit_session_inbox(session, inbox, persistence, active_run_id).await;
        if let Some((execution_id, observation)) = capture {
            if read_complete
                && admission.observation_complete
                && admission.admission_error.is_none()
            {
                *observation = crate::runtime::managers::lifecycle::InputObservation::projected(
                    project_new_committed_inputs(
                        &session.id,
                        execution_id,
                        &admission.committed_messages,
                    ),
                );
            }
        }
        return TurnBoundaryRefresh {
            merged: admission.merged,
            committed_messages: admission.committed_messages,
            admission_error: admission.admission_error,
            disk_permission_mode,
        };
    }

    let Some(latest) = latest else {
        return TurnBoundaryRefresh {
            merged: 0,
            committed_messages: Vec::new(),
            admission_error: None,
            disk_permission_mode,
        };
    };

    // Read via the typed accessor (prefers `runtime_metadata`, falls back to the
    // legacy `pending_injected_messages` JSON string; defensive on malformed).
    let Some(messages) = latest.pending_injected_messages() else {
        if let Some((execution_id, observation)) =
            capture.filter(|_| super::session_setup::legacy_instruction::sdk_runtime_active())
        {
            let pending_absent = !latest.metadata.contains_key("pending_injected_messages")
                && latest
                    .runtime_metadata
                    .as_ref()
                    .is_none_or(|metadata| metadata.pending_injected_messages.is_none());
            let current_users = session
                .messages
                .iter()
                .filter(|message| message.role == bamboo_agent_core::Role::User);
            let durable_users = latest
                .messages
                .iter()
                .filter(|message| message.role == bamboo_agent_core::Role::User);
            let mut current_users = current_users;
            let mut durable_users = durable_users;
            let same_inputs = loop {
                match (current_users.next(), durable_users.next()) {
                    (None, None) => break true,
                    (Some(current), Some(durable))
                        if crate::runtime::config::sdk_message_digest(current)
                            == crate::runtime::config::sdk_message_digest(durable) => {}
                    _ => break false,
                }
            };
            if read_complete && pending_absent && same_inputs {
                *observation = crate::runtime::managers::lifecycle::InputObservation::projected(
                    project_input_request_batch(&session.id, execution_id, &[]),
                );
            }
        }
        return TurnBoundaryRefresh {
            merged: 0,
            committed_messages: Vec::new(),
            admission_error: None,
            disk_permission_mode,
        };
    };

    let mut merged = 0usize;
    let mut appended_messages = Vec::new();
    for msg in messages {
        if let Some(content) = msg.get("content").and_then(|v| v.as_str()) {
            let message = bamboo_agent_core::Message::user(content.to_string());
            appended_messages.push(message.clone());
            session.add_message(message);
            merged += 1;
        }
    }

    if merged > 0 {
        // Clear on both planes (typed field + legacy string mirror).
        session.clear_pending_injected_messages();
        session.updated_at = chrono::Utc::now();

        let mut saved = false;
        if let Some(persistence) = persistence {
            match persistence.save_runtime_session(session).await {
                Ok(()) => saved = true,
                Err(error) => tracing::warn!(
                    "[{}] Failed to persist pending injected message cleanup: {}",
                    session.id,
                    error
                ),
            }
        }

        tracing::info!(
            "[{}] Merged {} injected message(s) from queued send_message at turn boundary",
            session.id,
            merged
        );

        // When the cleanup save ran, the adopting `save_runtime_session` stamped
        // the freshest on-disk bypass onto `session.agent_runtime_state` (so a
        // `PATCH` that landed DURING the merge is already reflected there) — read
        // it back from memory instead of a third full-session deserialization on
        // this steering hot path. Without a save, `session` holds no disk-fresh
        // value, so keep the pre-merge snapshot. #540.
        let disk_permission_mode = if saved {
            session
                .agent_runtime_state
                .as_ref()
                .map(|rs| rs.effective_permission_mode())
                .or(disk_permission_mode)
        } else {
            disk_permission_mode
        };
        return TurnBoundaryRefresh {
            merged,
            committed_messages: if saved { appended_messages } else { Vec::new() },
            admission_error: None,
            disk_permission_mode,
        };
    }

    TurnBoundaryRefresh {
        merged,
        committed_messages: Vec::new(),
        admission_error: None,
        disk_permission_mode,
    }
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn ql_overflow_old_wrapper_and_rich_prelude_preserve_actual_outputs_and_ack() {
        let mut snapshots = Vec::new();
        for rich in [false, true] {
            let (_home, store, locked, inbox, mut session) =
                durable_inbox_fixture("ql-overflow-parity").await;
            let mut system = Message::system("fixed provider system");
            system.id = "fixed-system-id".into();
            system.created_at = chrono::DateTime::from_timestamp(1700000000, 0).unwrap();
            session.add_message(system);
            store.save_session(&session).await.unwrap();
            let storage: Arc<dyn Storage> = store;
            let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
            for ordinal in 0..40 {
                deliver_interrupt_eligible(&inbox, &ql_envelope(&session.id, ordinal, Some(7000)))
                    .await;
            }
            let config = crate::runtime::config::AgentLoopConfig {
                storage: Some(storage.clone()),
                persistence: Some(persistence),
                session_inbox: Some(inbox.clone()),
                prompt_memory_flags: crate::runtime::config::PromptMemoryFlags {
                    project_prompt_injection: false,
                    relevant_recall: false,
                    relevant_recall_rerank: false,
                    project_first_dream: false,
                    ledger_agenda: false,
                },
                ..Default::default()
            };
            let mut runtime = AgentRuntimeState::new("actual-parity-run");
            let (tx, mut rx) = tokio::sync::mpsc::channel(128);
            let cancel = tokio_util::sync::CancellationToken::new();
            let memory = if rich {
                let (memory, observation) =
                    crate::runtime::runner::round_prelude::refresh_round_boundary_with_observation(
                        &mut session,
                        &mut runtime,
                        &config,
                        Some(&tx),
                        &cancel,
                        None,
                        None,
                        "actual-parity-run",
                    )
                    .await
                    .unwrap();
                assert!(
                    observation.is_unavailable(),
                    "whole overflow changes only optional data"
                );
                memory
            } else {
                crate::runtime::runner::round_prelude::refresh_round_boundary_and_prompt_context(
                    &mut session,
                    &mut runtime,
                    &config,
                    Some(&tx),
                    &cancel,
                    None,
                    None,
                )
                .await
                .unwrap()
            };
            let provider = AckBoundaryProvider(AtomicUsize::new(0));
            let stream = bamboo_llm::LLMProvider::chat_stream(
                &provider,
                &session.messages,
                &[],
                None,
                "model",
            )
            .await
            .unwrap();
            drop(stream);
            assert_eq!(provider.0.load(Ordering::SeqCst), 1);
            let mut events = Vec::new();
            while let Ok(event) = rx.try_recv() {
                events.push(serde_json::to_value(event).unwrap());
            }
            assert_eq!(
                events.len(),
                40,
                "all original committed prefix events remain visible"
            );
            for ordinal in 0..40 {
                assert!(inbox
                    .was_admitted(
                        &session.id,
                        &SessionMessageId::parse(format!("ql-{ordinal}")).unwrap()
                    )
                    .await
                    .unwrap());
            }
            let cold = storage.load_session(&session.id).await.unwrap().unwrap();
            assert_eq!(
                cold.messages
                    .iter()
                    .filter(|m| m.id.starts_with("ql-"))
                    .count(),
                40
            );
            let backlog = inbox.inspect(&session.id).await.unwrap();
            assert_eq!(backlog.pending + backlog.claimed, 0);
            snapshots.push((
                memory,
                serde_json::to_value(&session.messages).unwrap(),
                events,
                runtime.effective_permission_mode(),
                session.metadata.clone(),
            ));
        }
        assert_eq!(
            snapshots[0], snapshots[1],
            "provider input, memory refresh, events and posture remain identical"
        );
    }

    #[tokio::test]
    async fn sdk_no_inbox_no_new_checks_user_inputs_only_and_unknown_storage_clears() {
        use crate::runtime::runner::session_setup::legacy_instruction::scope_sdk_runtime;
        use bamboo_domain::RuntimeSessionPersistence;
        let (_home, store, locked, _inbox, mut session) = durable_inbox_fixture("sdk-no-new").await;
        session.add_message(Message::user("accepted SDK input"));
        locked
            .checkpoint_runtime_session(&mut session)
            .await
            .unwrap();
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        session.add_message(Message::system("normal assembled system"));
        session.add_message(Message::assistant("normal output", None));
        let (_, generic) = refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            None,
            None,
            "sdk-actual",
        )
        .await;
        assert!(
            generic.is_unavailable(),
            "generic history never establishes SDK currentness"
        );
        let (_, same) = scope_sdk_runtime(refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            None,
            None,
            "sdk-actual",
        ))
        .await;
        assert!(same.is_successful_no_new_input());
        assert!(
            same.new_inputs().is_none(),
            "NoNew never manufactures a User or Source"
        );
        session.add_message(Message::user("unsaved input"));
        let (_, changed) = scope_sdk_runtime(refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            None,
            None,
            "sdk-actual",
        ))
        .await;
        assert!(changed.is_unavailable());
        let (_, missing) = scope_sdk_runtime(refresh_turn_boundary_with_observation(
            &mut session,
            None,
            Some(&persistence),
            None,
            None,
            "sdk-actual",
        ))
        .await;
        assert!(missing.is_unavailable());
    }

    fn ql_envelope(id: &str, ordinal: usize, bytes: Option<usize>) -> SessionMessageEnvelope {
        let mut envelope = SessionMessageEnvelope::user_input(id, "unchanged provider text");
        envelope.id = SessionMessageId::parse(format!("ql-{ordinal}")).unwrap();
        envelope.created_at =
            chrono::DateTime::from_timestamp(1700000000 + ordinal as i64, 0).unwrap();
        if let (Some(bytes), SessionMessageBody::Content(content)) = (bytes, &mut envelope.body) {
            content.skill_request = Some(bamboo_domain::SessionSkillRequest {
                mode: Some("exact-mode".into()),
                selections: vec![bamboo_domain::SessionSkillSelection {
                    id: format!("selection-{ordinal}"),
                    source: "user".into(),
                    revision: u64::MAX,
                    args: serde_json::json!({"payload":"x".repeat(bytes), "float": 1.125, "null":null}),
                }],
            });
        }
        envelope
    }

    #[test]
    fn ql_raw_projection_matches_accepted_qb_cost_and_exact_numeric_data() {
        use crate::runtime::managers::lifecycle::InputRequestProjection;
        for root in [false, true] {
            for request in [None, Some(0), Some(7000)] {
                let envelope = ql_envelope("ql-raw", 1, request);
                let envelope = if root {
                    envelope.with_root_chat_prompt("system".into()).unwrap()
                } else {
                    envelope
                };
                let skill_request = match &envelope.body {
                    SessionMessageBody::Content(content) => content.skill_request.as_ref(),
                    SessionMessageBody::RuntimeInstruction(body) => {
                        body.content.as_ref().unwrap().skill_request.as_ref()
                    }
                    SessionMessageBody::ChildOutcome(_) => None,
                };
                let records = [BorrowedInputRequestRecord {
                    input_id: envelope.id.as_str(),
                    source: &envelope.source,
                    kind: envelope.kind,
                    wrapper: root.then_some("root_chat_turn_v1"),
                    created_at: envelope.created_at,
                    request: skill_request,
                }];
                let expected = project_input_request_batch("ql-raw", "actual-execution", &records);
                let actual = project_new_committed_inputs(
                    "ql-raw",
                    "actual-execution",
                    &[envelope.to_provider_message().unwrap()],
                );
                assert_eq!(actual, expected);
                let InputRequestProjection::Available(batch) = actual else {
                    panic!("valid fit")
                };
                assert_eq!(batch.records()[0].request.as_ref(), skill_request);
            }
        }
    }

    #[test]
    fn ql_raw_projection_normalizes_null_mode_and_missing_args_without_dropping_data() {
        let envelope = ql_envelope("ql-null", 0, Some(0));
        let mut message = envelope.to_provider_message().unwrap();
        let proof = &mut message.metadata.as_mut().unwrap()["session_message"];
        let request = &mut proof["body"]["skill_request"];
        request["mode"] = serde_json::Value::Null;
        request["selections"][0]
            .as_object_mut()
            .unwrap()
            .remove("args");
        let expected = bamboo_domain::SessionSkillRequest {
            mode: None,
            selections: vec![bamboo_domain::SessionSkillSelection {
                id: "selection-0".into(),
                source: "user".into(),
                revision: u64::MAX,
                args: serde_json::Value::Null,
            }],
        };
        let records = [BorrowedInputRequestRecord {
            input_id: envelope.id.as_str(),
            source: &envelope.source,
            kind: envelope.kind,
            wrapper: None,
            created_at: envelope.created_at,
            request: Some(&expected),
        }];
        assert_eq!(
            project_new_committed_inputs("ql-null", "e", &[message]),
            project_input_request_batch("ql-null", "e", &records)
        );
    }

    #[test]
    fn ql_raw_projection_rejects_unknown_small_deep_and_wide_programmatic_data() {
        use crate::runtime::managers::lifecycle::InputRequestProjection::Unavailable;
        let message = ql_envelope("ql-shape", 0, Some(0))
            .to_provider_message()
            .unwrap();
        let mut deep = serde_json::Value::Null;
        for _ in 0..65 {
            deep = serde_json::json!([deep]);
        }
        for args in [
            deep,
            serde_json::json!((0..8192).map(|_| 0).collect::<Vec<_>>()),
        ] {
            let mut invalid = message.clone();
            invalid.metadata.as_mut().unwrap()["session_message"]["body"]["skill_request"]
                ["selections"][0]["args"] = args;
            assert!(matches!(
                project_new_committed_inputs("ql-shape", "e", &[invalid]),
                Unavailable(_)
            ));
        }
        let mut invalid = message.clone();
        invalid.metadata.as_mut().unwrap()["session_message"]["body"]["skill_request"]["extra"] =
            1.into();
        assert!(matches!(
            project_new_committed_inputs("ql-shape", "e", &[invalid]),
            Unavailable(_)
        ));
        let mut invalid = message;
        invalid.metadata.as_mut().unwrap()["session_message"]["id"] = "wrong-id".into();
        assert!(matches!(
            project_new_committed_inputs("ql-shape", "e", &[invalid]),
            Unavailable(_)
        ));
        assert!(matches!(
            project_new_committed_inputs("ql-shape", "e", &[Message::user("old native")]),
            Unavailable(_)
        ));
    }

    #[tokio::test]
    async fn ql_real_new_order_none_overflow_nonew_and_fitting_restore() {
        let (_home, store, locked, inbox, mut session) = durable_inbox_fixture("ql-sequence").await;
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let mut current = None;
        for (start, count, request, fitting) in [
            (0, 2, Some(7), true),
            (2, 1, None, true),
            (3, 40, Some(7000), false),
            (43, 0, None, false),
            (43, 1, Some(9), true),
        ] {
            for ordinal in start..start + count {
                deliver_interrupt_eligible(&inbox, &ql_envelope(&session.id, ordinal, request))
                    .await;
            }
            let (refresh, observation) = refresh_turn_boundary_with_observation(
                &mut session,
                Some(&storage),
                Some(&persistence),
                Some(&inbox),
                None,
                "actual-sequence-run",
            )
            .await;
            assert_eq!(refresh.merged, count);
            assert_eq!(refresh.committed_messages.len(), count);
            assert!(refresh.admission_error.is_none());
            if count == 0 {
                assert!(observation.is_successful_no_new_input());
            }
            if count == 40 {
                assert!(observation.is_unavailable());
            }
            let session_id = session.id.clone();
            observation.update_current(&mut current, &session_id, "actual-sequence-run");
            assert_eq!(current.is_some(), fitting);
            if let Some(batch) = &current {
                assert_eq!(
                    batch
                        .records()
                        .iter()
                        .map(|r| r.input_id.as_str())
                        .collect::<Vec<_>>(),
                    (start..start + count)
                        .map(|i| format!("ql-{i}"))
                        .collect::<Vec<_>>()
                );
                assert_eq!(batch.records()[0].request.is_some(), request.is_some());
                assert_eq!(batch.execution_id(), "actual-sequence-run");
            }
            let backlog = inbox.inspect(&session_id).await.unwrap();
            assert_eq!(backlog.pending + backlog.claimed, 0);
        }
    }

    #[tokio::test]
    async fn ql_original_checkpoint_failure_is_unavailable_and_cold_retry_is_new_once() {
        let (_home, store, locked, inbox, mut session) =
            durable_inbox_fixture("ql-checkpoint-failure").await;
        let storage: Arc<dyn Storage> = store;
        let faulted = Arc::new(FaultingPersistence {
            inner: locked,
            fail_checkpoint: std::sync::atomic::AtomicBool::new(true),
        });
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = faulted.clone();
        let envelope = ql_envelope(&session.id, 0, Some(9));
        deliver_interrupt_eligible(&inbox, &envelope).await;
        let (refresh, observation) = refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            None,
            "e",
        )
        .await;
        assert!(
            refresh.admission_error.is_none(),
            "preserve original non-error checkpoint branch"
        );
        assert_eq!(refresh.merged, 0);
        assert!(refresh.committed_messages.is_empty());
        assert!(observation.is_unavailable());
        assert!(!session
            .messages
            .iter()
            .any(|m| m.id == envelope.id.as_str()));
        assert!(!inbox.was_admitted(&session.id, &envelope.id).await.unwrap());
        faulted.fail_checkpoint.store(false, Ordering::SeqCst);
        session = storage.load_session(&session.id).await.unwrap().unwrap();
        let (refresh, observation) = refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            None,
            "actual-cold-retry",
        )
        .await;
        assert_eq!(refresh.merged, 1);
        assert_eq!(
            observation.new_inputs().unwrap().records()[0].input_id,
            envelope.id.as_str()
        );
        let (_, observation) = refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            None,
            "actual-cold-retry",
        )
        .await;
        assert!(observation.is_successful_no_new_input());
    }

    #[tokio::test]
    async fn ql_unresolved_ack_preserves_prefix_events_but_never_new_and_recovery_is_nonew() {
        for permanent in [false, true] {
            let (_home, store, locked, real, mut session) =
                durable_inbox_fixture("ql-ack-failure").await;
            let storage: Arc<dyn Storage> = store;
            let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
            let inbox: Arc<dyn SessionInboxPort> = Arc::new(AckAfterPersistErrorInbox {
                inner: real.clone(),
                fail_before_once: std::sync::atomic::AtomicBool::new(!permanent),
                fail_after_once: std::sync::atomic::AtomicBool::new(permanent),
            });
            let envelope = ql_envelope(&session.id, 0, Some(9));
            deliver_interrupt_eligible(&inbox, &envelope).await;
            let (refresh, observation) = refresh_turn_boundary_with_observation(
                &mut session,
                Some(&storage),
                Some(&persistence),
                Some(&inbox),
                None,
                "e",
            )
            .await;
            assert_eq!(
                refresh.admission_error.as_deref(),
                Some(INBOX_ACK_UNRESOLVED)
            );
            assert_eq!(
                refresh.committed_messages.len(),
                1,
                "retain original pre-ACK durable prefix"
            );
            assert!(observation.is_unavailable());
            let mut cold = storage.load_session(&session.id).await.unwrap().unwrap();
            let (refresh, observation) = refresh_turn_boundary_with_observation(
                &mut cold,
                Some(&storage),
                Some(&persistence),
                Some(&inbox),
                None,
                "cold-new-run",
            )
            .await;
            assert_eq!(refresh.merged, 0);
            assert!(refresh.committed_messages.is_empty());
            assert!(observation.is_successful_no_new_input());
            assert_eq!(
                cold.messages
                    .iter()
                    .filter(|m| m.id == envelope.id.as_str())
                    .count(),
                1
            );
            assert_eq!(real.inspect(&session.id).await.unwrap().claimed, 0);
        }
    }

    #[tokio::test]
    async fn ql_owned_root_new_and_recovered_are_distinguished_after_exact_ack() {
        use bamboo_domain::RuntimeSessionPersistence;
        for recovered in [false, true] {
            let (_home, store, locked, inbox, mut root) =
                durable_inbox_fixture("ql-owned-root").await;
            let envelope = ql_envelope(&root.id, 0, Some(17))
                .with_root_chat_prompt("Root system".into())
                .unwrap();
            if recovered {
                root.add_message(envelope.to_provider_message().unwrap());
                store.save_session(&root).await.unwrap();
            }
            let repo = crate::SessionRepository::new(Arc::default(), store.clone(), locked)
                .with_root_actor_directory(store.clone());
            let binding = repo
                .bind_root_actor_execution(&root, "actual-owned-root-run")
                .await
                .unwrap()
                .unwrap();
            let storage: Arc<dyn Storage> = store;
            deliver_interrupt_eligible(&inbox, &envelope).await;
            let (refresh, observation) = refresh_turn_boundary_with_observation(
                &mut root,
                Some(&storage),
                Some(&binding.persistence),
                Some(&inbox),
                None,
                "actual-owned-root-run",
            )
            .await;
            assert!(refresh.admission_error.is_none());
            assert_eq!(refresh.merged, usize::from(!recovered));
            assert_eq!(observation.is_successful_no_new_input(), recovered);
            if !recovered {
                let batch = observation
                    .new_inputs()
                    .expect("actual owned Root New must project");
                assert_eq!(batch.records().len(), 1);
                let record = &batch.records()[0];
                assert_eq!(record.input_id, envelope.id.as_str());
                assert_eq!(
                    record.source,
                    SessionMessageSource::Runtime {
                        subsystem: "chat".into()
                    }
                );
                assert_eq!(record.kind, SessionMessageKind::RuntimeInstruction);
                assert_eq!(record.wrapper.as_deref(), Some("root_chat_turn_v1"));
                assert_eq!(record.created_at, envelope.created_at);
                assert_eq!(
                    record.request.as_ref().unwrap().selections[0].revision,
                    u64::MAX
                );
            }
            assert!(inbox.was_admitted(&root.id, &envelope.id).await.unwrap());
            assert_eq!(inbox.inspect(&root.id).await.unwrap().pending, 0);
            assert_eq!(
                root.messages
                    .iter()
                    .filter(|m| m.id == envelope.id.as_str())
                    .count(),
                1
            );
        }
    }

    #[tokio::test]
    async fn ql_new_peer_user_presentation_is_unavailable_without_stale_fallback() {
        let (_home, store, locked, inbox, mut session) = durable_inbox_fixture("ql-peer").await;
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let user = ql_envelope(&session.id, 0, Some(8));
        deliver_interrupt_eligible(&inbox, &user).await;
        let (_, observation) = refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            None,
            "e",
        )
        .await;
        let mut current = None;
        observation.update_current(&mut current, &session.id, "e");
        assert!(current.is_some());
        let mut peer = ql_envelope(&session.id, 1, None);
        peer.source = SessionMessageSource::Session {
            session_id: "real-peer".into(),
        };
        peer.kind = SessionMessageKind::PeerMessage;
        assert_eq!(
            peer.to_provider_message().unwrap().role,
            bamboo_domain::Role::User
        );
        deliver_interrupt_eligible(&inbox, &peer).await;
        let (refresh, observation) = refresh_turn_boundary_with_observation(
            &mut session,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            None,
            "e",
        )
        .await;
        assert_eq!(refresh.merged, 1);
        assert!(observation.is_unavailable());
        observation.update_current(&mut current, &session.id, "e");
        assert!(current.is_none());
        assert!(inbox.was_admitted(&session.id, &peer.id).await.unwrap());
    }

    use super::*;
    use bamboo_agent_core::storage::Storage;
    use bamboo_domain::{
        AgentStatusState, SessionActivationDisposition, SessionActivationError,
        SessionActivationPort,
    };
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::sync::RwLock;

    fn test_session() -> Session {
        Session::new("test-session", "test-model")
    }

    #[test]
    fn read_from_structured_field() {
        let mut session = test_session();
        let mut state = AgentRuntimeState::new("run-1");
        state.status = AgentStatusState::Running;
        session.agent_runtime_state = Some(state.clone());

        let read = read_runtime_state(&session).unwrap();
        assert_eq!(read.status, AgentStatusState::Running);
        assert_eq!(read.run_id, "run-1");
    }

    #[test]
    fn read_from_metadata_fallback() {
        let mut session = test_session();
        let state = AgentRuntimeState::new("run-2");
        session.metadata.insert(
            METADATA_KEY.to_string(),
            serde_json::to_string(&state).unwrap(),
        );

        let read = read_runtime_state(&session).unwrap();
        assert_eq!(read.run_id, "run-2");
    }

    #[test]
    fn structured_field_takes_priority() {
        let mut session = test_session();
        let mut state1 = AgentRuntimeState::new("from-field");
        state1.status = AgentStatusState::Running;
        session.agent_runtime_state = Some(state1);

        let mut state2 = AgentRuntimeState::new("from-metadata");
        state2.status = AgentStatusState::Completed;
        session.metadata.insert(
            METADATA_KEY.to_string(),
            serde_json::to_string(&state2).unwrap(),
        );

        let read = read_runtime_state(&session).unwrap();
        assert_eq!(read.run_id, "from-field");
        assert_eq!(read.status, AgentStatusState::Running);
    }

    #[test]
    fn read_returns_none_when_empty() {
        let session = test_session();
        assert!(read_runtime_state(&session).is_none());
    }

    #[test]
    fn write_only_structured_field() {
        let mut session = test_session();
        let state = AgentRuntimeState::new("run-3");

        write_runtime_state(&mut session, &state);

        assert!(session.agent_runtime_state.is_some());
        // Legacy metadata mirror is no longer written
        assert!(!session.metadata.contains_key(METADATA_KEY));
        assert_eq!(
            session.agent_runtime_state.as_ref().unwrap().run_id,
            "run-3"
        );
    }

    #[test]
    fn sync_extracts_model_name() {
        let mut session = test_session();
        session.model = "gpt-4o".to_string();
        session.metadata.insert(
            "responses.previous_response_id".to_string(),
            "resp-123".to_string(),
        );

        let mut state = AgentRuntimeState::new("run-4");
        sync_from_metadata(&session, &mut state);

        assert_eq!(state.llm.model_name, Some("gpt-4o".to_string()));
        assert_eq!(
            state.llm.responses_previous_id,
            Some("resp-123".to_string())
        );
    }

    // --- Pending injected message tests ---

    #[derive(Default)]
    struct TestStorage {
        sessions: RwLock<HashMap<String, Session>>,
    }

    #[async_trait::async_trait]
    impl Storage for TestStorage {
        async fn save_session(&self, session: &Session) -> std::io::Result<()> {
            self.sessions
                .write()
                .await
                .insert(session.id.clone(), session.clone());
            Ok(())
        }

        async fn load_session(&self, session_id: &str) -> std::io::Result<Option<Session>> {
            Ok(self.sessions.read().await.get(session_id).cloned())
        }

        async fn delete_session(&self, session_id: &str) -> std::io::Result<bool> {
            Ok(self.sessions.write().await.remove(session_id).is_some())
        }
    }

    #[tokio::test]
    async fn tool_boundary_permission_refresh_preserves_legacy_same_mode_without_audit() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());
        let mut persisted = Session::new("legacy-same-mode", "model");
        persisted.agent_runtime_state = Some(AgentRuntimeState::new("run"));
        persisted.add_message(bamboo_agent_core::Message::user(
            "must stay on disk until the next turn boundary",
        ));
        storage.save_session(&persisted).await.unwrap();

        let mut running = persisted.clone();
        running.messages.clear();
        let mut runtime_state = AgentRuntimeState::new("run");
        refresh_tool_boundary_authorities(&mut running, &mut runtime_state, Some(&storage))
            .await
            .expect("same-mode legacy posture is not a transition to adopt");

        assert_eq!(
            runtime_state.effective_permission_mode(),
            bamboo_domain::SessionPermissionMode::Default
        );
        assert!(
            running.messages.is_empty(),
            "tool-boundary refresh must not merge durable messages mid-round"
        );
        assert!(bamboo_domain::PermissionAuditSnapshot::from_metadata(&running.metadata).is_none());
    }

    #[tokio::test]
    async fn first_unpersisted_root_is_published_before_provider_round() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());
        let mut fresh = Session::new("fresh-sdk-root", "model");
        fresh.agent_runtime_state = Some(AgentRuntimeState::new("run"));
        ensure_initial_root_tool_authority(&mut fresh, Some(&storage))
            .await
            .expect("new SDK Root is durably published first");
        refresh_round_root_tool_authority(&mut fresh, Some(&storage))
            .await
            .expect("first provider round reads the published Root");
        assert!(fresh.allows_model_tool_execution("Bash"));
        assert!(storage
            .load_runtime_control_plane(&fresh.id)
            .await
            .unwrap()
            .is_some());

        let mut runtime_state = AgentRuntimeState::new("run");
        refresh_tool_boundary_authorities(&mut fresh, &mut runtime_state, Some(&storage))
            .await
            .expect("the saved control plane admits ordinary execution");

        let mut selected = Session::new("selected-sdk-root", "model");
        selected.set_root_orchestration_only(true).unwrap();
        assert!(
            refresh_round_root_tool_authority(&mut selected, Some(&storage))
                .await
                .is_err()
        );

        let mut resumed = Session::new("resumed-sdk-root", "model");
        resumed.add_message(Message::assistant("prior round", None));
        assert!(
            refresh_round_root_tool_authority(&mut resumed, Some(&storage))
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn revoked_early_root_cannot_be_recreated_by_initial_runtime_publication() {
        let home = tempfile::tempdir().unwrap();
        let store = Arc::new(
            bamboo_storage::SessionStoreV2::new(home.path().join("sessions"))
                .await
                .unwrap(),
        );
        let stale = Session::new("revoked-early-root", "model");
        store.save_session(&stale).await.unwrap();
        assert!(store.delete_session(&stale.id).await.unwrap());
        let storage: Arc<dyn Storage> = store;
        let mut running = stale;

        let error = ensure_initial_root_tool_authority(&mut running, Some(&storage))
            .await
            .expect_err("ordinary save must not revive a deleted Root lifetime");
        assert!(error.to_string().contains("failed closed"));
        assert!(storage
            .load_runtime_control_plane(&running.id)
            .await
            .unwrap()
            .is_none());
        assert!(
            refresh_round_root_tool_authority(&mut running, Some(&storage))
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn old_sdk_root_cannot_adopt_a_recreated_root_lifetime() {
        let home = tempfile::tempdir().unwrap();
        let store = Arc::new(
            bamboo_storage::SessionStoreV2::new(home.path().join("sessions"))
                .await
                .unwrap(),
        );
        let mut old = Session::new("recreated-sdk-root", "model");
        old.agent_runtime_state = Some(AgentRuntimeState::new("old-run"));
        store.save_session(&old).await.unwrap();
        assert!(store.delete_session(&old.id).await.unwrap());

        let mut replacement = store
            .recreate_root_session(&old.id, "new-model")
            .await
            .unwrap();
        assert_ne!(replacement.created_at, old.created_at);
        replacement.agent_runtime_state = Some(AgentRuntimeState::new("new-run"));
        store.save_session(&replacement).await.unwrap();
        let storage: Arc<dyn Storage> = store;

        let old_birth = old.created_at;
        let mut running = old;
        let error = ensure_initial_root_tool_authority(&mut running, Some(&storage))
            .await
            .expect_err("pre-provider proof must reject the old SDK snapshot");
        assert!(error.to_string().contains("Root tool authority"));
        assert!(
            refresh_round_root_tool_authority(&mut running, Some(&storage))
                .await
                .is_err(),
            "subsequent catalog refresh must reject the same stale lifetime"
        );
        let mut runtime_state = AgentRuntimeState::new("old-run");
        let error =
            refresh_tool_boundary_authorities(&mut running, &mut runtime_state, Some(&storage))
                .await
                .expect_err("pre-dispatch proof must reject the old SDK snapshot");
        assert!(error.to_string().contains("Root tool authority"));
        assert_eq!(running.created_at, old_birth);
        assert_eq!(runtime_state.run_id, "old-run");
    }

    #[tokio::test]
    async fn active_supervisor_adopts_mode_before_next_provider_catalog() {
        let home = tempfile::tempdir().unwrap();
        let store = std::sync::Arc::new(
            bamboo_storage::SessionStoreV2::new(home.path().join("sessions"))
                .await
                .unwrap(),
        );
        store
            .get_or_create_default_supervisor("model")
            .await
            .unwrap();
        let id = bamboo_domain::DEFAULT_SUPERVISOR_SESSION_ID;
        let mut running = store.load_root_authority(id).await.unwrap().unwrap();
        assert!(!running.root_orchestration_only_enabled());
        assert!(running.model_orchestration_only_enabled());
        assert!(!running.allows_model_tool_execution("Bash"));
        assert!(running.allows_model_tool_execution("SubAgent"));
        let operation = bamboo_domain::RootModeOperationRequest {
            session_id: id.to_string(),
            operation_id: format!("0:{}", uuid::Uuid::new_v4()),
            birth_token: running.root_mode_birth_token(),
            expected_epoch: 0,
            requested_enabled: true,
            action: bamboo_domain::RootModeOperationAction::Select,
        };
        assert!(matches!(
            store.root_mode_operation(&operation).await.unwrap(),
            bamboo_domain::RootModeOperationDecision::Terminal(_)
        ));

        let storage: Arc<dyn Storage> = store;
        refresh_round_root_tool_authority(&mut running, Some(&storage))
            .await
            .expect("strict Supervisor management proof remains valid");
        assert!(running.root_orchestration_only_enabled());
        assert!(!running.allows_model_tool_execution("Bash"));
        assert!(running.allows_model_tool_execution("SubAgent"));
        assert_eq!(running.root_mode_transition_epoch, 1);
        assert_eq!(running.root_mode_operations.len(), 1);
        running.add_message(Message::assistant("Supervisor result", None));
        let persistence =
            std::sync::Arc::new(bamboo_storage::LockedSessionStore::new(storage.clone()));
        let repository =
            crate::SessionRepository::new(std::sync::Arc::default(), storage.clone(), persistence);
        repository.save(&mut running).await.unwrap();
        let durable = storage.load_session(id).await.unwrap().unwrap();
        assert_eq!(durable.root_mode_transition_epoch, 1);
        assert_eq!(
            durable.messages.last().unwrap().content,
            "Supervisor result"
        );
    }

    #[tokio::test]
    async fn ordinary_root_at_reserved_id_still_refreshes_before_provider() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());
        let mut running = Session::new(bamboo_domain::DEFAULT_SUPERVISOR_SESSION_ID, "model");
        let mut latest = running.clone();
        latest.set_root_orchestration_only(true).unwrap();
        storage.save_session(&latest).await.unwrap();

        refresh_round_root_tool_authority(&mut running, Some(&storage))
            .await
            .expect("ordinary identity at the reserved ID still needs durable proof");
        assert!(running.root_orchestration_only_enabled());
        assert!(!running.allows_model_tool_execution("Bash"));
    }

    struct TestPersistence(Arc<dyn Storage>);

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

    struct FaultingPersistence {
        inner: Arc<bamboo_storage::LockedSessionStore>,
        fail_checkpoint: std::sync::atomic::AtomicBool,
    }

    #[async_trait::async_trait]
    impl bamboo_domain::RuntimeSessionPersistence for FaultingPersistence {
        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
                .load(std::sync::atomic::Ordering::SeqCst)
            {
                return Err(std::io::Error::other("injected 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 AckAfterPersistErrorInbox {
        inner: Arc<dyn SessionInboxPort>,
        fail_before_once: std::sync::atomic::AtomicBool,
        fail_after_once: std::sync::atomic::AtomicBool,
    }

    struct ForcedPermanentReceiptInbox {
        inner: Arc<dyn SessionInboxPort>,
        ack_count: Arc<AtomicUsize>,
    }

    struct FailSecondDeliveryInbox {
        inner: Arc<dyn SessionInboxPort>,
        deliveries: AtomicUsize,
    }

    struct FailActivationInbox {
        inner: Arc<dyn SessionInboxPort>,
        marks: AtomicUsize,
    }

    #[async_trait::async_trait]
    impl SessionInboxPort for FailActivationInbox {
        async fn deliver(
            &self,
            envelope: &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.marks.fetch_add(1, Ordering::SeqCst);
            Err(bamboo_domain::SessionInboxError::Storage(
                "injected activation watermark failure".to_string(),
            ))
        }

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

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

        async fn ack(
            &self,
            target_session_id: &str,
            claim: &bamboo_domain::SessionInboxClaim,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            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_trait::async_trait]
    impl SessionInboxPort for FailSecondDeliveryInbox {
        async fn deliver(
            &self,
            envelope: &SessionMessageEnvelope,
        ) -> Result<bamboo_domain::SessionInboxReceipt, bamboo_domain::SessionInboxError> {
            if self.deliveries.fetch_add(1, Ordering::SeqCst) == 1 {
                return Err(bamboo_domain::SessionInboxError::Storage(
                    "injected second legacy delivery failure".to_string(),
                ));
            }
            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<bamboo_domain::SessionInboxClaim>, bamboo_domain::SessionInboxError>
        {
            self.inner.claim(target_session_id, limit).await
        }

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

        async fn ack(
            &self,
            target_session_id: &str,
            claim: &bamboo_domain::SessionInboxClaim,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            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
        }
    }

    struct ActivationBeforeClearPersistence {
        inner: Arc<bamboo_storage::LockedSessionStore>,
        inbox: Arc<dyn SessionInboxPort>,
        fail_clear_once: std::sync::atomic::AtomicBool,
        clear_calls: AtomicUsize,
    }

    #[async_trait::async_trait]
    impl bamboo_domain::RuntimeSessionPersistence for ActivationBeforeClearPersistence {
        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<()> {
            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
        }

        async fn clear_legacy_pending_messages(
            &self,
            session_id: &str,
            expected: &[serde_json::Value],
        ) -> std::io::Result<bool> {
            let backlog = self
                .inbox
                .inspect(session_id)
                .await
                .map_err(|error| std::io::Error::other(error.to_string()))?;
            if backlog.activation_generation < backlog.generation
                || backlog.interrupt_generation < backlog.generation
            {
                return Err(std::io::Error::other(format!(
                    "legacy source clear attempted before interrupt activation publish: {backlog:?}"
                )));
            }
            self.clear_calls.fetch_add(1, Ordering::SeqCst);
            if self
                .fail_clear_once
                .swap(false, std::sync::atomic::Ordering::SeqCst)
            {
                return Err(std::io::Error::other(
                    "injected crash after enqueue+mark and before source clear",
                ));
            }
            self.inner
                .clear_legacy_pending_messages(session_id, expected)
                .await
        }
    }

    #[async_trait::async_trait]
    impl SessionInboxPort for ForcedPermanentReceiptInbox {
        async fn deliver(
            &self,
            envelope: &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<bamboo_domain::SessionInboxClaim>, bamboo_domain::SessionInboxError>
        {
            self.inner.claim(target_session_id, limit).await
        }

        async fn was_admitted(
            &self,
            _target_session_id: &str,
            _id: &SessionMessageId,
        ) -> Result<bool, bamboo_domain::SessionInboxError> {
            Ok(true)
        }

        async fn ack(
            &self,
            target_session_id: &str,
            claim: &bamboo_domain::SessionInboxClaim,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            self.inner.ack(target_session_id, claim).await?;
            self.ack_count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

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

    struct BacklogActivationSpawner {
        inbox: Arc<dyn SessionInboxPort>,
        reservations: Arc<AtomicUsize>,
        launches: Arc<AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl crate::SessionActivationSpawner for BacklogActivationSpawner {
        async fn reserve_activation(
            &self,
            target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<crate::SessionActivationReserveOutcome, SessionActivationError> {
            let backlog = self
                .inbox
                .inspect(target_session_id)
                .await
                .map_err(|error| SessionActivationError::Internal(error.to_string()))?;
            if !backlog.activation_pending() {
                return Ok(crate::SessionActivationReserveOutcome::NoWork);
            }
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            let launches = self.launches.clone();
            Ok(crate::SessionActivationReserveOutcome::Reserved(
                crate::SessionActivationLaunch::new(format!("successor-{ordinal}"), move || {
                    launches.fetch_add(1, Ordering::SeqCst);
                }),
            ))
        }
    }

    #[async_trait::async_trait]
    impl SessionInboxPort for AckAfterPersistErrorInbox {
        async fn deliver(
            &self,
            envelope: &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<bamboo_domain::SessionInboxClaim>, bamboo_domain::SessionInboxError>
        {
            self.inner.claim(target_session_id, limit).await
        }

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

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

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

    async fn durable_inbox_fixture(
        id: &str,
    ) -> (
        tempfile::TempDir,
        Arc<bamboo_storage::SessionStoreV2>,
        Arc<bamboo_storage::LockedSessionStore>,
        Arc<dyn SessionInboxPort>,
        Session,
    ) {
        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 persistence = 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(id, "model");
        store.save_session(&session).await.unwrap();
        (temp, store, persistence, inbox, session)
    }

    async fn deliver_interrupt_eligible(
        inbox: &Arc<dyn SessionInboxPort>,
        envelope: &SessionMessageEnvelope,
    ) -> bamboo_domain::SessionInboxReceipt {
        let receipt = inbox.deliver(envelope).await.unwrap();
        inbox
            .mark_activation_eligible(
                &envelope.target_session_id,
                receipt.generation,
                bamboo_domain::SessionActivationPolicy::InterruptSpecificWait,
            )
            .await
            .unwrap();
        receipt
    }

    #[tokio::test]
    async fn owned_inbox_claim_requires_current_owner_before_provider_admission() {
        use bamboo_domain::{SessionInboxConsumerId, SessionInboxLeaseRequest};

        let (_home, store, locked, inbox, mut running) =
            durable_inbox_fixture("owned-claim-boundary").await;
        let envelope = SessionMessageEnvelope::user_input(&running.id, "leased input");
        deliver_interrupt_eligible(&inbox, &envelope).await;
        let lease = SessionInboxLeaseRequest {
            consumer: SessionInboxConsumerId::new(),
            now: chrono::Utc::now(),
            duration: chrono::Duration::seconds(30),
        };
        let owned = inbox
            .claim_owned(&running.id, 1, None, &lease)
            .await
            .unwrap();
        assert_eq!(owned.len(), 1);

        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(
            refresh.admission_error.as_deref(),
            Some(INBOX_CLAIM_UNRESOLVED)
        );
        assert_eq!(refresh.merged, 0);
        assert!(!running
            .messages
            .iter()
            .any(|message| message.id == envelope.id.as_str()));
        assert!(!inbox.was_admitted(&running.id, &envelope.id).await.unwrap());
        let cold = store.load_session(&running.id).await.unwrap().unwrap();
        assert!(!cold
            .messages
            .iter()
            .any(|message| message.id == envelope.id.as_str()));
        assert_eq!(
            inbox
                .inspect_owned_leases(&running.id, 1, lease.now)
                .await
                .unwrap()
                .len(),
            1
        );
    }

    #[tokio::test]
    async fn merge_pending_injected_messages_merges_and_clears() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> =
            Arc::new(TestPersistence(storage.clone()));
        let mut persisted = Session::new_child("child-merge", "parent", "model", "Child");
        persisted.add_message(bamboo_agent_core::Message::system("system"));
        persisted.add_message(bamboo_agent_core::Message::user("original task"));
        persisted.metadata.insert(
            PENDING_INJECTED_MESSAGES_KEY.to_string(),
            serde_json::json!([
                {
                    "content": "queued correction",
                    "created_at": chrono::Utc::now(),
                }
            ])
            .to_string(),
        );
        storage
            .save_session(&persisted)
            .await
            .expect("persisted child should be saved");

        let mut running = persisted.clone();
        running.metadata.remove(PENDING_INJECTED_MESSAGES_KEY);

        let count =
            merge_pending_injected_messages(&mut running, Some(&storage), Some(&persistence)).await;

        assert_eq!(count, 1);
        assert_eq!(
            running
                .messages
                .last()
                .map(|message| message.content.as_str()),
            Some("queued correction")
        );
        assert!(!running.metadata.contains_key(PENDING_INJECTED_MESSAGES_KEY));
        let saved = storage
            .load_session("child-merge")
            .await
            .expect("load should succeed")
            .expect("session should exist");
        assert!(!saved.metadata.contains_key(PENDING_INJECTED_MESSAGES_KEY));

        // Second merge is a no-op
        let count2 =
            merge_pending_injected_messages(&mut running, Some(&storage), Some(&persistence)).await;
        assert_eq!(count2, 0);
    }

    #[tokio::test]
    async fn merge_pending_injected_messages_returns_zero_without_storage() {
        let mut session = test_session();
        let count = merge_pending_injected_messages(&mut session, None, None).await;
        assert_eq!(count, 0);
    }

    // #540/#770: the turn-boundary refresh reports the live on-disk permission
    // mode so the pipeline can adopt a mid-run PATCH into the running loop.
    #[tokio::test]
    async fn refresh_turn_boundary_reports_disk_permission_mode() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());

        // Persist a session with bypass ON.
        let mut persisted = Session::new("bypass-live", "model");
        let mut state = AgentRuntimeState::new("run-x");
        state.set_permission_mode(bamboo_domain::SessionPermissionMode::Auto);
        persisted.agent_runtime_state = Some(state);
        for (key, value) in [
            ("permission.policy_revision", "17"),
            ("permission.requested_mode", "auto"),
            ("permission.effective_mode", "auto"),
            ("permission.executor_mapping", "bamboo_runtime:auto"),
            ("permission.transitioned_at", "2026-07-31T12:00:00Z"),
        ] {
            persisted
                .metadata
                .insert(key.to_string(), value.to_string());
        }
        storage.save_session(&persisted).await.unwrap();

        // A running loop holds a stale copy with bypass OFF.
        let mut running = Session::new("bypass-live", "model");
        running.agent_runtime_state = Some(AgentRuntimeState::new("run-x"));
        running.metadata.insert(
            "permission.executor_mapping".to_string(),
            "bamboo_runtime:default".to_string(),
        );

        let refresh = refresh_turn_boundary_from_disk(&mut running, Some(&storage), None).await;
        assert_eq!(
            refresh.disk_permission_mode,
            Some(bamboo_domain::SessionPermissionMode::Auto)
        );
        assert_eq!(refresh.merged, 0);
        for (key, value) in [
            ("permission.policy_revision", "17"),
            ("permission.requested_mode", "auto"),
            ("permission.effective_mode", "auto"),
            ("permission.executor_mapping", "bamboo_runtime:auto"),
            ("permission.transitioned_at", "2026-07-31T12:00:00Z"),
        ] {
            assert_eq!(running.metadata.get(key).map(String::as_str), Some(value));
        }
    }

    #[tokio::test]
    async fn refresh_turn_boundary_reports_none_without_storage() {
        let mut session = test_session();
        let refresh = refresh_turn_boundary_from_disk(&mut session, None, None).await;
        assert_eq!(refresh.disk_permission_mode, None);
        assert_eq!(refresh.merged, 0);
    }

    // #540 review: a disk copy with no agent_runtime_state reports None
    // (unknown), NOT Some(false) — so the pipeline won't force-disable a
    // legitimately bypassed run.
    #[tokio::test]
    async fn refresh_turn_boundary_reports_none_when_disk_has_no_runtime_state() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());
        let persisted = Session::new("no-rs", "model");
        assert!(persisted.agent_runtime_state.is_none());
        storage.save_session(&persisted).await.unwrap();

        let mut running = Session::new("no-rs", "model");
        let refresh = refresh_turn_boundary_from_disk(&mut running, Some(&storage), None).await;
        assert_eq!(refresh.disk_permission_mode, None);
    }

    #[tokio::test]
    async fn inbox_checkpoint_failure_rolls_back_memory_and_leaves_claim_recoverable() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("checkpoint-failure").await;
        let mut envelope = SessionMessageEnvelope::user_input("checkpoint-failure", "recover me");
        envelope.id = SessionMessageId::parse("checkpoint-failure-message").unwrap();
        deliver_interrupt_eligible(&inbox, &envelope).await;

        let fault = Arc::new(FaultingPersistence {
            inner: locked.clone(),
            fail_checkpoint: std::sync::atomic::AtomicBool::new(true),
        });
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = fault;
        let storage: Arc<dyn Storage> = store.clone();
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert!(!running
            .messages
            .iter()
            .any(|message| message.id == envelope.id.as_str()));
        assert!(!running
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&envelope.id)));
        let backlog = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.claimed, 1);
        assert!(!inbox.was_admitted(&running.id, &envelope.id).await.unwrap());

        // Restart: recover the cur claim and admit it exactly once.
        let reopened: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let normal: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let mut restarted = store.load_session(&running.id).await.unwrap().unwrap();
        let refresh = refresh_turn_boundary_with_inbox(
            &mut restarted,
            Some(&storage),
            Some(&normal),
            Some(&reopened),
        )
        .await;
        assert_eq!(refresh.merged, 1);
        assert_eq!(
            restarted
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
        assert!(reopened
            .was_admitted(&running.id, &envelope.id)
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn non_typed_transcript_id_collision_never_acks_the_typed_claim() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("transcript-id-collision").await;
        let mut envelope =
            SessionMessageEnvelope::user_input("transcript-id-collision", "typed truth");
        envelope.id = SessionMessageId::parse("colliding-id").unwrap();
        deliver_interrupt_eligible(&inbox, &envelope).await;

        let mut forged = bamboo_agent_core::Message::user("unrelated transcript entry");
        forged.id = envelope.id.to_string();
        running.add_message(forged);
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert!(!running
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&envelope.id)));
        let backlog = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.claimed, 1);
        assert!(!inbox.was_admitted(&running.id, &envelope.id).await.unwrap());
    }

    #[tokio::test]
    async fn concurrent_durable_id_collision_after_claim_never_acks() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("durable-id-collision").await;
        let mut envelope =
            SessionMessageEnvelope::user_input("durable-id-collision", "typed truth");
        envelope.id = SessionMessageId::parse("durable-colliding-id").unwrap();
        deliver_interrupt_eligible(&inbox, &envelope).await;

        // A concurrent writer lands after the running snapshot was loaded but
        // before checkpoint merge. LockedSessionStore preserves that durable
        // message, so post-checkpoint proof must catch the collision.
        let mut concurrent = store.load_session(&running.id).await.unwrap().unwrap();
        let mut forged = bamboo_agent_core::Message::user("concurrent unrelated message");
        forged.id = envelope.id.to_string();
        concurrent.add_message(forged);
        store.save_session(&concurrent).await.unwrap();

        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        let backlog = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.claimed, 1);
        assert!(!inbox.was_admitted(&running.id, &envelope.id).await.unwrap());
        let durable = store.load_session(&running.id).await.unwrap().unwrap();
        assert!(!durable
            .messages
            .iter()
            .any(|message| { bamboo_domain::is_matching_session_message(message, &envelope) }));
    }

    #[tokio::test]
    async fn concurrent_durable_typed_body_mismatch_after_claim_never_acks() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("durable-typed-body-collision").await;
        let mut envelope =
            SessionMessageEnvelope::user_input("durable-typed-body-collision", "typed truth");
        envelope.id = SessionMessageId::parse("durable-typed-colliding-id").unwrap();
        deliver_interrupt_eligible(&inbox, &envelope).await;

        let mut different = envelope.clone();
        different.body = bamboo_domain::SessionMessageBody::Content(
            bamboo_domain::SessionMessageContent::text("forged different body"),
        );
        let mut concurrent = store.load_session(&running.id).await.unwrap().unwrap();
        concurrent.add_message(different.to_provider_message().unwrap());
        store.save_session(&concurrent).await.unwrap();

        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert_eq!(inbox.inspect(&running.id).await.unwrap().claimed, 1);
        assert!(!inbox.was_admitted(&running.id, &envelope.id).await.unwrap());
        let durable = store.load_session(&running.id).await.unwrap().unwrap();
        assert!(!durable
            .messages
            .iter()
            .any(|message| bamboo_domain::is_matching_session_message(message, &envelope)));
    }

    #[tokio::test]
    async fn permanent_receipt_without_typed_transcript_proof_leaves_cur_recoverable() {
        let (_temp, store, locked, real_inbox, mut running) =
            durable_inbox_fixture("permanent-without-proof").await;
        let mut envelope =
            SessionMessageEnvelope::user_input("permanent-without-proof", "recoverable");
        envelope.id = SessionMessageId::parse("receipt-without-proof").unwrap();
        deliver_interrupt_eligible(&real_inbox, &envelope).await;
        let ack_count = Arc::new(AtomicUsize::new(0));
        let inbox: Arc<dyn SessionInboxPort> = Arc::new(ForcedPermanentReceiptInbox {
            inner: real_inbox.clone(),
            ack_count: ack_count.clone(),
        });
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;

        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert_eq!(ack_count.load(Ordering::SeqCst), 0);
        assert_eq!(real_inbox.inspect(&running.id).await.unwrap().claimed, 1);
    }

    fn next_conversation(source: &Session) -> Session {
        let mut current = source.clone();
        current.conversation_reset = Some(bamboo_domain::ConversationResetState {
            schema_version: 1,
            conversation_revision: 1,
            receipts: vec![bamboo_domain::ConversationResetReceipt {
                operation_id: format!("0:{}", uuid::Uuid::new_v4()),
                birth_token: source.root_mode_birth_token(),
                expected_snapshot_sha256: "a".repeat(64),
                previous_revision: 0,
                conversation_revision: 1,
                retained_system_messages: 0,
                reset_at: source.updated_at,
            }],
        });
        current
    }

    struct ConversationReadPersistence {
        current: Session,
        writes: AtomicUsize,
    }
    #[async_trait::async_trait]
    impl bamboo_domain::RuntimeSessionPersistence for ConversationReadPersistence {
        async fn save_runtime_session(&self, _: &mut Session) -> std::io::Result<()> {
            self.writes.fetch_add(1, Ordering::SeqCst);
            Err(std::io::Error::other("unexpected write"))
        }
        async fn load_runtime_session(&self, _: &str) -> std::io::Result<Option<Session>> {
            Ok(Some(self.current.clone()))
        }
    }

    #[tokio::test]
    async fn permanent_receipt_from_another_conversation_cannot_adopt_history_or_ack() {
        let (_temp, store, _locked, real_inbox, mut running) =
            durable_inbox_fixture("permanent-conversation").await;
        let envelope =
            SessionMessageEnvelope::user_input(&running.id, "different conversation input");
        deliver_interrupt_eligible(&real_inbox, &envelope).await;
        let mut current = next_conversation(&running);
        current.add_message(envelope.to_provider_message().unwrap());
        let read = Arc::new(ConversationReadPersistence {
            current,
            writes: AtomicUsize::new(0),
        });
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = read.clone();
        let ack_count = Arc::new(AtomicUsize::new(0));
        let inbox: Arc<dyn SessionInboxPort> = Arc::new(ForcedPermanentReceiptInbox {
            inner: real_inbox.clone(),
            ack_count: ack_count.clone(),
        });
        let before = serde_json::to_value(&running).unwrap();
        let storage: Arc<dyn Storage> = store.clone();
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert!(refresh.committed_messages.is_empty());
        assert!(refresh
            .admission_error
            .unwrap()
            .contains("session_conversation_changed:"));
        assert_eq!(ack_count.load(Ordering::SeqCst), 0);
        assert_eq!(real_inbox.inspect(&running.id).await.unwrap().claimed, 1);
        assert_eq!(read.writes.load(Ordering::SeqCst), 0);
        assert_eq!(serde_json::to_value(&running).unwrap(), before);
        assert_eq!(
            serde_json::to_value(store.load_session(&running.id).await.unwrap().unwrap()).unwrap(),
            before
        );
    }

    #[tokio::test]
    async fn canonical_refresh_cannot_adopt_authority_queue_or_inputs_from_another_conversation() {
        let storage: Arc<dyn Storage> = Arc::new(TestStorage::default());
        let mut original = Session::new("refresh-conversation", "model");
        original.add_message(Message::user("original history"));
        let mut current = next_conversation(&original);
        current.metadata.insert(
            "pending_injected_messages".into(),
            r#"[{"content":"new conversation queue"}]"#.into(),
        );
        storage.save_session(&current).await.unwrap();
        let before = serde_json::to_value(&original).unwrap();
        let mut runtime = AgentRuntimeState::new("original-operation");
        let before_runtime = serde_json::to_value(&runtime).unwrap();
        assert!(
            refresh_tool_boundary_authorities(&mut original, &mut runtime, Some(&storage))
                .await
                .is_err()
        );
        assert!(
            refresh_round_root_tool_authority(&mut original, Some(&storage))
                .await
                .is_err()
        );
        assert!(
            ensure_initial_root_tool_authority(&mut original, Some(&storage))
                .await
                .is_err()
        );
        let refresh =
            refresh_turn_boundary_with_inbox(&mut original, Some(&storage), None, None).await;
        assert!(refresh
            .admission_error
            .unwrap()
            .contains("session_conversation_changed:"));
        assert_eq!(refresh.merged, 0);
        assert!(refresh.disk_permission_mode.is_none());
        assert_eq!(serde_json::to_value(&original).unwrap(), before);
        assert_eq!(serde_json::to_value(&runtime).unwrap(), before_runtime);
        assert_eq!(
            serde_json::to_value(storage.load_session(&original.id).await.unwrap().unwrap())
                .unwrap(),
            serde_json::to_value(&current).unwrap()
        );
    }

    #[tokio::test]
    async fn permanent_receipt_uses_unbounded_typed_marker_after_cursor_eviction() {
        let (_temp, store, locked, real_inbox, mut running) =
            durable_inbox_fixture("permanent-evicted-cursor").await;
        let mut envelope =
            SessionMessageEnvelope::user_input("permanent-evicted-cursor", "old admitted message");
        envelope.id = SessionMessageId::parse("evicted-receipt-id").unwrap();
        running.add_message(envelope.to_provider_message().unwrap());
        running
            .session_inbox_admission_mut()
            .record(envelope.id.clone(), 1);
        for sequence in 2..=(bamboo_domain::SESSION_INBOX_ADMITTED_CAPACITY as u64 + 1) {
            running.session_inbox_admission_mut().record(
                SessionMessageId::parse(format!("later-{sequence}")).unwrap(),
                sequence,
            );
        }
        assert!(!running
            .session_inbox_admission()
            .unwrap()
            .contains(&envelope.id));
        store.save_session(&running).await.unwrap();
        deliver_interrupt_eligible(&real_inbox, &envelope).await;

        let ack_count = Arc::new(AtomicUsize::new(0));
        let inbox: Arc<dyn SessionInboxPort> = Arc::new(ForcedPermanentReceiptInbox {
            inner: real_inbox.clone(),
            ack_count: ack_count.clone(),
        });
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert_eq!(ack_count.load(Ordering::SeqCst), 1);
        let backlog = real_inbox.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
        assert_eq!(
            running
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn post_receipt_ack_error_restarts_without_duplicate_transcript() {
        let (_temp, store, locked, real_inbox, mut running) =
            durable_inbox_fixture("ack-after-receipt").await;
        let mut envelope = SessionMessageEnvelope::user_input("ack-after-receipt", "exactly once");
        envelope.id = SessionMessageId::parse("ack-after-receipt-message").unwrap();
        deliver_interrupt_eligible(&real_inbox, &envelope).await;

        let faulted: Arc<dyn SessionInboxPort> = Arc::new(AckAfterPersistErrorInbox {
            inner: real_inbox.clone(),
            fail_before_once: std::sync::atomic::AtomicBool::new(false),
            fail_after_once: std::sync::atomic::AtomicBool::new(true),
        });
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked.clone();
        let storage: Arc<dyn Storage> = store.clone();
        refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&faulted),
        )
        .await;

        let checkpointed = store.load_session(&running.id).await.unwrap().unwrap();
        assert_eq!(
            checkpointed
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
        assert!(checkpointed
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&envelope.id)));
        assert!(real_inbox
            .was_admitted(&running.id, &envelope.id)
            .await
            .unwrap());

        let reopened: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        // A sender retry after restart observes the permanent receipt and does
        // not enqueue a second copy.
        reopened.deliver(&envelope).await.unwrap();
        assert_eq!(
            reopened.inspect(&running.id).await.unwrap().pending
                + reopened.inspect(&running.id).await.unwrap().claimed,
            0
        );
        let mut restarted = store.load_session(&running.id).await.unwrap().unwrap();
        refresh_turn_boundary_with_inbox(
            &mut restarted,
            Some(&storage),
            Some(&persistence),
            Some(&reopened),
        )
        .await;
        assert_eq!(
            restarted
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn checkpoint_success_pre_ack_failure_recovers_cur_without_duplicate() {
        let (_temp, store, locked, real_inbox, mut running) =
            durable_inbox_fixture("pre-ack-failure").await;
        let mut envelope = SessionMessageEnvelope::user_input("pre-ack-failure", "recover claimed");
        envelope.id = SessionMessageId::parse("pre-ack-message").unwrap();
        deliver_interrupt_eligible(&real_inbox, &envelope).await;
        let faulted: Arc<dyn SessionInboxPort> = Arc::new(AckAfterPersistErrorInbox {
            inner: real_inbox.clone(),
            fail_before_once: std::sync::atomic::AtomicBool::new(true),
            fail_after_once: std::sync::atomic::AtomicBool::new(false),
        });
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked.clone();
        let storage: Arc<dyn Storage> = store.clone();
        refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&faulted),
        )
        .await;
        let checkpointed = store.load_session(&running.id).await.unwrap().unwrap();
        assert_eq!(
            checkpointed
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
        assert_eq!(real_inbox.inspect(&running.id).await.unwrap().claimed, 1);
        assert!(!real_inbox
            .was_admitted(&running.id, &envelope.id)
            .await
            .unwrap());

        let reopened: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let mut restarted = checkpointed;
        refresh_turn_boundary_with_inbox(
            &mut restarted,
            Some(&storage),
            Some(&persistence),
            Some(&reopened),
        )
        .await;
        assert_eq!(
            restarted
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
        assert!(reopened
            .was_admitted(&running.id, &envelope.id)
            .await
            .unwrap());
        let backlog = reopened.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
    }

    #[derive(Default)]
    struct AckBoundaryProvider(AtomicUsize);

    #[async_trait::async_trait]
    impl bamboo_llm::LLMProvider for AckBoundaryProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[bamboo_agent_core::tools::ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> bamboo_llm::provider::Result<bamboo_llm::LLMStream> {
            self.0.fetch_add(1, Ordering::SeqCst);
            Ok(Box::pin(futures::stream::iter(vec![
                Ok(bamboo_llm::LLMChunk::Token("done".into())),
                Ok(bamboo_llm::LLMChunk::Done),
            ])))
        }
    }

    async fn run_ack_boundary(
        session: &mut Session,
        storage: Arc<dyn Storage>,
        persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence>,
        inbox: Arc<dyn SessionInboxPort>,
        provider: Arc<AckBoundaryProvider>,
    ) -> (Result<(), AgentError>, Vec<bamboo_agent_core::AgentEvent>) {
        let (events, mut received) = tokio::sync::mpsc::channel(128);
        let result = crate::runtime::runner::run_agent_loop_with_config(
            session,
            "continue".into(),
            events,
            provider,
            Arc::new(bamboo_tools::BuiltinToolExecutorBuilder::new().build()),
            tokio_util::sync::CancellationToken::new(),
            crate::runtime::config::AgentLoopConfig {
                storage: Some(storage),
                persistence: Some(persistence),
                session_inbox: Some(inbox),
                system_prompt: Some("system".into()),
                model_name: Some("model".into()),
                run_budget: bamboo_config::RunBudgetConfig {
                    max_rounds: Some(1),
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .await;
        let mut observed = Vec::new();
        while let Ok(event) = received.try_recv() {
            observed.push(event);
        }
        (result, observed)
    }

    #[tokio::test]
    async fn unresolved_ack_stops_shared_provider_round_and_cold_retry_deduplicates() {
        for permanent in [false, true] {
            for after_receipt in [false, true] {
                let id = format!("ack-stop-{permanent}-{after_receipt}");
                let (home, store, locked, real_inbox, mut running) =
                    durable_inbox_fixture(&id).await;
                let envelope = SessionMessageEnvelope::user_input(&id, "durable input");
                deliver_interrupt_eligible(&real_inbox, &envelope).await;
                if permanent {
                    // Model receipt publication followed by an interrupted cur
                    // removal using the actual claim bytes and permanent receipt.
                    let claim = real_inbox.claim(&id, 1).await.unwrap().remove(0);
                    let path = store
                        .bamboo_home_dir()
                        .join(store.resolve_rel_path(&id).await.unwrap())
                        .join("inbox/cur")
                        .join(&claim.claim_id);
                    let raw_claim = tokio::fs::read(&path).await.unwrap();
                    running.add_message(envelope.to_provider_message().unwrap());
                    running
                        .session_inbox_admission_mut()
                        .record(envelope.id.clone(), claim.generation);
                    locked
                        .checkpoint_runtime_session(&mut running)
                        .await
                        .unwrap();
                    real_inbox.ack(&id, &claim).await.unwrap();
                    tokio::fs::write(&path, raw_claim).await.unwrap();
                    assert!(real_inbox.was_admitted(&id, &envelope.id).await.unwrap());
                }
                let faulted: Arc<dyn SessionInboxPort> = Arc::new(AckAfterPersistErrorInbox {
                    inner: real_inbox.clone(),
                    fail_before_once: std::sync::atomic::AtomicBool::new(!after_receipt),
                    fail_after_once: std::sync::atomic::AtomicBool::new(after_receipt),
                });
                let provider = Arc::new(AckBoundaryProvider::default());
                let (result, events) = run_ack_boundary(
                    &mut running,
                    store.clone(),
                    locked,
                    faulted,
                    provider.clone(),
                )
                .await;
                assert!(result
                    .unwrap_err()
                    .to_string()
                    .contains("SessionInbox ACK unresolved"));
                assert_eq!(provider.0.load(Ordering::SeqCst), 0);
                assert_eq!(
                    events
                        .iter()
                        .filter(|event| matches!(event,
                    bamboo_agent_core::AgentEvent::MessageAppended { message_id, .. }
                    if message_id == envelope.id.as_str()))
                        .count(),
                    usize::from(!permanent)
                );
                assert_eq!(
                    real_inbox.was_admitted(&id, &envelope.id).await.unwrap(),
                    permanent || after_receipt
                );
                assert_eq!(
                    real_inbox.inspect(&id).await.unwrap().claimed,
                    usize::from(!after_receipt)
                );

                let reopened = Arc::new(
                    bamboo_storage::SessionStoreV2::new(home.path().to_path_buf())
                        .await
                        .unwrap(),
                );
                let mut retry = reopened.load_session(&id).await.unwrap().unwrap();
                assert_eq!(
                    retry
                        .messages
                        .iter()
                        .filter(|message| bamboo_domain::is_matching_session_message(
                            message, &envelope
                        ))
                        .count(),
                    1
                );
                assert!(retry
                    .session_inbox_admission()
                    .unwrap()
                    .contains(&envelope.id));
                let storage: Arc<dyn Storage> = reopened.clone();
                let persistence =
                    Arc::new(bamboo_storage::LockedSessionStore::new(storage.clone()));
                let inbox: Arc<dyn SessionInboxPort> =
                    Arc::new(bamboo_storage::FileSessionInbox::new(
                        reopened.clone(),
                        bamboo_domain::SessionInboxLimits::default(),
                    ));
                let (result, events) = run_ack_boundary(
                    &mut retry,
                    storage,
                    persistence,
                    inbox.clone(),
                    provider.clone(),
                )
                .await;
                result.unwrap();
                assert_eq!(provider.0.load(Ordering::SeqCst), 1);
                assert!(!events.iter().any(|event| matches!(event,
                    bamboo_agent_core::AgentEvent::MessageAppended { message_id, .. }
                    if message_id == envelope.id.as_str())));
                assert!(inbox.was_admitted(&id, &envelope.id).await.unwrap());
                let backlog = inbox.inspect(&id).await.unwrap();
                assert_eq!(backlog.pending + backlog.claimed, 0);
                let durable = reopened.load_session(&id).await.unwrap().unwrap();
                assert_eq!(
                    durable
                        .messages
                        .iter()
                        .filter(|message| bamboo_domain::is_matching_session_message(
                            message, &envelope
                        ))
                        .count(),
                    1
                );
            }
        }
    }

    #[tokio::test]
    async fn legacy_migration_clears_matching_running_snapshot_without_resurrection() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("legacy-running-snapshot").await;
        let legacy = vec![serde_json::json!({
            "content": "migrate me once",
            "created_at": "2026-07-25T00:00:00Z"
        })];
        running.set_pending_injected_messages(legacy.clone());
        store.save_session(&running).await.unwrap();

        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 1);
        assert!(!running.has_pending_injected_messages());

        let message_id = SessionMessageId::legacy(&running.id, 0, &legacy[0]);
        let reloaded = store.load_session(&running.id).await.unwrap().unwrap();
        assert!(!reloaded.has_pending_injected_messages());
        assert_eq!(
            reloaded
                .messages
                .iter()
                .filter(|message| message.id == message_id.as_str())
                .count(),
            1
        );

        let mut restarted = reloaded;
        let refresh = refresh_turn_boundary_with_inbox(
            &mut restarted,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 0);
        assert!(!restarted.has_pending_injected_messages());
        assert_eq!(
            restarted
                .messages
                .iter()
                .filter(|message| message.id == message_id.as_str())
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn legacy_migration_publishes_interrupt_activation_before_source_clear() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("legacy-mark-before-clear").await;
        let legacy = vec![serde_json::json!({
            "content": "survive clear crash",
            "nested": {"z": 1, "a": 2}
        })];
        let mut producer = store.load_session(&running.id).await.unwrap().unwrap();
        producer.set_pending_injected_messages(legacy.clone());
        store.save_session(&producer).await.unwrap();

        let storage: Arc<dyn Storage> = store.clone();
        let fault = Arc::new(ActivationBeforeClearPersistence {
            inner: locked.clone(),
            inbox: inbox.clone(),
            fail_clear_once: std::sync::atomic::AtomicBool::new(true),
            clear_calls: AtomicUsize::new(0),
        });
        let fault_persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = fault.clone();
        let crashed = migrate_legacy_pending_only(
            &mut running,
            Some(&storage),
            Some(&fault_persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(crashed.delivered, 1);
        assert_eq!(crashed.highest_generation, Some(1));
        assert!(!crashed.source_cleared);
        assert_eq!(fault.clear_calls.load(Ordering::SeqCst), 1);

        let after_crash = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(after_crash.generation, 1);
        assert_eq!(after_crash.activation_generation, 1);
        assert_eq!(after_crash.interrupt_generation, 1);
        assert!(after_crash.activation_pending());
        assert!(store
            .load_session(&running.id)
            .await
            .unwrap()
            .unwrap()
            .has_pending_injected_messages());

        // Process restart: deterministic delivery reuses generation one, then
        // the already-published activation permits the source CAS-clear.
        let reopened: Arc<dyn SessionInboxPort> = Arc::new(bamboo_storage::FileSessionInbox::new(
            store.clone(),
            bamboo_domain::SessionInboxLimits::default(),
        ));
        let normal: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let mut restarted = store.load_session(&running.id).await.unwrap().unwrap();
        let recovered = migrate_legacy_pending_only(
            &mut restarted,
            Some(&storage),
            Some(&normal),
            Some(&reopened),
        )
        .await;
        assert_eq!(recovered.delivered, 1);
        assert_eq!(recovered.highest_generation, Some(1));
        assert!(recovered.source_cleared);
        let backlog = reopened.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.generation, 1);
        assert_eq!(backlog.activation_generation, 1);
        assert_eq!(backlog.interrupt_generation, 1);
        assert!(!store
            .load_session(&running.id)
            .await
            .unwrap()
            .unwrap()
            .has_pending_injected_messages());
    }

    #[tokio::test]
    async fn legacy_activation_publish_failure_never_invokes_source_clear() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("legacy-mark-failure").await;
        let legacy = vec![serde_json::json!({"content": "do not clear"})];
        let mut producer = store.load_session(&running.id).await.unwrap().unwrap();
        producer.set_pending_injected_messages(legacy);
        store.save_session(&producer).await.unwrap();
        let storage: Arc<dyn Storage> = store.clone();
        let failed_inbox = Arc::new(FailActivationInbox {
            inner: inbox.clone(),
            marks: AtomicUsize::new(0),
        });
        let failed_port: Arc<dyn SessionInboxPort> = failed_inbox.clone();
        let clear_probe = Arc::new(ActivationBeforeClearPersistence {
            inner: locked,
            inbox: inbox.clone(),
            fail_clear_once: std::sync::atomic::AtomicBool::new(false),
            clear_calls: AtomicUsize::new(0),
        });
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = clear_probe.clone();

        let migration = migrate_legacy_pending_only(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&failed_port),
        )
        .await;
        assert_eq!(migration.delivered, 1);
        assert_eq!(migration.highest_generation, None);
        assert!(!migration.source_cleared);
        assert_eq!(failed_inbox.marks.load(Ordering::SeqCst), 1);
        assert_eq!(
            clear_probe.clear_calls.load(Ordering::SeqCst),
            0,
            "source CAS-clear must be unreachable until activation publish succeeds"
        );
        let backlog = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.generation, 1);
        assert_eq!(backlog.activation_generation, 0);
        assert!(store
            .load_session(&running.id)
            .await
            .unwrap()
            .unwrap()
            .has_pending_injected_messages());
    }

    #[tokio::test]
    async fn partial_legacy_migration_authorizes_prefix_and_never_clears_source() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("legacy-partial-prefix").await;
        let legacy = vec![
            serde_json::json!({"content": "first"}),
            serde_json::json!({"content": "second"}),
        ];
        let mut producer = store.load_session(&running.id).await.unwrap().unwrap();
        producer.set_pending_injected_messages(legacy.clone());
        store.save_session(&producer).await.unwrap();
        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked.clone();
        let faulted: Arc<dyn SessionInboxPort> = Arc::new(FailSecondDeliveryInbox {
            inner: inbox.clone(),
            deliveries: AtomicUsize::new(0),
        });

        let partial = migrate_legacy_pending_only(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&faulted),
        )
        .await;
        assert_eq!(partial.delivered, 1);
        assert_eq!(partial.highest_generation, Some(1));
        assert!(!partial.source_cleared);
        let prefix = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(prefix.generation, 1);
        assert_eq!(prefix.activation_generation, 1);
        assert_eq!(prefix.interrupt_generation, 1);
        assert!(prefix.activation_pending());
        assert!(store
            .load_session(&running.id)
            .await
            .unwrap()
            .unwrap()
            .has_pending_injected_messages());

        // A retry sees the first envelope's permanent enqueue identity, adds
        // only the missing suffix, publishes generation two, then clears.
        let mut restarted = store.load_session(&running.id).await.unwrap().unwrap();
        let complete = migrate_legacy_pending_only(
            &mut restarted,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(complete.delivered, 2);
        assert_eq!(complete.highest_generation, Some(2));
        assert!(complete.source_cleared);
        let backlog = inbox.inspect(&running.id).await.unwrap();
        assert_eq!(backlog.generation, 2);
        assert_eq!(backlog.activation_generation, 2);
        assert_eq!(backlog.interrupt_generation, 2);
        assert_eq!(backlog.pending, 2);
        assert!(!store
            .load_session(&running.id)
            .await
            .unwrap()
            .unwrap()
            .has_pending_injected_messages());
    }

    #[tokio::test]
    async fn task_end_guidance_survives_later_round_admission_and_launches_one_successor() {
        let (_temp, store, locked, inbox, mut running) =
            durable_inbox_fixture("guidance-modes").await;
        let storage: Arc<dyn Storage> = store;
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let router = crate::SessionActivationRouter::new();
        router.set_inbox(inbox.clone());
        let reservations = Arc::new(AtomicUsize::new(0));
        let launches = Arc::new(AtomicUsize::new(0));
        router
            .set_spawner(Arc::new(BacklogActivationSpawner {
                inbox: inbox.clone(),
                reservations: reservations.clone(),
                launches: launches.clone(),
            }))
            .await;
        let mut registration = router.register_run(&running.id, "run-a").await.unwrap();
        let mut deferred = SessionMessageEnvelope::user_input(&running.id, "task end");
        deferred.correlation_id = Some("session-guidance-after-run:run-a".into());
        let mut immediate = SessionMessageEnvelope::user_input(&running.id, "round end");
        immediate.correlation_id = Some("session-guidance".into());
        for envelope in [&deferred, &immediate] {
            let receipt = deliver_interrupt_eligible(&inbox, envelope).await;
            router
                .request_activation(&running.id, receipt.generation)
                .await
                .unwrap();
        }
        let result = refresh_turn_boundary_with_inbox_for_run(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            Some("run-a"),
        )
        .await;
        assert_eq!(result.merged, 1);
        assert_eq!(result.committed_messages.len(), 1);
        assert_eq!(result.committed_messages[0].id, immediate.id.as_str());
        assert!(running
            .messages
            .iter()
            .any(|message| message.id == immediate.id.as_str()));
        assert!(!running
            .messages
            .iter()
            .any(|message| message.id == deferred.id.as_str()));
        let cursor = running
            .session_inbox_admission()
            .unwrap()
            .last_admitted_sequence;
        assert_eq!(cursor, 2);
        assert_eq!(inbox.pending_guidance(&running.id).await.unwrap().len(), 1);
        registration.begin_finalization().await;
        assert_eq!(
            registration.finish(cursor).await.unwrap(),
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(launches.load(Ordering::SeqCst), 1);
        let mut next = router
            .register_run(&running.id, "successor-1")
            .await
            .unwrap();
        let result = refresh_turn_boundary_with_inbox_for_run(
            &mut running,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
            Some("successor-1"),
        )
        .await;
        assert_eq!(result.merged, 1);
        assert_eq!(result.committed_messages.len(), 1);
        assert_eq!(result.committed_messages[0].id, deferred.id.as_str());
        assert_eq!(
            running
                .messages
                .iter()
                .filter(|message| message.id == deferred.id.as_str())
                .count(),
            1
        );
        next.begin_finalization().await;
        assert_eq!(next.finish(cursor).await.unwrap(), None);
        assert_eq!(reservations.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn terminal_typed_delivery_stays_pending_for_exactly_one_successor_turn() {
        let (_temp, store, locked, inbox, mut first_run) =
            durable_inbox_fixture("terminal-typed-race").await;
        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let router = crate::SessionActivationRouter::new();
        let reservations = Arc::new(AtomicUsize::new(0));
        let launches = Arc::new(AtomicUsize::new(0));
        router
            .set_spawner(Arc::new(BacklogActivationSpawner {
                inbox: inbox.clone(),
                reservations: reservations.clone(),
                launches: launches.clone(),
            }))
            .await;
        let mut registration = router
            .register_run(&first_run.id, "first-run")
            .await
            .unwrap();

        // The provider has returned from its final round. A typed delivery now
        // lands, but terminal cleanup must not claim or ack it.
        let mut envelope = SessionMessageEnvelope::user_input(&first_run.id, "after final round");
        envelope.id = SessionMessageId::parse("terminal-race-message").unwrap();
        let receipt = deliver_interrupt_eligible(&inbox, &envelope).await;
        assert_eq!(
            router
                .request_activation(&first_run.id, receipt.generation)
                .await
                .unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        assert_eq!(inbox.inspect(&first_run.id).await.unwrap().pending, 1);
        assert!(!first_run
            .messages
            .iter()
            .any(|message| message.id == envelope.id.as_str()));

        registration.begin_finalization().await;
        assert_eq!(
            registration.finish(0).await.unwrap(),
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(reservations.load(Ordering::SeqCst), 1);
        assert_eq!(launches.load(Ordering::SeqCst), 1);
        assert_eq!(inbox.inspect(&first_run.id).await.unwrap().pending, 1);

        // The successor's first safe boundary checkpoints and acknowledges the
        // envelope exactly once before reasoning.
        let refresh = refresh_turn_boundary_with_inbox(
            &mut first_run,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 1);
        assert_eq!(
            first_run
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
        let backlog = inbox.inspect(&first_run.id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
    }

    #[tokio::test]
    async fn terminal_legacy_migration_enqueues_without_ack_and_hands_off_generation() {
        let (_temp, store, locked, inbox, mut first_run) =
            durable_inbox_fixture("terminal-legacy-race").await;
        let legacy = vec![serde_json::json!({
            "content": "legacy after final round",
            "created_at": "2026-07-25T00:00:00Z"
        })];
        let mut producer_snapshot = store.load_session(&first_run.id).await.unwrap().unwrap();
        producer_snapshot.set_pending_injected_messages(legacy.clone());
        store.save_session(&producer_snapshot).await.unwrap();

        let storage: Arc<dyn Storage> = store.clone();
        let persistence: Arc<dyn bamboo_domain::RuntimeSessionPersistence> = locked;
        let migration = migrate_legacy_pending_only(
            &mut first_run,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(migration.delivered, 1);
        assert!(migration.source_cleared);
        let generation = migration.highest_generation.expect("durable generation");
        let message_id = SessionMessageId::legacy(&first_run.id, 0, &legacy[0]);
        assert_eq!(inbox.inspect(&first_run.id).await.unwrap().pending, 1);
        assert!(!inbox
            .was_admitted(&first_run.id, &message_id)
            .await
            .unwrap());
        assert!(!store
            .load_session(&first_run.id)
            .await
            .unwrap()
            .unwrap()
            .has_pending_injected_messages());

        let router = crate::SessionActivationRouter::new();
        let reservations = Arc::new(AtomicUsize::new(0));
        let launches = Arc::new(AtomicUsize::new(0));
        router
            .set_spawner(Arc::new(BacklogActivationSpawner {
                inbox: inbox.clone(),
                reservations: reservations.clone(),
                launches: launches.clone(),
            }))
            .await;
        let mut registration = router
            .register_run(&first_run.id, "first-run")
            .await
            .unwrap();
        assert_eq!(
            router
                .request_activation(&first_run.id, generation)
                .await
                .unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        registration.begin_finalization().await;
        assert_eq!(
            registration.finish(0).await.unwrap(),
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(reservations.load(Ordering::SeqCst), 1);
        assert_eq!(launches.load(Ordering::SeqCst), 1);

        let refresh = refresh_turn_boundary_with_inbox(
            &mut first_run,
            Some(&storage),
            Some(&persistence),
            Some(&inbox),
        )
        .await;
        assert_eq!(refresh.merged, 1);
        assert_eq!(
            first_run
                .messages
                .iter()
                .filter(|message| message.id == message_id.as_str())
                .count(),
            1
        );
        let backlog = inbox.inspect(&first_run.id).await.unwrap();
        assert_eq!(backlog.pending + backlog.claimed, 0);
    }
}

#[cfg(test)]
mod input_request_projection_tests {
    use super::*;
    use crate::runtime::managers::lifecycle::{
        BoundedInputRequestBatch,
        InputRequestProjection::{Available, Unavailable},
        InputRequestUnavailable,
    };
    use bamboo_domain::{SessionSkillRequest, SessionSkillSelection};

    fn request() -> SessionSkillRequest {
        SessionSkillRequest {
            selections: vec![SessionSkillSelection {
                id: "skill".into(),
                source: "user".into(),
                revision: u64::MAX,
                args: serde_json::json!({"n": u64::MAX, "a": [1, 1.25, null]}),
            }],
            mode: None,
        }
    }
    fn record(request: Option<&SessionSkillRequest>) -> BorrowedInputRequestRecord<'_> {
        BorrowedInputRequestRecord {
            input_id: "u",
            source: &SessionMessageSource::User,
            kind: SessionMessageKind::UserInput,
            wrapper: None,
            created_at: chrono::DateTime::from_timestamp(1, 0).unwrap(),
            request,
        }
    }
    fn available(
        session: &str,
        execution: &str,
        records: &[BorrowedInputRequestRecord<'_>],
    ) -> BoundedInputRequestBatch {
        match project_input_request_batch(session, execution, records) {
            Available(batch) => batch,
            Unavailable(error) => panic!("unexpected bounded diagnostic {error:?}"),
        }
    }

    #[test]
    fn input_request_projection_charges_exact_private_framing_escaping_and_null() {
        let mut row = record(None);
        row.input_id = "u\"\t界";
        let rows = [row];
        let expected = r#"{"session_id":"s\n界","execution_id":"e\"","records":[["u\"\t界",{"type":"user"},"user_input",null,"1970-01-01T00:00:01Z",null]]}"#;
        let encoded = serde_json::to_vec(&InputRequestMeasurement {
            session_id: "s\n界",
            execution_id: "e\"",
            records: InputRequestRecordsMeasurement(&rows),
        })
        .unwrap();
        assert_eq!(encoded, expected.as_bytes());
        let batch = available("s\n界", "e\"", &rows);
        assert_eq!(batch.compact_bytes(), expected.len());
        assert_eq!(batch.session_id(), "s\n界");
        assert_eq!(batch.execution_id(), "e\"");
        assert_eq!(batch.records()[0].input_id, row.input_id);
        assert_eq!(batch.records()[0].request, None);
        let mut data = request();
        let without_mode = available("s", "e", &[record(Some(&data))]).compact_bytes();
        data.mode = Some("review".into());
        assert_eq!(
            available("s", "e", &[record(Some(&data))]).compact_bytes(),
            without_mode + r#","mode":"review""#.len()
        );
    }

    #[test]
    fn input_request_projection_accepts_exact_whole_limit_then_rejects_one_byte() {
        let mut data = SessionSkillRequest {
            selections: (0..32)
                .map(|i| SessionSkillSelection {
                    id: format!("{i:x}"),
                    source: "user".into(),
                    revision: 1,
                    args: serde_json::Value::String(String::new()),
                })
                .collect(),
            mode: None,
        };
        let baseline = serde_json::to_vec(&InputRequestMeasurement {
            session_id: "s",
            execution_id: "e",
            records: InputRequestRecordsMeasurement(&[record(Some(&data))]),
        })
        .unwrap()
        .len();
        let padding = 262144 - baseline;
        for (i, selection) in data.selections.iter_mut().enumerate() {
            selection.args =
                serde_json::Value::String("x".repeat(padding / 32 + usize::from(i < padding % 32)));
        }
        data.validate().unwrap();
        let batch = available("s", "e", &[record(Some(&data))]);
        assert_eq!(batch.compact_bytes(), 262144);
        assert_eq!(batch.records()[0].request.as_ref().unwrap(), &data);
        if let serde_json::Value::String(value) = &mut data.selections[0].args {
            value.push('x');
        }
        data.validate().unwrap(); // Individually valid; only whole-batch overhead overflows.
        assert_eq!(
            project_input_request_batch("s", "e", &[record(Some(&data))]),
            Unavailable(InputRequestUnavailable::CompactLimit { limit: 262144 })
        );
        let rows = [record(Some(&data)), record(Some(&data))];
        assert!(matches!(
            project_input_request_batch("s", "e", &rows),
            Unavailable(InputRequestUnavailable::CompactLimit { .. })
        ));
    }

    #[test]
    fn input_request_projection_preserves_order_and_charges_every_none_record() {
        let ids: Vec<_> = (0..129).map(|i| format!("u-{i}")).collect();
        let rows: Vec<_> = ids
            .iter()
            .map(|id| BorrowedInputRequestRecord {
                input_id: id,
                ..record(None)
            })
            .collect();
        let batch = available("s", "e", &rows[..128]);
        assert_eq!(batch.records().len(), 128);
        assert_eq!(
            batch
                .records()
                .iter()
                .map(|r| &r.input_id)
                .collect::<Vec<_>>(),
            ids[..128].iter().collect::<Vec<_>>()
        );
        assert!(batch.records().iter().all(|row| row.request.is_none()));
        let one = available("s", "e", &rows[..1]);
        assert!(batch.compact_bytes() > one.compact_bytes() * 50);
        assert_eq!(
            project_input_request_batch("s", "e", &rows),
            Unavailable(InputRequestUnavailable::RecordLimit {
                count: 129,
                limit: 128
            })
        );
        let empty = available("s", "e", &[]);
        assert!(empty.records().is_empty());
        assert_eq!(
            empty.compact_bytes(),
            r#"{"session_id":"s","execution_id":"e","records":[]}"#.len()
        );
    }

    #[test]
    fn input_request_projection_rejects_original_invalid_data_without_partial_output() {
        for id in ["", " ", " u", "u ", "a/b", "a\\b", "a..b", &"界".repeat(86)] {
            let rows = [
                record(None),
                BorrowedInputRequestRecord {
                    input_id: id,
                    ..record(None)
                },
            ];
            assert_eq!(
                project_input_request_batch("s", "e", &rows),
                Unavailable(InputRequestUnavailable::InvalidData)
            );
        }
        let canonical = format!("{}\t界", "x".repeat(252));
        assert_eq!(canonical.len(), 256);
        assert_eq!(
            available(
                "s",
                "e",
                &[BorrowedInputRequestRecord {
                    input_id: &canonical,
                    ..record(None)
                }]
            )
            .records()[0]
                .input_id,
            canonical
        );
        let mut data = request();
        for depth in [64, 65, 256] {
            data.selections[0].args = (0..depth).fold(serde_json::Value::Null, |value, _| {
                serde_json::Value::Array(vec![value])
            });
            let result =
                project_input_request_batch("s", "e", &[record(None), record(Some(&data))]);
            assert_eq!(matches!(result, Available(_)), depth == 64);
            if depth != 64 {
                assert_eq!(result, Unavailable(InputRequestUnavailable::InvalidData));
            }
        }
        data.selections[0].args = serde_json::Value::Array(vec![serde_json::Value::Null; 8192]);
        assert_eq!(
            project_input_request_batch("s", "e", &[record(Some(&data))]),
            Unavailable(InputRequestUnavailable::InvalidData)
        );
        data.selections[0].args = serde_json::Value::Null;
        for mode in ["", "UPPER", "a_b", &"x".repeat(65)] {
            data.mode = Some(mode.into());
            assert_eq!(
                project_input_request_batch("s", "e", &[record(Some(&data))]),
                Unavailable(InputRequestUnavailable::InvalidData)
            );
        }
        data.mode = Some("x".repeat(64));
        available("s", "e", &[record(Some(&data))]);
        data.selections.clear();
        assert_eq!(
            project_input_request_batch("s", "e", &[record(Some(&data))]),
            Unavailable(InputRequestUnavailable::InvalidData)
        );
    }

    #[test]
    fn input_request_projection_normalizes_nested_capacities_and_outlives_original_data() {
        fn excess(value: &str) -> String {
            let mut s = String::with_capacity(100000);
            s.push_str(value);
            s
        }
        fn nodes(value: &serde_json::Value) -> usize {
            1 + match value {
                serde_json::Value::Array(v) => v.iter().map(nodes).sum(),
                serde_json::Value::Object(v) => v.values().map(nodes).sum(),
                _ => 0,
            }
        }
        let mut data = request();
        data.mode = Some(excess("review"));
        let mut array = Vec::with_capacity(100000);
        array.push(serde_json::Value::String(excess("界\"\n")));
        let mut object = serde_json::Map::new();
        object.insert(excess("key"), serde_json::Value::String(excess("value")));
        array.push(serde_json::Value::Object(object));
        data.selections[0].args = serde_json::Value::Array(array);
        data.selections[0].id = excess("skill");
        data.selections[0].source = excess("user");
        data.selections.reserve(100000);
        let source = SessionMessageSource::Runtime {
            subsystem: excess("chat"),
        };
        let input_id = excess("u");
        let wrapper = excess("root_chat_turn_v1");
        let session = excess("s");
        let execution = excess("e");
        let batch = available(
            &session,
            &execution,
            &[BorrowedInputRequestRecord {
                input_id: &input_id,
                source: &source,
                kind: SessionMessageKind::RuntimeInstruction,
                wrapper: Some(&wrapper),
                ..record(Some(&data))
            }],
        );
        let row = &batch.records()[0];
        assert_eq!(row.request.as_ref().unwrap(), &data);
        assert_eq!(
            row.created_at,
            chrono::DateTime::from_timestamp(1, 0).unwrap()
        );
        assert_eq!(row.kind, SessionMessageKind::RuntimeInstruction);
        assert_eq!(row.wrapper.as_deref(), Some("root_chat_turn_v1"));
        assert_eq!(batch.session_id.capacity(), batch.session_id.len());
        assert_eq!(batch.execution_id.capacity(), batch.execution_id.len());
        assert_eq!(row.input_id.capacity(), row.input_id.len());
        assert_eq!(row.wrapper.as_ref().unwrap().capacity(), wrapper.len());
        let SessionMessageSource::Runtime { subsystem } = &row.source else {
            panic!()
        };
        assert_eq!(subsystem.capacity(), subsystem.len());
        let copied = row.request.as_ref().unwrap();
        assert_eq!(copied.selections.capacity(), copied.selections.len());
        assert_eq!(copied.mode.as_ref().unwrap().capacity(), 6);
        let selection = &copied.selections[0];
        assert_eq!(selection.id.capacity(), selection.id.len());
        assert_eq!(selection.source.capacity(), selection.source.len());
        let values = selection.args.as_array().unwrap();
        assert_eq!(values.capacity(), values.len());
        let serde_json::Value::String(s) = &values[0] else {
            panic!()
        };
        assert_eq!(s.capacity(), s.len());
        let (key, value) = values[1].as_object().unwrap().iter().next().unwrap();
        assert_eq!(key.capacity(), key.len());
        let serde_json::Value::String(s) = value else {
            panic!()
        };
        assert_eq!(s.capacity(), s.len());
        assert!(nodes(&selection.args) <= batch.compact_bytes());
        drop((data, source, input_id, wrapper, session, execution));
        assert_eq!(
            batch.records()[0].request.as_ref().unwrap().selections[0].revision,
            u64::MAX
        );
        let scalar = request();
        assert_eq!(
            available("s", "e", &[record(Some(&scalar))]).records()[0]
                .request
                .as_ref(),
            Some(&scalar)
        );
    }
    #[test]
    fn input_request_projection_request_golden_charges_keys_numbers_mode_and_provenance() {
        let data = SessionSkillRequest {
            mode: Some("review".into()),
            selections: vec![SessionSkillSelection {
                id: "skill".into(),
                source: "plugin".into(),
                revision: u64::MAX,
                args: serde_json::json!({"n": u64::MAX, "q": "界\"\n"}),
            }],
        };
        let source = SessionMessageSource::Runtime {
            subsystem: "chat".into(),
        };
        let rows = [BorrowedInputRequestRecord {
            source: &source,
            kind: SessionMessageKind::RuntimeInstruction,
            wrapper: Some("root_chat_turn_v1"),
            created_at: chrono::DateTime::from_timestamp(1, 123456789).unwrap(),
            ..record(Some(&data))
        }];
        let expected = r#"{"session_id":"s","execution_id":"e","records":[["u",{"type":"runtime","subsystem":"chat"},"runtime_instruction","root_chat_turn_v1","1970-01-01T00:00:01.123456789Z",{"selections":[{"id":"skill","source":"plugin","revision":18446744073709551615,"args":{"n":18446744073709551615,"q":"界\"\n"}}],"mode":"review"}]]}"#;
        assert_eq!(
            serde_json::to_vec(&InputRequestMeasurement {
                session_id: "s",
                execution_id: "e",
                records: InputRequestRecordsMeasurement(&rows)
            })
            .unwrap(),
            expected.as_bytes()
        );
        let batch = available("s", "e", &rows);
        assert_eq!(batch.compact_bytes(), expected.len());
        assert_eq!(batch.records()[0].request.as_ref(), Some(&data));
        assert_eq!(batch.records()[0].created_at, rows[0].created_at);
    }

    #[test]
    fn input_request_projection_reuses_all_original_selection_validation() {
        let mut invalid = Vec::new();
        for id in ["", " skill", "skill ", "bad\n", &"x".repeat(257)] {
            let mut value = request();
            value.selections[0].id = id.into();
            invalid.push(value);
        }
        for source in ["", "USER", "user ", "unknown"] {
            let mut value = request();
            value.selections[0].source = source.into();
            invalid.push(value);
        }
        let mut zero = request();
        zero.selections[0].revision = 0;
        invalid.push(zero);
        let mut duplicate = request();
        duplicate.selections.push(duplicate.selections[0].clone());
        duplicate.selections[1].source = "builtin".into();
        invalid.push(duplicate);
        let mut excessive = request();
        excessive.selections = (0..33)
            .map(|i| SessionSkillSelection {
                id: format!("s{i}"),
                ..request().selections.remove(0)
            })
            .collect();
        invalid.push(excessive);
        for value in invalid {
            assert_eq!(
                project_input_request_batch("s", "e", &[record(None), record(Some(&value))]),
                Unavailable(InputRequestUnavailable::InvalidData)
            );
        }
    }

    #[test]
    fn input_request_projection_retains_every_untrusted_source_and_kind_exactly() {
        let mut identity = String::with_capacity(100000);
        identity.push_str(" peer/\n界");
        let sources = [
            SessionMessageSource::User,
            SessionMessageSource::Session {
                session_id: identity,
            },
            SessionMessageSource::Runtime {
                subsystem: "arbitrary".into(),
            },
        ];
        for source in &sources {
            for kind in [
                SessionMessageKind::UserInput,
                SessionMessageKind::PeerMessage,
                SessionMessageKind::ChildOutcome,
                SessionMessageKind::RuntimeInstruction,
            ] {
                let row = BorrowedInputRequestRecord {
                    source,
                    kind,
                    ..record(None)
                };
                let batch = available("s", "e", &[row]);
                assert_eq!(&batch.records()[0].source, source);
                assert_eq!(batch.records()[0].kind, kind); // Data, never eligibility/currentness.
                if let SessionMessageSource::Session { session_id } = &batch.records()[0].source {
                    assert_eq!(session_id.capacity(), session_id.len());
                    assert_eq!(session_id, " peer/\n界");
                }
            }
        }
    }
}