bamboo-engine 2026.10.22

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

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock, Weak};

use async_trait::async_trait;
use bamboo_domain::{
    SessionActivationDisposition, SessionActivationError, SessionActivationPort, SessionInboxPort,
    SessionInboxWakeCandidate,
};
use chrono::{DateTime, Duration, Utc};
use tokio::sync::{mpsc, watch, Mutex, RwLock};

type AsyncRollback =
    Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> + Send + 'static>;

/// A reservation whose runner slot already exists but whose task has not yet
/// been launched. The router publishes the logical owner before calling
/// `launch`, so even an immediately-completing task participates in the
/// finalization handshake.
pub struct SessionActivationLaunch {
    pub run_id: String,
    launch: Option<Box<dyn FnOnce() + Send + 'static>>,
    rollback: Option<AsyncRollback>,
    rollback_completion: Option<Arc<RollbackCompletion>>,
}

struct RollbackCompletion {
    completed: watch::Sender<bool>,
}

impl RollbackCompletion {
    fn new() -> Arc<Self> {
        let (completed, _receiver) = watch::channel(false);
        Arc::new(Self { completed })
    }

    fn complete(&self) {
        self.completed.send_replace(true);
    }

    async fn wait(&self) {
        let mut completed = self.completed.subscribe();
        while !*completed.borrow() {
            if completed.changed().await.is_err() {
                break;
            }
        }
    }
}

impl SessionActivationLaunch {
    pub fn new(run_id: impl Into<String>, launch: impl FnOnce() + Send + 'static) -> Self {
        Self {
            run_id: run_id.into(),
            launch: Some(Box::new(launch)),
            rollback: None,
            rollback_completion: None,
        }
    }

    /// Build a launch backed by an already-reserved external runner slot.
    ///
    /// If the launch is dropped before `launch` commits, `rollback` must release
    /// that exact reservation. This makes cancellation between the spawner
    /// returning and the router publishing ownership recoverable.
    pub fn new_with_rollback(
        run_id: impl Into<String>,
        launch: impl FnOnce() + Send + 'static,
        rollback: impl FnOnce() + Send + 'static,
    ) -> Self {
        Self::new_with_async_rollback(run_id, launch, move || async move {
            rollback();
        })
    }

    /// Build a launch whose exact external runner reservation is released
    /// asynchronously if publication is cancelled. The router does not release
    /// its coalescing token until this future completes, preventing a newer
    /// activation from adopting the still-present unlaunched slot.
    pub fn new_with_async_rollback<F, Fut>(
        run_id: impl Into<String>,
        launch: impl FnOnce() + Send + 'static,
        rollback: F,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let rollback_completion = RollbackCompletion::new();
        Self {
            run_id: run_id.into(),
            launch: Some(Box::new(launch)),
            rollback: Some(Box::new(move || Box::pin(rollback()))),
            rollback_completion: Some(rollback_completion),
        }
    }

    fn rollback_completion(&self) -> Option<Arc<RollbackCompletion>> {
        self.rollback_completion.clone()
    }

    fn launch(mut self) {
        if let Some(launch) = self.launch.take() {
            self.rollback = None;
            self.rollback_completion = None;
            launch();
        }
    }
}

impl Drop for SessionActivationLaunch {
    fn drop(&mut self) {
        if self.launch.is_some() {
            if let Some(rollback) = self.rollback.take() {
                let completion = self.rollback_completion.take();
                if let Ok(runtime) = tokio::runtime::Handle::try_current() {
                    runtime.spawn(async move {
                        rollback().await;
                        if let Some(completion) = completion {
                            completion.complete();
                        }
                    });
                }
            }
        }
    }
}

impl fmt::Debug for SessionActivationLaunch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SessionActivationLaunch")
            .field("run_id", &self.run_id)
            .finish_non_exhaustive()
    }
}

#[derive(Debug)]
pub enum SessionActivationReserveOutcome {
    /// Existing runner reservation succeeded. The returned launch must be
    /// invoked exactly once.
    Reserved(SessionActivationLaunch),
    /// Some non-router path already owns the existing runner reservation.
    AlreadyRunning { run_id: String },
    /// The target disappeared before reservation.
    NotFound,
    /// The inbox was drained by another valid owner before reservation.
    NoWork,
}

/// A logical session already belongs to a different exact activation run.
///
/// Registration is the last line of defence between independently scheduled
/// entry points. A collision is returned to the later caller without mutating
/// the existing owner.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SessionRunRegistrationError {
    #[error(
        "session activation owner collision for {target_session_id}: \
         existing run {existing_run_id}, attempted run {attempted_run_id}"
    )]
    OwnerCollision {
        target_session_id: String,
        existing_run_id: String,
        attempted_run_id: String,
    },
}

impl SessionRunRegistrationError {
    /// The exact run that already owns the logical session.
    pub fn existing_run_id(&self) -> &str {
        match self {
            Self::OwnerCollision {
                existing_run_id, ..
            } => existing_run_id,
        }
    }
}

/// Adapter to the owning runtime's existing runner reservation and spawn path.
///
/// Implementations must reserve through the same per-session runner registry as
/// user/resume execution. They must not start a task before returning
/// [`SessionActivationReserveOutcome::Reserved`].
#[async_trait]
pub trait SessionActivationSpawner: Send + Sync {
    async fn reserve_activation(
        &self,
        target_session_id: &str,
        inbox_generation: u64,
    ) -> Result<SessionActivationReserveOutcome, SessionActivationError>;
}

#[derive(Debug, Clone)]
struct ActiveOwner {
    instance: Arc<()>,
    run_id: String,
    /// Set only by a real registration at its Session-bound execution entry.
    session_created_at: Option<DateTime<Utc>>,
    finalizing: bool,
    registrations: usize,
    /// Scheduling boundary for this owner, not durable queue/authority state.
    /// Keep wait/Guardian outcomes together until this exact Run leaves.
    child_completions_need_successor: bool,
    /// Present only while an external actor driver is alive. The payload is a
    /// wake generation; that driver remains the single consumer of the
    /// canonical FileSessionInbox and forwards the claimed typed envelope.
    delivery_sink: Option<mpsc::UnboundedSender<u64>>,
    scoped_loop: Option<SupervisorLoopGrant>,
}

#[derive(Debug, Clone)]
struct SupervisorLoopGrant {
    binding: bamboo_domain::ScopedLoopControlBinding,
    execution_cancel: tokio_util::sync::CancellationToken,
    host_stop: tokio_util::sync::CancellationToken,
}
impl SupervisorLoopGrant {
    fn stopped(&self) -> bool {
        self.execution_cancel.is_cancelled() || self.host_stop.is_cancelled()
    }
}

struct SupervisorLoopDeliveryGuard {
    inner: ExpectedRunDeliveryGuard,
    grant: SupervisorLoopGrant,
}
impl bamboo_domain::SessionRunDeliveryGuard for SupervisorLoopDeliveryGuard {
    fn matches(&self, target: &str, birth: DateTime<Utc>, run: &str) -> bool {
        !self.grant.stopped()
            && bamboo_domain::SessionRunDeliveryGuard::matches(&self.inner, target, birth, run)
    }
    fn notify_committed_delivery(&self, generation: u64) -> bool {
        self.inner.notify_if(generation, || !self.grant.stopped())
    }
}

#[derive(Debug)]
struct TargetActivationState {
    latest_generation: u64,
    /// Delivery notification only. Never participates in successor scheduling.
    latest_delivery_generation: u64,
    /// Highest generation for which this process already launched an execution.
    /// Adopting an independently running owner does not consume this retry. If a
    /// launched execution leaves the same poison claim pending,
    /// terminal finalization must not hot-loop provider runs forever. A newer
    /// generation may still trigger one fresh activation; process restart also
    /// resets this bounded retry guard.
    last_dispatched_generation: u64,
    /// Immediate messages can run ahead of an unreleased staged prefix. A
    /// later coordinator release permits one more dispatch even when its
    /// delivery generation is older, without retrying the same poison prefix.
    last_dispatched_coordinator_generation: u64,
    /// Advances only when the exact logical owner leaves. A recovered ready
    /// claim may be redispatched in the same generation after this edge.
    owner_completion_epoch: u64,
    last_recovery_attempt: Option<RecoveryAttempt>,
    owner: Option<ActiveOwner>,
    activation_reserved: bool,
    /// Identity of the current reservation attempt. A cancellation cleanup or
    /// late spawner result may only release the token it acquired.
    activation_token: u64,
    /// Incremented whenever an in-flight reservation attempt releases the
    /// reservation. A delivery that coalesces behind that attempt waits for
    /// this edge and re-evaluates ownership instead of returning a success that
    /// could be stranded when the earlier attempt reports NoWork or fails.
    activation_epoch: watch::Sender<u64>,
    notify: watch::Sender<u64>,
}

impl Default for TargetActivationState {
    fn default() -> Self {
        let (activation_epoch, _activation_receiver) = watch::channel(0);
        let (notify, _receiver) = watch::channel(0);
        Self {
            latest_generation: 0,
            latest_delivery_generation: 0,
            last_dispatched_generation: 0,
            last_dispatched_coordinator_generation: 0,
            owner_completion_epoch: 0,
            last_recovery_attempt: None,
            owner: None,
            activation_reserved: false,
            activation_token: 0,
            activation_epoch,
            notify,
        }
    }
}

const INITIAL_RECOVERY_BACKOFF: Duration = Duration::seconds(30);
const MAX_RECOVERY_BACKOFF: Duration = Duration::minutes(30);

#[derive(Debug, Clone)]
struct RecoveryAttempt {
    candidate: SessionInboxWakeCandidate,
    completion_epoch: u64,
    backoff: Duration,
    next_retry_at: DateTime<Utc>,
    /// A reserved owner must finish before the same exact claim is retried.
    /// NoWork has no owner completion edge and is retried after backoff.
    requires_completion: bool,
}

fn recovery_retry_at(
    state: &TargetActivationState,
    candidate: &SessionInboxWakeCandidate,
    now: DateTime<Utc>,
) -> Option<Option<DateTime<Utc>>> {
    let previous = state
        .last_recovery_attempt
        .as_ref()
        .filter(|attempt| attempt.candidate == *candidate)?;
    if previous.requires_completion && state.owner_completion_epoch <= previous.completion_epoch {
        return Some(None);
    }
    (now < previous.next_retry_at).then_some(Some(previous.next_retry_at))
}

fn record_recovery_attempt(
    state: &mut TargetActivationState,
    candidate: SessionInboxWakeCandidate,
    now: DateTime<Utc>,
    requires_completion: bool,
) {
    let backoff = state
        .last_recovery_attempt
        .as_ref()
        .filter(|attempt| attempt.candidate == candidate)
        .map_or(INITIAL_RECOVERY_BACKOFF, |attempt| {
            (attempt.backoff * 2).min(MAX_RECOVERY_BACKOFF)
        });
    state.last_recovery_attempt = Some(RecoveryAttempt {
        candidate,
        completion_epoch: state.owner_completion_epoch,
        backoff,
        next_retry_at: now + backoff,
        requires_completion,
    });
}

/// Result of one exact Inbox wake inspection and router handoff. A due time
/// is a scheduling hint; the next attempt re-reads the canonical queue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionWakeReconcileResult {
    pub disposition: Option<SessionActivationDisposition>,
    pub next_due_at: Option<DateTime<Utc>>,
}

fn reserve_activation_token(state: &mut TargetActivationState) -> u64 {
    state.activation_reserved = true;
    state.activation_token = state.activation_token.wrapping_add(1).max(1);
    state.activation_token
}

fn release_activation_token(state: &mut TargetActivationState, token: u64) -> bool {
    if !state.activation_reserved || state.activation_token != token {
        return false;
    }
    state.activation_reserved = false;
    let next_epoch = (*state.activation_epoch.borrow()).wrapping_add(1);
    state.activation_epoch.send_replace(next_epoch);
    true
}

fn inbox_activation_error(error: bamboo_domain::SessionInboxError) -> SessionActivationError {
    match error {
        bamboo_domain::SessionInboxError::TargetNotFound(target) => {
            SessionActivationError::TargetNotFound(target)
        }
        error => SessionActivationError::Internal(error.to_string()),
    }
}

/// Cancellation lease for one router reservation attempt. Every await after
/// publishing `activation_reserved` is covered; dropping the caller releases
/// only its exact token and wakes coalesced deliveries. Finalization-owned
/// attempts additionally schedule one bounded retry because their racing
/// producer already returned a coalesced success and is no longer waiting.
struct ActivationReservationLease {
    router: SessionActivationRouter,
    target_session_id: String,
    token: u64,
    recover_on_drop: bool,
    armed: bool,
    rollback_completion: Option<Arc<RollbackCompletion>>,
}

impl ActivationReservationLease {
    fn new(
        router: SessionActivationRouter,
        target_session_id: &str,
        token: u64,
        recover_on_drop: bool,
    ) -> Self {
        Self {
            router,
            target_session_id: target_session_id.to_string(),
            token,
            recover_on_drop,
            armed: true,
            rollback_completion: None,
        }
    }

    fn wait_for_rollback(&mut self, completion: Option<Arc<RollbackCompletion>>) {
        self.rollback_completion = completion;
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for ActivationReservationLease {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let router = self.router.clone();
        let target_session_id = self.target_session_id.clone();
        let token = self.token;
        let recover_on_drop = self.recover_on_drop;
        let rollback_completion = self.rollback_completion.take();
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            runtime.spawn(async move {
                if let Some(completion) = rollback_completion {
                    completion.wait().await;
                }
                router
                    .recover_cancelled_reservation(&target_session_id, token, recover_on_drop)
                    .await;
            });
        }
    }
}

struct ExpectedRunDeliveryGuard {
    target_session_id: String,
    session_created_at: DateTime<Utc>,
    run_id: String,
    states: Arc<Mutex<HashMap<String, TargetActivationState>>>,
    _publication: tokio::sync::OwnedMutexGuard<()>,
}

impl bamboo_domain::SessionRunDeliveryGuard for ExpectedRunDeliveryGuard {
    fn matches(
        &self,
        target_session_id: &str,
        target_created_at: DateTime<Utc>,
        expected_run_id: &str,
    ) -> bool {
        self.target_session_id == target_session_id
            && self.session_created_at == target_created_at
            && self.run_id == expected_run_id
    }

    fn notify_committed_delivery(&self, inbox_generation: u64) -> bool {
        self.notify_if(inbox_generation, || true)
    }
}

impl ExpectedRunDeliveryGuard {
    fn notify_if(&self, inbox_generation: u64, allowed: impl FnOnce() -> bool) -> bool {
        // The blocking publication job already holds this target's fence.
        // Take the global map only for its short notification update.
        let mut states = self.states.blocking_lock();
        let Some(state) = states.get_mut(&self.target_session_id) else {
            return false;
        };
        let Some(owner) = state.owner.as_mut().filter(|owner| {
            owner.run_id == self.run_id
                && owner.session_created_at == Some(self.session_created_at)
                && !owner.finalizing
                && owner.registrations > 0
                && allowed()
        }) else {
            return false;
        };
        // Same QueueOnly notification contract as v2: never reserve a successor.
        state.latest_delivery_generation = state.latest_delivery_generation.max(inbox_generation);
        state.notify.send_replace(inbox_generation);
        if owner
            .delivery_sink
            .as_ref()
            .is_some_and(|sink| sink.send(inbox_generation).is_err())
        {
            owner.delivery_sink = None;
        }
        true
    }
}

/// One router per owning runtime/AppState. All keys are logical Session ids.
#[derive(Clone, Default)]
pub struct SessionActivationRouter {
    runtime_instance: Arc<()>,
    states: Arc<Mutex<HashMap<String, TargetActivationState>>>,
    /// Live operations for one logical target share a fence. Weak entries are
    /// pruned on access; idle/deleted targets retain no separate lock state.
    publication_fences: TargetPublicationFences,
    spawner: Arc<RwLock<Option<Arc<dyn SessionActivationSpawner>>>>,
    inbox: Arc<StdRwLock<Option<Arc<dyn SessionInboxPort>>>>,
    #[cfg(test)]
    terminal_inspection_pause: Arc<Mutex<Option<TerminalInspectionPause>>>,
}

type TargetPublicationFences = Arc<StdMutex<HashMap<String, Weak<Mutex<()>>>>>;

#[cfg(test)]
type TerminalInspectionPause = (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>);

type AbortCleanup =
    Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> + Send + 'static>;

type ScopedTransportCleanup =
    Arc<dyn Fn() -> Pin<Box<dyn Future<Output = std::io::Result<()>> + Send>> + Send + Sync>;

struct ClosedLoopTransportGuard(ExpectedRunDeliveryGuard);
impl bamboo_domain::SessionRunDeliveryGuard for ClosedLoopTransportGuard {
    fn matches(&self, target: &str, birth: DateTime<Utc>, run: &str) -> bool {
        bamboo_domain::SessionRunDeliveryGuard::matches(&self.0, target, birth, run)
    }
    fn notify_committed_delivery(&self, _generation: u64) -> bool {
        false
    }
}

/// Exact-run ownership lease returned by
/// [`SessionActivationRouter::register_run`].
///
/// The lease deliberately owns the safe-point receiver. Dropping it before the
/// normal finalization handshake schedules exact-run cleanup, reconciles the
/// durable activation watermark, and gives the router one chance to launch a
/// successor. A stale lease can never clear a newer owner.
pub struct SessionRunRegistration {
    instance: Arc<()>,
    router: Arc<SessionActivationRouter>,
    target_session_id: String,
    run_id: String,
    notifications: Option<watch::Receiver<u64>>,
    abort_cleanup: Option<AbortCleanup>,
    scoped_transport_cleanup: Option<ScopedTransportCleanup>,
    quarantine_on_drop: bool,
    // The host binds the actual opaque scope before polling direct execution.
    // It is not a Session/model field and cannot grant or weaken authority.
    tool_suspension_observation: Option<bamboo_agent_core::tools::SuspensionRestriction>,
    selected_input_wakes: Option<watch::Receiver<u64>>,
    armed: bool,
}

/// Private proof derived from a real registration, never reconstructed from
/// metadata or the presence of another caller's active run.
#[derive(Clone)]
pub(crate) struct SessionRunOwnership {
    instance: Arc<()>,
    router: Arc<SessionActivationRouter>,
    target_session_id: String,
    run_id: String,
}

impl SessionRunOwnership {
    /// Target authority only. Close under the producer's original publication
    /// fence, without recreating a missing owner or consulting a revoked grant.
    pub(crate) async fn close_scoped_transport(
        &self,
        binding: &bamboo_domain::ScopedLoopControlBinding,
    ) -> std::io::Result<()> {
        if binding.target_session_id != self.target_session_id
            || binding.owner_run_id != self.run_id
        {
            return Err(std::io::Error::other(
                "target transport proof identity differs",
            ));
        }
        let _publication = self.router.lock_publication(&self.target_session_id).await;
        let mut states = self.router.states.lock().await;
        let owner = states
            .get_mut(&self.target_session_id)
            .and_then(|state| state.owner.as_mut())
            .filter(|owner| {
                Arc::ptr_eq(&owner.instance, &self.instance)
                    && owner.run_id == self.run_id
                    && owner.session_created_at == Some(binding.target_created_at)
                    && owner.registrations > 0
            })
            .ok_or_else(|| {
                std::io::Error::other("target transport owner is no longer registered")
            })?;
        if owner
            .scoped_loop
            .as_ref()
            .is_some_and(|grant| grant.binding.execution_id != binding.execution_id)
        {
            return Err(std::io::Error::other("target transport execution differs"));
        }
        owner.finalizing = true;
        Ok(())
    }

    pub(crate) fn retain_closed_scoped_transport(
        &self,
        binding: &bamboo_domain::ScopedLoopControlBinding,
    ) -> std::io::Result<Arc<dyn bamboo_domain::SessionRunDeliveryGuard>> {
        if binding.target_session_id != self.target_session_id
            || binding.owner_run_id != self.run_id
        {
            return Err(std::io::Error::other("closed transport identity differs"));
        }
        let publication = self
            .router
            .publication_fence(&self.target_session_id)
            .blocking_lock_owned();
        let states = self.router.states.blocking_lock();
        if !states
            .get(&self.target_session_id)
            .and_then(|state| state.owner.as_ref())
            .is_some_and(|owner| {
                Arc::ptr_eq(&owner.instance, &self.instance)
                    && owner.run_id == self.run_id
                    && owner.session_created_at == Some(binding.target_created_at)
                    && owner.finalizing
                    && owner.registrations > 0
            })
        {
            return Err(std::io::Error::other("closed transport owner changed"));
        }
        drop(states);
        Ok(Arc::new(ClosedLoopTransportGuard(
            ExpectedRunDeliveryGuard {
                target_session_id: self.target_session_id.clone(),
                session_created_at: binding.target_created_at,
                run_id: self.run_id.clone(),
                states: self.router.states.clone(),
                _publication: publication,
            },
        )))
    }

    pub(crate) fn run_id(&self) -> &str {
        &self.run_id
    }

    pub(crate) fn router(&self) -> &Arc<SessionActivationRouter> {
        &self.router
    }

    pub(crate) fn matches_router(&self, router: &Arc<SessionActivationRouter>) -> bool {
        Arc::ptr_eq(&self.router, router)
    }

    pub(crate) async fn is_current(&self, session_id: &str) -> bool {
        self.target_session_id == session_id && self.router.owns_run(session_id, &self.run_id).await
    }
}

impl SessionRunRegistration {
    pub(crate) fn set_scoped_transport_cleanup<F, Fut>(&mut self, cleanup: F)
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = std::io::Result<()>> + Send + 'static,
    {
        self.scoped_transport_cleanup = Some(Arc::new(move || Box::pin(cleanup())));
    }

    pub(crate) fn bind_tool_suspension_observation(
        &mut self,
        token: bamboo_agent_core::tools::SuspensionRestriction,
    ) {
        self.tool_suspension_observation = Some(token);
    }

    pub(crate) fn observed_forbidden_running(&self) -> bool {
        self.tool_suspension_observation
            .as_ref()
            .is_some_and(|token| token.observation().forbidden_running_seen)
    }

    pub(crate) fn ownership(&self) -> SessionRunOwnership {
        SessionRunOwnership {
            instance: self.instance.clone(),
            router: self.router.clone(),
            target_session_id: self.target_session_id.clone(),
            run_id: self.run_id.clone(),
        }
    }

    /// Observe independent producer wakeups without consuming the runtime's
    /// normal receiver. A selected input must not promote unrelated durable
    /// backlog merely by releasing its own registration. This is an existing
    /// watch subscription, not a second routing state or durable grant.
    pub(crate) fn restrict_to_selected_input(&mut self) {
        if self.selected_input_wakes.is_none() {
            self.selected_input_wakes = self.notifications.clone();
        }
    }

    pub fn notifications_mut(&mut self) -> &mut watch::Receiver<u64> {
        self.notifications
            .as_mut()
            .expect("run registration notifications are live before finalization")
    }

    /// Run host-specific exact-reservation cleanup before an abandoned owner
    /// asks the router to reserve a successor.
    pub fn set_abort_cleanup<F, Fut>(&mut self, cleanup: F)
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.abort_cleanup = Some(Box::new(move || Box::pin(cleanup())));
    }

    pub async fn begin_finalization(&mut self) {
        self.router
            .begin_finalization(&self.target_session_id, &self.run_id)
            .await;
    }

    /// Physical execution now outlives this lease's future. Unexpected unwind
    /// must retain ownership until backend reconciliation, never launch a
    /// successor through the ordinary abandoned-startup cleanup.
    pub(crate) fn quarantine_on_drop(&mut self) {
        self.quarantine_on_drop = true;
    }

    /// Keep this exact logical owner finalizing when its physical stop or
    /// terminal delivery is unconfirmed. Dropping this lease must not run the
    /// usual abandoned-owner recovery and launch a successor.
    ///
    /// Recovery must explicitly reconcile the retained owner before finishing
    /// finalization. Disarm before the await so cancelling quarantine itself
    /// cannot accidentally release the owner.
    pub async fn quarantine(mut self) {
        self.armed = false;
        self.abort_cleanup = None;
        self.router
            .begin_finalization(&self.target_session_id, &self.run_id)
            .await;
        if let Some(cleanup) = self.scoped_transport_cleanup.take() {
            let task = tokio::spawn(async move { cleanup().await });
            match task.await {
                Ok(Ok(())) => {}
                result => tracing::warn!(?result, "quarantined Loop transport cleanup incomplete"),
            }
        }
        self.notifications.take();
    }

    /// Synchronously abandon this exact ownership lease.
    ///
    /// Most cancellation paths can rely on [`Drop`], which schedules the same
    /// cleanup. Startup paths that must return a truthful retryable response
    /// use this method so the runner slot and router owner are released before
    /// the response becomes observable. Cleanup runs in a detached owned task:
    /// cancelling the caller's wait cannot strand an already-taken host
    /// cleanup closure or this router owner.
    pub async fn abandon(mut self) {
        self.armed = false;
        if self.selected_input_wakes.is_some() {
            drop(self.notifications.take());
        }
        let scoped_transport_cleanup = self.scoped_transport_cleanup.clone();
        let abort_cleanup = self.abort_cleanup.take();
        let router = self.router.clone();
        let target_session_id = self.target_session_id.clone();
        let run_id = self.run_id.clone();
        let cleanup_target_session_id = target_session_id.clone();
        let cleanup_run_id = run_id.clone();
        let selected_input_wakes = self.selected_input_wakes.take();
        let cleanup = tokio::spawn(async move {
            if let Some(cleanup) = scoped_transport_cleanup {
                if let Err(error) = cleanup().await {
                    tracing::warn!(%error, "closed Loop transport cleanup failed; retaining abandoned owner");
                    return;
                }
            }
            if let Some(cleanup) = abort_cleanup {
                cleanup().await;
            }
            router
                .cleanup_abandoned_registration(
                    &cleanup_target_session_id,
                    &cleanup_run_id,
                    selected_input_wakes,
                )
                .await;
        });
        if let Err(error) = cleanup.await {
            tracing::error!(
                %target_session_id,
                %run_id,
                %error,
                "detached SessionInbox registration cleanup failed"
            );
        }
    }

    /// Complete the normal exact-owner handshake. The Drop fallback remains
    /// armed across the await and is disabled only after finalization returns.
    pub async fn finish(
        mut self,
        admitted_generation: u64,
    ) -> Result<Option<SessionActivationDisposition>, SessionActivationError> {
        if let Some(cleanup) = &self.scoped_transport_cleanup {
            cleanup()
                .await
                .map_err(|error| SessionActivationError::Internal(error.to_string()))?;
        }
        // The router compacts caught-up routing state only after the last
        // safe-point receiver is gone.
        drop(self.notifications.take());
        let released = match self.selected_input_wakes.as_ref() {
            Some(wakes) => {
                self.router
                    .release_selected_if_unnotified(&self.target_session_id, &self.run_id, wakes)
                    .await
            }
            None => false,
        };
        let result = if released {
            Ok(None)
        } else {
            self.router
                .finish_finalization(&self.target_session_id, &self.run_id, admitted_generation)
                .await
        };
        if result.is_ok() {
            self.armed = false;
            self.abort_cleanup = None;
        }
        result
    }
}

impl Drop for SessionRunRegistration {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let router = self.router.clone();
        let target_session_id = self.target_session_id.clone();
        let run_id = self.run_id.clone();
        let scoped_transport_cleanup = self.scoped_transport_cleanup.clone();
        let abort_cleanup = self.abort_cleanup.take();
        let quarantine = self.quarantine_on_drop || self.observed_forbidden_running();
        if self.selected_input_wakes.is_some() {
            drop(self.notifications.take());
        }
        let selected_input_wakes = self.selected_input_wakes.take();
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            runtime.spawn(async move {
                if let Some(cleanup) = scoped_transport_cleanup {
                    if let Err(error) = cleanup().await {
                        tracing::warn!(%error, "closed Loop transport cleanup failed; retaining dropped owner");
                        return;
                    }
                }
                if quarantine {
                    router.begin_finalization(&target_session_id, &run_id).await;
                    return;
                }
                if let Some(cleanup) = abort_cleanup {
                    cleanup().await;
                }
                router
                    .cleanup_abandoned_registration(
                        &target_session_id,
                        &run_id,
                        selected_input_wakes,
                    )
                    .await;
            });
        }
    }
}

impl SessionActivationRouter {
    fn publication_fence(&self, target: &str) -> Arc<Mutex<()>> {
        let mut fences = self
            .publication_fences
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        fences.retain(|_, fence| fence.strong_count() > 0);
        if let Some(fence) = fences.get(target).and_then(Weak::upgrade) {
            return fence;
        }
        let fence = Arc::new(Mutex::new(()));
        fences.insert(target.into(), Arc::downgrade(&fence));
        fence
    }

    async fn lock_publication(&self, target: &str) -> tokio::sync::OwnedMutexGuard<()> {
        // Always acquire this target before the map. Never await a target
        // publication while holding the runtime-wide states mutex.
        self.publication_fence(target).lock_owned().await
    }

    async fn coordinator_generation(&self, target: &str) -> Result<u64, SessionActivationError> {
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        match inbox {
            Some(inbox) => inbox
                .coordinator_activation_generation(target)
                .await
                .map_err(inbox_activation_error),
            None => Ok(0),
        }
    }

    async fn released_pending_generation(
        &self,
        target: &str,
        after: u64,
    ) -> Result<u64, SessionActivationError> {
        if self.coordinator_generation(target).await? <= after {
            return Ok(0);
        }
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        match inbox {
            Some(inbox) => {
                let backlog = inbox
                    .inspect(target)
                    .await
                    .map_err(inbox_activation_error)?;
                Ok(
                    if backlog.activation_pending() && backlog.coordinator_generation > after {
                        backlog.coordinator_generation
                    } else {
                        0
                    },
                )
            }
            None => Ok(0),
        }
    }

    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Late-bind the real server/SDK reservation adapter after its dependency
    /// graph has been assembled.
    pub async fn set_spawner(&self, spawner: Arc<dyn SessionActivationSpawner>) {
        *self.spawner.write().await = Some(spawner);
    }

    /// Snapshot the current logical run, including its terminal handoff.
    pub async fn current_run_id(&self, target_session_id: &str) -> Option<String> {
        self.states
            .lock()
            .await
            .get(target_session_id)
            .and_then(|state| state.owner.as_ref().map(|owner| owner.run_id.clone()))
    }

    /// Select a completion's successor fence under the current owner lock.
    /// Once a wait or Guardian transition belongs to this owner, later sibling
    /// callbacks keep that boundary even after the durable wait was cleared.
    /// A background-only reasoning owner can instead consume its next safe point.
    pub(crate) async fn child_completion_successor_run(
        &self,
        target_session_id: &str,
        wait_or_guardian_transition: bool,
        previous_fenced_run: Option<&str>,
    ) -> Option<String> {
        let mut states = self.states.lock().await;
        let owner = states.get_mut(target_session_id)?.owner.as_mut()?;
        owner.child_completions_need_successor |=
            wait_or_guardian_transition || previous_fenced_run == Some(owner.run_id.as_str());
        (owner.finalizing || owner.child_completions_need_successor).then(|| owner.run_id.clone())
    }

    /// Bind the durable inbox used by abandoned-run reconciliation.
    pub fn set_inbox(&self, inbox: Arc<dyn SessionInboxPort>) {
        *self
            .inbox
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(inbox);
    }

    /// Reconcile one target against a storage-locked proof of claimable work.
    /// A later claim still CAS-checks the lease and activation policy. The
    /// router keeps only a bounded retry guard, never queue truth.
    pub async fn reconcile_wake(
        &self,
        target_session_id: &str,
        now: DateTime<Utc>,
    ) -> Result<SessionWakeReconcileResult, SessionActivationError> {
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
            .ok_or_else(|| {
                SessionActivationError::Internal("session inbox is not configured".into())
            })?;
        let readiness = inbox
            .inspect_wake_readiness(target_session_id, now)
            .await
            .map_err(inbox_activation_error)?;
        let Some(candidate) = readiness.ready else {
            return Ok(SessionWakeReconcileResult {
                disposition: None,
                next_due_at: readiness.next_due_at,
            });
        };
        let mut result = self
            .request_recovery_activation(target_session_id, candidate, now)
            .await?;
        result.next_due_at = match (result.next_due_at, readiness.next_due_at) {
            (Some(left), Some(right)) => Some(left.min(right)),
            (left, right) => left.or(right),
        };
        Ok(result)
    }

    /// A precise grant can open a delivery below an already dispatched high
    /// watermark. Use the existing bounded recovery handshake for that hole;
    /// ordinary same-generation leftovers keep their existing retry cadence.
    async fn reconcile_older_message(
        &self,
        target: &str,
    ) -> Result<Option<SessionActivationDisposition>, SessionActivationError> {
        let high = self
            .states
            .lock()
            .await
            .get(target)
            .map_or(0, |state| state.last_dispatched_generation);
        self.reconcile_message_below(target, high).await
    }

    async fn reconcile_message_below(
        &self,
        target: &str,
        high: u64,
    ) -> Result<Option<SessionActivationDisposition>, SessionActivationError> {
        if high == 0 {
            return Ok(None);
        }
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let Some(inbox) = inbox else {
            return Ok(None);
        };
        let now = Utc::now();
        let candidate = inbox
            .inspect_wake_readiness(target, now)
            .await
            .map_err(inbox_activation_error)?
            .ready;
        match candidate.filter(|candidate| {
            candidate.generation < high
                // Only an explicit coordinator upgrade opens this older hole.
                // A prefix may already cover the delivery at Respect policy.
                && candidate.coordinator_message_policy
                    == Some(bamboo_domain::SessionActivationPolicy::InterruptSpecificWait)
        }) {
            Some(candidate) => self
                .request_recovery_activation(target, candidate, now)
                .await
                .map(|result| result.disposition),
            None => Ok(None),
        }
    }

    #[cfg(test)]
    async fn pause_after_terminal_inspection(&self) {
        let pause = self.terminal_inspection_pause.lock().await.take();
        if let Some((entered, release)) = pause {
            entered.notify_one();
            release.notified().await;
        }
    }

    async fn request_recovery_activation(
        &self,
        target_session_id: &str,
        candidate: SessionInboxWakeCandidate,
        now: DateTime<Utc>,
    ) -> Result<SessionWakeReconcileResult, SessionActivationError> {
        loop {
            let (reservation_wait, reservation_token) = {
                let mut states = self.states.lock().await;
                let state = states.entry(target_session_id.to_string()).or_default();
                state.latest_generation = state.latest_generation.max(candidate.generation);
                if let Some(owner) = state.owner.as_mut() {
                    if !owner.finalizing {
                        state.notify.send_replace(candidate.generation);
                        if owner
                            .delivery_sink
                            .as_ref()
                            .is_some_and(|sink| sink.send(candidate.generation).is_err())
                        {
                            owner.delivery_sink = None;
                        }
                        return Ok(SessionWakeReconcileResult {
                            disposition: Some(SessionActivationDisposition::ActiveNotified),
                            next_due_at: None,
                        });
                    }
                    return Ok(SessionWakeReconcileResult {
                        disposition: Some(SessionActivationDisposition::ActivationCoalesced),
                        next_due_at: None,
                    });
                }
                if let Some(next_due_at) = recovery_retry_at(state, &candidate, now) {
                    return Ok(SessionWakeReconcileResult {
                        disposition: None,
                        next_due_at,
                    });
                } else if state.activation_reserved {
                    (Some(state.activation_epoch.subscribe()), None)
                } else {
                    let token = reserve_activation_token(state);
                    (None, Some(token))
                }
            };

            if let Some(mut reservation_wait) = reservation_wait {
                if reservation_wait.changed().await.is_err() {
                    return Err(SessionActivationError::TargetNotFound(
                        target_session_id.to_string(),
                    ));
                }
                continue;
            }
            let token = reservation_token.expect("recovery activation owns reservation token");
            let disposition = self
                .dispatch_reserved_with_recovery(
                    target_session_id,
                    candidate.generation,
                    token,
                    false,
                    Some((candidate, now)),
                )
                .await?;
            return Ok(SessionWakeReconcileResult {
                disposition: Some(disposition),
                next_due_at: None,
            });
        }
    }

    #[cfg(test)]
    pub(crate) async fn hold_state_lock_for_test(
        &self,
        entered: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        let _states = self.states.lock().await;
        entered.notify_one();
        release.notified().await;
    }

    #[cfg(test)]
    pub(crate) async fn install_owner_placeholder_for_test(
        &self,
        target_session_id: &str,
        run_id: &str,
    ) {
        let _publication = self.lock_publication(target_session_id).await;
        let mut states = self.states.lock().await;
        states
            .entry(target_session_id.to_string())
            .or_default()
            .owner = Some(ActiveOwner {
            instance: Arc::new(()),
            run_id: run_id.to_string(),
            session_created_at: None,
            finalizing: false,
            registrations: 0,
            child_completions_need_successor: false,
            delivery_sink: None,
            scoped_loop: None,
        });
    }

    /// Register an execution created by any entry point. The returned receiver
    /// is a safe-point wake signal; the loop also drains the durable inbox at
    /// every round boundary, so missed/coalesced notifications do not lose data.
    pub async fn register_run(
        self: &Arc<Self>,
        target_session_id: &str,
        run_id: &str,
    ) -> Result<SessionRunRegistration, SessionRunRegistrationError> {
        self.register_run_with_birth(target_session_id, run_id, None)
            .await
    }

    /// Register from the actual execution's Session, enabling birth-fenced
    /// steer. This is a trusted host entrypoint, not model-supplied authority.
    pub async fn register_session_run(
        self: &Arc<Self>,
        session: &bamboo_domain::Session,
        run_id: &str,
    ) -> Result<SessionRunRegistration, SessionRunRegistrationError> {
        self.register_run_with_birth(&session.id, run_id, Some(session.created_at))
            .await
    }

    pub(crate) async fn bind_run_lifetime(
        self: &Arc<Self>,
        ownership: &SessionRunOwnership,
        session: &bamboo_domain::Session,
    ) -> bool {
        if !ownership.matches_router(self) || ownership.target_session_id != session.id {
            return false;
        }
        let _publication = self.lock_publication(&session.id).await;
        let mut states = self.states.lock().await;
        let Some(owner) = states
            .get_mut(&session.id)
            .and_then(|state| state.owner.as_mut())
        else {
            return false;
        };
        if owner.run_id != ownership.run_id
            || owner.finalizing
            || owner.registrations == 0
            || owner
                .session_created_at
                .is_some_and(|birth| birth != session.created_at)
        {
            return false;
        }
        owner.session_created_at = Some(session.created_at);
        true
    }

    /// Install only through the actual registered owner proof. Serialized
    /// observations never enter this slot. A different grant requires host
    /// revocation first; an equal retry is harmless.
    pub(crate) async fn bind_supervisor_loop_control(
        self: &Arc<Self>,
        ownership: &SessionRunOwnership,
        binding: bamboo_domain::ScopedLoopControlBinding,
        execution_cancel: tokio_util::sync::CancellationToken,
        host_stop: tokio_util::sync::CancellationToken,
    ) -> Result<(), bamboo_domain::SessionInboxError> {
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
            .ok_or_else(|| {
                bamboo_domain::SessionInboxError::InvalidClaim("scoped Loop Inbox missing".into())
            })?;
        binding
            .validate()
            .map_err(bamboo_domain::SessionInboxError::InvalidClaim)?;
        if execution_cancel.is_cancelled() || host_stop.is_cancelled() {
            return Err(bamboo_domain::SessionInboxError::InvalidClaim(
                "Loop owner is stopped".into(),
            ));
        }
        if !ownership.matches_router(self)
            || ownership.target_session_id != binding.target_session_id
            || ownership.run_id != binding.owner_run_id
        {
            return Err(bamboo_domain::SessionInboxError::InvalidClaim(
                "Loop owner proof mismatch".into(),
            ));
        }
        let _publication = self.lock_publication(&binding.target_session_id).await;
        let mut states = self.states.lock().await;
        let owner = states
            .get_mut(&binding.target_session_id)
            .and_then(|state| state.owner.as_mut())
            .filter(|owner| {
                Arc::ptr_eq(&owner.instance, &ownership.instance)
                    && owner.run_id == ownership.run_id
                    && !owner.finalizing
                    && owner.registrations > 0
                    && owner.session_created_at == Some(binding.target_created_at)
            })
            .ok_or_else(|| {
                bamboo_domain::SessionInboxError::InvalidClaim(
                    "Loop owner is no longer current".into(),
                )
            })?;
        // Tokens can be cancelled while waiting for the publication fence.
        if execution_cancel.is_cancelled() || host_stop.is_cancelled() {
            return Err(bamboo_domain::SessionInboxError::InvalidClaim(
                "Loop owner stopped during grant binding".into(),
            ));
        }
        if let Some(old) = &owner.scoped_loop {
            if old.binding != binding || old.stopped() {
                return Err(bamboo_domain::SessionInboxError::InvalidClaim(
                    "different or stopped Loop grant already bound".into(),
                ));
            }
            // Idempotency must not replace the original stop/cancel tokens.
            return Ok(());
        }
        let runtime: Arc<dyn SessionActivationPort> = self.clone();
        if !inbox
            .bind_scoped_transport_runtime(Arc::downgrade(&runtime), self.runtime_instance.clone())
        {
            return Err(bamboo_domain::SessionInboxError::InvalidClaim(
                "scoped Inbox belongs to another live runtime or is unsupported".into(),
            ));
        }
        owner.scoped_loop = Some(SupervisorLoopGrant {
            binding,
            execution_cancel,
            host_stop,
        });
        Ok(())
    }

    /// Host revocation shares the target publication fence with physical
    /// writes. It does not stop another run or retain a grant after owner exit.
    pub async fn revoke_supervisor_loop_control(
        &self,
        target: &str,
        grant_id: &uuid::Uuid,
    ) -> bool {
        let _publication = self.lock_publication(target).await;
        let mut states = self.states.lock().await;
        let Some(owner) = states
            .get_mut(target)
            .and_then(|state| state.owner.as_mut())
        else {
            return false;
        };
        if owner
            .scoped_loop
            .as_ref()
            .is_some_and(|grant| grant.binding.grant_id == *grant_id)
        {
            owner.scoped_loop = None;
            true
        } else {
            false
        }
    }

    async fn register_run_with_birth(
        self: &Arc<Self>,
        target_session_id: &str,
        run_id: &str,
        birth: Option<DateTime<Utc>>,
    ) -> Result<SessionRunRegistration, SessionRunRegistrationError> {
        loop {
            let (notifications, reservation_wait) = {
                let _publication = self.lock_publication(target_session_id).await;
                let mut states = self.states.lock().await;
                let state = states.entry(target_session_id.to_string()).or_default();
                match state.owner.as_mut() {
                    Some(owner)
                        if owner.run_id == run_id
                            && owner.registrations == 0
                            && !owner.finalizing =>
                    {
                        // `dispatch_reserved` publishes the exact owner before
                        // making the task runnable. The task converts that
                        // placeholder into the one live registration here.
                        if owner
                            .session_created_at
                            .is_some_and(|existing| birth.is_some_and(|birth| existing != birth))
                        {
                            return Err(SessionRunRegistrationError::OwnerCollision {
                                target_session_id: target_session_id.into(),
                                existing_run_id: owner.run_id.clone(),
                                attempted_run_id: run_id.into(),
                            });
                        }
                        if birth.is_some() {
                            owner.session_created_at = birth;
                        }
                        owner.registrations = 1;
                        (
                            Some((
                                state.notify.subscribe(),
                                state
                                    .owner
                                    .as_ref()
                                    .expect("registered owner")
                                    .instance
                                    .clone(),
                            )),
                            None,
                        )
                    }
                    Some(owner) => {
                        return Err(SessionRunRegistrationError::OwnerCollision {
                            target_session_id: target_session_id.to_string(),
                            existing_run_id: owner.run_id.clone(),
                            attempted_run_id: run_id.to_string(),
                        });
                    }
                    None if state.activation_reserved => {
                        // The router's two-phase activation already owns the
                        // right to publish the next exact owner. A direct/manual
                        // entry must wait for that reservation to publish or
                        // roll back; superseding its token can strand a raw
                        // external runner behind a phantom router owner.
                        (None, Some(state.activation_epoch.subscribe()))
                    }
                    None => {
                        state.owner = Some(ActiveOwner {
                            instance: Arc::new(()),
                            run_id: run_id.to_string(),
                            session_created_at: birth,
                            finalizing: false,
                            registrations: 1,
                            child_completions_need_successor: false,
                            delivery_sink: None,
                            scoped_loop: None,
                        });
                        (
                            Some((
                                state.notify.subscribe(),
                                state
                                    .owner
                                    .as_ref()
                                    .expect("registered owner")
                                    .instance
                                    .clone(),
                            )),
                            None,
                        )
                    }
                }
            };

            if let Some(mut reservation_wait) = reservation_wait {
                let _ = reservation_wait.changed().await;
                continue;
            }
            let (notifications, instance) =
                notifications.expect("registered owner has a receiver and instance");
            return Ok(SessionRunRegistration {
                instance,
                router: self.clone(),
                target_session_id: target_session_id.to_string(),
                run_id: run_id.to_string(),
                notifications: Some(notifications),
                abort_cleanup: None,
                scoped_transport_cleanup: None,
                quarantine_on_drop: false,
                tool_suspension_observation: None,
                selected_input_wakes: None,
                armed: true,
            });
        }
    }

    /// Bind an external actor driver to the current logical-session owner.
    ///
    /// Returns the active run id used to correlate every forwarded claim and
    /// confirmation. A pending generation is pushed immediately, closing the
    /// delivery-before-bind race without making this in-memory signal durable.
    pub async fn attach_delivery_sink(
        &self,
        target_session_id: &str,
        sink: mpsc::UnboundedSender<u64>,
    ) -> Option<String> {
        let mut states = self.states.lock().await;
        let state = states.get_mut(target_session_id)?;
        let owner = state.owner.as_mut()?;
        if owner.finalizing {
            return None;
        }
        owner.delivery_sink = Some(sink.clone());
        let run_id = owner.run_id.clone();
        let delivery_generation = state
            .latest_generation
            .max(state.latest_delivery_generation);
        if delivery_generation > 0 && sink.send(delivery_generation).is_err() {
            owner.delivery_sink = None;
            return None;
        }
        Some(run_id)
    }

    /// Remove a driver only when it still belongs to the same activation run.
    /// A stale driver can therefore never unbind its successor.
    pub async fn detach_delivery_sink(&self, target_session_id: &str, run_id: &str) {
        let mut states = self.states.lock().await;
        let Some(state) = states.get_mut(target_session_id) else {
            return;
        };
        let Some(owner) = state.owner.as_mut() else {
            return;
        };
        if owner.run_id == run_id {
            owner.delivery_sink = None;
        }
    }

    /// True only while this exact activation run remains the logical owner.
    pub async fn owns_run(&self, target_session_id: &str, run_id: &str) -> bool {
        let states = self.states.lock().await;
        states
            .get(target_session_id)
            .and_then(|state| state.owner.as_ref())
            .is_some_and(|owner| owner.run_id == run_id && !owner.finalizing)
    }

    /// Mark the current run as finalizing before its runner slot becomes
    /// available. Deliveries racing this interval are retained in
    /// `latest_generation` and handed to one successor by
    /// [`finish_finalization`](Self::finish_finalization).
    pub async fn begin_finalization(&self, target_session_id: &str, run_id: &str) {
        let _publication = self.lock_publication(target_session_id).await;
        let mut states = self.states.lock().await;
        let state = states.entry(target_session_id.to_string()).or_default();
        match state.owner.as_mut() {
            Some(owner) if owner.run_id == run_id => owner.finalizing = true,
            Some(_) => {}
            None => {
                state.owner = Some(ActiveOwner {
                    instance: Arc::new(()),
                    run_id: run_id.to_string(),
                    session_created_at: None,
                    finalizing: true,
                    registrations: 0,
                    child_completions_need_successor: false,
                    delivery_sink: None,
                    scoped_loop: None,
                });
            }
        }
    }

    /// Close selection and notification atomically under the original router
    /// owner lock. A producer arriving afterwards sees no owner and reserves
    /// its own activation; a coalesced earlier notification retains the normal
    /// finalization/recovery path, including Child/Bash coordinator wakeups.
    async fn release_selected_if_unnotified(
        &self,
        target_session_id: &str,
        run_id: &str,
        wakes: &watch::Receiver<u64>,
    ) -> bool {
        let _publication = self.lock_publication(target_session_id).await;
        let mut states = self.states.lock().await;
        let Some(state) = states.get_mut(target_session_id) else {
            return true;
        };
        if !state
            .owner
            .as_ref()
            .is_some_and(|owner| owner.run_id == run_id)
        {
            return true;
        }
        if wakes.has_changed().unwrap_or(false) {
            return false;
        }
        state.owner = None;
        state.owner_completion_epoch = state.owner_completion_epoch.wrapping_add(1);
        if state.latest_generation == 0
            && !state.activation_reserved
            && state.notify.receiver_count() <= 1
            && state.activation_epoch.receiver_count() == 0
        {
            states.remove(target_session_id);
        }
        true
    }

    async fn cleanup_abandoned_registration(
        self: &Arc<Self>,
        target_session_id: &str,
        run_id: &str,
        selected_input_wakes: Option<watch::Receiver<u64>>,
    ) {
        if let Some(wakes) = selected_input_wakes {
            if self
                .release_selected_if_unnotified(target_session_id, run_id, &wakes)
                .await
            {
                return;
            }
        }
        {
            let _publication = self.lock_publication(target_session_id).await;
            let mut states = self.states.lock().await;
            let Some(state) = states.get_mut(target_session_id) else {
                return;
            };
            let Some(owner) = state.owner.as_mut() else {
                return;
            };
            if owner.run_id != run_id {
                return;
            }
            owner.registrations = 0;
            owner.finalizing = true;
        }

        // Delivery commits and its activation watermark are durable before the
        // producer asks the in-memory router to wake an owner. If that producer
        // or this execution is cancelled between those steps, recover the
        // authoritative eligible prefix rather than trusting only RAM.
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let (durable_generation, released_prefix) = match inbox {
            Some(inbox) => match inbox.inspect(target_session_id).await {
                Ok(backlog) if backlog.activation_pending() => (
                    backlog.activation_generation,
                    backlog.coordinator_generation,
                ),
                Ok(_) => (0, 0),
                Err(error) => {
                    tracing::warn!(
                        %target_session_id,
                        %run_id,
                        %error,
                        "failed to reconcile durable SessionInbox generation for abandoned run"
                    );
                    (0, 0)
                }
            },
            None => (0, 0),
        };

        #[cfg(test)]
        self.pause_after_terminal_inspection().await;
        let (reservation_to_dispatch, previous_high) = {
            let _publication = self.lock_publication(target_session_id).await;
            let mut states = self.states.lock().await;
            let Some(state) = states.get_mut(target_session_id) else {
                return;
            };
            if !state.owner.as_ref().is_some_and(|owner| {
                owner.run_id == run_id && owner.finalizing && owner.registrations == 0
            }) {
                return;
            }
            state.latest_generation = state.latest_generation.max(durable_generation);
            let previous_high = state.last_dispatched_generation;
            state.owner = None;
            state.owner_completion_epoch = state.owner_completion_epoch.wrapping_add(1);
            if (state.latest_generation > state.last_dispatched_generation
                || released_prefix > state.last_dispatched_coordinator_generation)
                && !state.activation_reserved
            {
                let generation = state.latest_generation;
                let token = reserve_activation_token(state);
                (Some((generation, token)), previous_high)
            } else {
                if state.latest_generation == 0
                    && !state.activation_reserved
                    && state.notify.receiver_count() == 0
                    && state.activation_epoch.receiver_count() == 0
                {
                    states.remove(target_session_id);
                }
                (None, previous_high)
            }
        };

        if let Some((generation, token)) = reservation_to_dispatch {
            if let Err(error) = self
                .dispatch_reserved(target_session_id, generation, token)
                .await
            {
                tracing::error!(
                    %target_session_id,
                    %run_id,
                    %error,
                    "failed to reserve successor for abandoned SessionInbox owner"
                );
            }
        } else {
            // A precise grant can race the pre-lock inspection while the
            // producer still observes this owner as finalizing. Re-read after
            // releasing the owner even when that earlier snapshot was empty.
            if let Err(error) = self
                .reconcile_message_below(target_session_id, previous_high)
                .await
            {
                tracing::warn!(%target_session_id, %error,
                    "failed to reconcile older eligible message after abandoned owner");
            }
        }
    }

    /// Release the terminal owner and, if the durable transcript cursor is
    /// behind a concurrently delivered inbox generation, reserve and launch
    /// exactly one successor using the injected real runtime adapter.
    pub async fn finish_finalization(
        &self,
        target_session_id: &str,
        run_id: &str,
        admitted_generation: u64,
    ) -> Result<Option<SessionActivationDisposition>, SessionActivationError> {
        // Deferred guidance may precede a later admitted message. A maximum
        // transcript cursor alone cannot prove that this authorized queue is empty.
        let inbox = self
            .inbox
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let durable_pending = match inbox {
            Some(inbox) => Some(
                inbox
                    .inspect(target_session_id)
                    .await
                    .map_err(|error| SessionActivationError::Internal(error.to_string()))?,
            ),
            None => None,
        };
        #[cfg(test)]
        self.pause_after_terminal_inspection().await;
        let (reservation_to_dispatch, previous_high) = {
            let _publication = self.lock_publication(target_session_id).await;
            let mut states = self.states.lock().await;
            let state = states.entry(target_session_id.to_string()).or_default();
            let previous_high = state.last_dispatched_generation;
            if state
                .owner
                .as_ref()
                .is_some_and(|owner| owner.run_id != run_id)
            {
                return Ok(None);
            }
            if state.owner.take().is_some() {
                state.owner_completion_epoch = state.owner_completion_epoch.wrapping_add(1);
            }
            let pending = durable_pending
                .as_ref()
                .is_some_and(|backlog| backlog.activation_pending());
            let released_prefix = durable_pending
                .as_ref()
                .filter(|_| pending)
                .map_or(0, |backlog| backlog.coordinator_generation);
            if let Some(backlog) = durable_pending.as_ref() {
                state.latest_generation =
                    state.latest_generation.max(backlog.activation_generation);
            }
            if (pending || state.latest_generation > admitted_generation)
                && (state.latest_generation > state.last_dispatched_generation
                    || released_prefix > state.last_dispatched_coordinator_generation)
                && !state.activation_reserved
            {
                let generation = state.latest_generation;
                let token = reserve_activation_token(state);
                (Some((generation, token)), previous_high)
            } else {
                // Both execution paths drop their safe-point receiver before
                // calling finish_finalization. Once the durable cursor has
                // caught up and no reservation exists, this target carries no
                // live routing state and must not remain in AppState forever.
                if state.latest_generation <= admitted_generation
                    && !pending
                    && state.owner.is_none()
                    && !state.activation_reserved
                    && state.notify.receiver_count() == 0
                    && state.activation_epoch.receiver_count() == 0
                {
                    states.remove(target_session_id);
                }
                (None, previous_high)
            }
        };

        match reservation_to_dispatch {
            Some((generation, token)) => self
                .dispatch_reserved(target_session_id, generation, token)
                .await
                .map(Some),
            // Keep the prior high even if the empty pre-lock snapshot allowed
            // state eviction. A late older grant still needs its one successor.
            None => {
                self.reconcile_message_below(target_session_id, previous_high)
                    .await
            }
        }
    }

    pub async fn subscribe(&self, target_session_id: &str) -> watch::Receiver<u64> {
        let mut states = self.states.lock().await;
        states
            .entry(target_session_id.to_string())
            .or_default()
            .notify
            .subscribe()
    }

    /// Release an activation attempt whose caller was cancelled or panicked.
    ///
    /// Finalization-racing producers already received a coalesced success while
    /// the old owner was visible, so no external waiter remains to retry after
    /// the reservation token is released. The first abandoned attempt therefore
    /// gets one detached, router-level retry for the newest still-undispatched
    /// generation. That retry is deliberately bounded: its own Drop releases
    /// the token but does not recursively hot-loop a broken spawner.
    async fn recover_cancelled_reservation(
        &self,
        target_session_id: &str,
        reservation_token: u64,
        recover_on_drop: bool,
    ) {
        let previous_prefix = {
            let mut states = self.states.lock().await;
            let Some(state) = states.get_mut(target_session_id) else {
                return;
            };
            if !release_activation_token(state, reservation_token) || !recover_on_drop {
                return;
            }
            state.last_dispatched_coordinator_generation
        };
        let released_prefix = self
            .released_pending_generation(target_session_id, previous_prefix)
            .await
            .unwrap_or(0);
        let reservation_to_dispatch = {
            let mut states = self.states.lock().await;
            let Some(state) = states.get_mut(target_session_id) else {
                return;
            };
            if state.owner.is_none()
                && (state.latest_generation > state.last_dispatched_generation
                    || released_prefix > state.last_dispatched_coordinator_generation)
                && !state.activation_reserved
            {
                let generation = state.latest_generation;
                let token = reserve_activation_token(state);
                Some((generation, token))
            } else {
                None
            }
        };

        if let Some((generation, token)) = reservation_to_dispatch {
            if let Err(error) = self
                .dispatch_reserved_with_recovery(target_session_id, generation, token, false, None)
                .await
            {
                tracing::error!(
                    %target_session_id,
                    %error,
                    "failed bounded retry after cancelled SessionInbox activation reservation"
                );
            }
        }
    }

    async fn dispatch_reserved(
        &self,
        target_session_id: &str,
        generation: u64,
        reservation_token: u64,
    ) -> Result<SessionActivationDisposition, SessionActivationError> {
        self.dispatch_reserved_with_recovery(
            target_session_id,
            generation,
            reservation_token,
            true,
            None,
        )
        .await
    }

    async fn dispatch_reserved_with_recovery(
        &self,
        target_session_id: &str,
        generation: u64,
        reservation_token: u64,
        recover_on_drop: bool,
        recovery: Option<(SessionInboxWakeCandidate, DateTime<Utc>)>,
    ) -> Result<SessionActivationDisposition, SessionActivationError> {
        let mut lease = ActivationReservationLease::new(
            self.clone(),
            target_session_id,
            reservation_token,
            recover_on_drop,
        );
        let Some(spawner) = self.spawner.read().await.clone() else {
            let mut states = self.states.lock().await;
            if let Some(state) = states.get_mut(target_session_id) {
                release_activation_token(state, reservation_token);
            }
            lease.disarm();
            return Err(SessionActivationError::Internal(
                "session activation spawner is not configured".to_string(),
            ));
        };

        // Sample before the spawner admits/launches its run. A coordinator
        // release arriving later remains fresh work for finalization.
        let coordinator_generation = self.coordinator_generation(target_session_id).await?;

        let outcome = spawner
            .reserve_activation(target_session_id, generation)
            .await;
        if let Ok(SessionActivationReserveOutcome::Reserved(launch)) = &outcome {
            lease.wait_for_rollback(launch.rollback_completion());
        }
        match outcome {
            Ok(SessionActivationReserveOutcome::Reserved(launch)) => {
                let run_id = launch.run_id.clone();
                {
                    let _publication = self.lock_publication(target_session_id).await;
                    let mut states = self.states.lock().await;
                    let state = states.entry(target_session_id.to_string()).or_default();
                    if !release_activation_token(state, reservation_token) {
                        // Cancellation recovery or a newer exact reservation
                        // may have superseded this attempt while its spawner
                        // was preparing. Direct/manual registration is
                        // serialized behind `activation_reserved`, so it
                        // cannot create an unrelated owner in this window.
                        // Dropping the unlaunched value rolls back its external
                        // slot.
                        lease.disarm();
                        return if state.owner.is_some() {
                            Ok(SessionActivationDisposition::ActiveNotified)
                        } else {
                            Err(SessionActivationError::Internal(
                                "session activation reservation was superseded".to_string(),
                            ))
                        };
                    }
                    state.owner = Some(ActiveOwner {
                        instance: Arc::new(()),
                        run_id,
                        session_created_at: None,
                        finalizing: false,
                        registrations: 0,
                        child_completions_need_successor: false,
                        delivery_sink: None,
                        scoped_loop: None,
                    });
                    state.last_dispatched_generation =
                        state.last_dispatched_generation.max(generation);
                    state.last_dispatched_coordinator_generation = state
                        .last_dispatched_coordinator_generation
                        .max(coordinator_generation);
                    if let Some((candidate, now)) = recovery {
                        record_recovery_attempt(state, candidate, now, true);
                    }
                }
                lease.disarm();
                // The existing runner slot is already reserved. Publish owner
                // state first, then make the task runnable exactly once.
                launch.launch();
                Ok(SessionActivationDisposition::ActivationReserved)
            }
            Ok(SessionActivationReserveOutcome::AlreadyRunning { run_id }) => {
                let _publication = self.lock_publication(target_session_id).await;
                let mut states = self.states.lock().await;
                let state = states.entry(target_session_id.to_string()).or_default();
                if !release_activation_token(state, reservation_token) {
                    lease.disarm();
                    return Ok(SessionActivationDisposition::ActiveNotified);
                }
                state.owner = Some(ActiveOwner {
                    instance: Arc::new(()),
                    run_id,
                    session_created_at: None,
                    finalizing: false,
                    registrations: 0,
                    child_completions_need_successor: false,
                    delivery_sink: None,
                    scoped_loop: None,
                });
                state.notify.send_replace(generation);
                if let Some((candidate, now)) = recovery {
                    record_recovery_attempt(state, candidate, now, true);
                }
                lease.disarm();
                Ok(SessionActivationDisposition::ActiveNotified)
            }
            Ok(SessionActivationReserveOutcome::NoWork) => {
                let mut states = self.states.lock().await;
                if let Some(state) = states.get_mut(target_session_id) {
                    if release_activation_token(state, reservation_token) {
                        if let Some((candidate, now)) = recovery {
                            record_recovery_attempt(state, candidate, now, false);
                        }
                    }
                }
                lease.disarm();
                Ok(SessionActivationDisposition::ActivationCoalesced)
            }
            Ok(SessionActivationReserveOutcome::NotFound) => {
                let _publication = self.lock_publication(target_session_id).await;
                let mut states = self.states.lock().await;
                if states
                    .get(target_session_id)
                    .is_some_and(|state| state.activation_token == reservation_token)
                {
                    states.remove(target_session_id);
                }
                lease.disarm();
                Err(SessionActivationError::TargetNotFound(
                    target_session_id.to_string(),
                ))
            }
            Err(error) => {
                let mut states = self.states.lock().await;
                if let Some(state) = states.get_mut(target_session_id) {
                    release_activation_token(state, reservation_token);
                }
                lease.disarm();
                Err(error)
            }
        }
    }
}

#[async_trait]
impl SessionActivationPort for SessionActivationRouter {
    fn scoped_transport_runtime_instance(&self) -> Option<Arc<()>> {
        Some(self.runtime_instance.clone())
    }

    fn retain_closed_scoped_transport_blocking(
        &self,
        binding: &bamboo_domain::ScopedLoopControlBinding,
    ) -> Result<Arc<dyn bamboo_domain::SessionRunDeliveryGuard>, bamboo_domain::SessionRunConflict>
    {
        let publication = self
            .publication_fence(&binding.target_session_id)
            .blocking_lock_owned();
        let states = self.states.blocking_lock();
        let matches = states
            .get(&binding.target_session_id)
            .and_then(|state| state.owner.as_ref())
            .is_some_and(|owner| {
                owner.finalizing
                    && owner.registrations > 0
                    && owner.run_id == binding.owner_run_id
                    && owner.session_created_at == Some(binding.target_created_at)
                    && owner
                        .scoped_loop
                        .as_ref()
                        .is_none_or(|grant| grant.binding.execution_id == binding.execution_id)
            });
        if !matches {
            return Err(bamboo_domain::SessionRunConflict::unsupported(
                &binding.owner_run_id,
            ));
        }
        drop(states);
        Ok(Arc::new(ClosedLoopTransportGuard(
            ExpectedRunDeliveryGuard {
                target_session_id: binding.target_session_id.clone(),
                session_created_at: binding.target_created_at,
                run_id: binding.owner_run_id.clone(),
                states: self.states.clone(),
                _publication: publication,
            },
        )))
    }

    fn retain_expected_run_blocking(
        &self,
        target_session_id: &str,
        target_created_at: DateTime<Utc>,
        expected_run_id: &str,
    ) -> Result<Arc<dyn bamboo_domain::SessionRunDeliveryGuard>, bamboo_domain::SessionRunConflict>
    {
        use bamboo_domain::{SessionRunConflict, SessionRunConflictReason};
        // Only this target is retained through disk publication. Every owner
        // installation/release/finalization takes the same target fence first.
        let publication = self
            .publication_fence(target_session_id)
            .blocking_lock_owned();
        let states = self.states.blocking_lock();
        let owner = states
            .get(target_session_id)
            .and_then(|state| state.owner.as_ref());
        let reason = match owner {
            None => Some(SessionRunConflictReason::NoActiveRun),
            Some(owner)
                if owner
                    .session_created_at
                    .is_some_and(|birth| birth != target_created_at) =>
            {
                Some(SessionRunConflictReason::SessionBirthChanged)
            }
            Some(owner) if owner.finalizing => Some(SessionRunConflictReason::Finalizing),
            Some(owner) if owner.registrations == 0 => {
                Some(SessionRunConflictReason::NotRegistered)
            }
            Some(owner) if owner.session_created_at.is_none() => {
                Some(SessionRunConflictReason::UnboundLifetime)
            }
            Some(owner) if owner.run_id != expected_run_id => {
                Some(SessionRunConflictReason::RunChanged)
            }
            Some(_) => None,
        };
        if let Some(reason) = reason {
            return Err(SessionRunConflict {
                reason,
                expected_run_id: expected_run_id.into(),
                observed_run_id: owner
                    .filter(|owner| owner.session_created_at == Some(target_created_at))
                    .map(|owner| owner.run_id.clone()),
            });
        }
        Ok(Arc::new(ExpectedRunDeliveryGuard {
            target_session_id: target_session_id.into(),
            session_created_at: target_created_at,
            run_id: expected_run_id.into(),
            states: self.states.clone(),
            _publication: publication,
        }))
    }

    async fn observe_supervisor_loop(
        &self,
        supervisor: &bamboo_domain::SupervisorReference,
        target: &str,
        expected_link_revision: Option<u64>,
        action: bamboo_domain::LoopControlAction,
    ) -> Result<bamboo_domain::ScopedLoopControlBinding, bamboo_domain::SessionInboxError> {
        let _publication = self.lock_publication(target).await;
        let states = self.states.lock().await;
        let owner = states
            .get(target)
            .and_then(|state| state.owner.as_ref())
            .filter(|owner| !owner.finalizing && owner.registrations > 0)
            .ok_or_else(|| {
                bamboo_domain::SessionInboxError::InvalidClaim("no live Loop owner".into())
            })?;
        let grant = owner
            .scoped_loop
            .as_ref()
            .filter(|grant| !grant.stopped())
            .ok_or_else(|| {
                bamboo_domain::SessionInboxError::InvalidClaim(
                    "host did not grant Supervisor Loop control".into(),
                )
            })?;
        let binding = &grant.binding;
        binding
            .validate()
            .map_err(bamboo_domain::SessionInboxError::InvalidClaim)?;
        if binding.supervisor != *supervisor
            || binding.target_session_id != target
            || owner.run_id != binding.owner_run_id
            || owner.session_created_at != Some(binding.target_created_at)
            || !binding.allowed_actions.contains(&action)
            || expected_link_revision.is_some_and(|revision| revision != binding.link_revision)
            || (expected_link_revision.is_none()
                && action != bamboo_domain::LoopControlAction::Status)
        {
            return Err(bamboo_domain::SessionInboxError::InvalidClaim(
                "live Loop grant observation mismatch".into(),
            ));
        }
        Ok(binding.clone())
    }

    fn retain_supervisor_loop_blocking(
        &self,
        binding: &bamboo_domain::ScopedLoopControlBinding,
    ) -> Result<Arc<dyn bamboo_domain::SessionRunDeliveryGuard>, bamboo_domain::SessionRunConflict>
    {
        use bamboo_domain::{SessionRunConflict, SessionRunConflictReason};
        let publication = self
            .publication_fence(&binding.target_session_id)
            .blocking_lock_owned();
        let states = self.states.blocking_lock();
        let owner = states
            .get(&binding.target_session_id)
            .and_then(|state| state.owner.as_ref());
        if binding.validate().is_err()
            || owner.is_none_or(|owner| {
                owner.finalizing
                    || owner.registrations == 0
                    || owner.run_id != binding.owner_run_id
                    || owner.session_created_at != Some(binding.target_created_at)
                    || owner
                        .scoped_loop
                        .as_ref()
                        .is_none_or(|grant| grant.stopped() || grant.binding != *binding)
            })
        {
            return Err(SessionRunConflict {
                reason: SessionRunConflictReason::RunChanged,
                expected_run_id: binding.owner_run_id.clone(),
                observed_run_id: owner
                    .filter(|owner| owner.session_created_at == Some(binding.target_created_at))
                    .map(|owner| owner.run_id.clone()),
            });
        }
        let grant = owner
            .and_then(|owner| owner.scoped_loop.as_ref())
            .expect("validated Loop grant")
            .clone();
        Ok(Arc::new(SupervisorLoopDeliveryGuard {
            inner: ExpectedRunDeliveryGuard {
                target_session_id: binding.target_session_id.clone(),
                session_created_at: binding.target_created_at,
                run_id: binding.owner_run_id.clone(),
                states: self.states.clone(),
                _publication: publication,
            },
            grant,
        }))
    }

    async fn notify_active_delivery(&self, target_session_id: &str, inbox_generation: u64) -> bool {
        let mut states = self.states.lock().await;
        let Some(state) = states.get_mut(target_session_id) else {
            return false;
        };
        let Some(owner) = state.owner.as_mut().filter(|owner| !owner.finalizing) else {
            return false;
        };
        state.latest_delivery_generation = state.latest_delivery_generation.max(inbox_generation);
        state.notify.send_replace(inbox_generation);
        if owner
            .delivery_sink
            .as_ref()
            .is_some_and(|sink| sink.send(inbox_generation).is_err())
        {
            owner.delivery_sink = None;
        }
        true
    }

    async fn request_activation(
        &self,
        target_session_id: &str,
        inbox_generation: u64,
    ) -> Result<SessionActivationDisposition, SessionActivationError> {
        let previous_prefix = {
            let states = self.states.lock().await;
            states
                .get(target_session_id)
                .filter(|state| inbox_generation <= state.last_dispatched_generation)
                .map(|state| state.last_dispatched_coordinator_generation)
        };
        let released_prefix = match previous_prefix {
            Some(prefix) => {
                self.released_pending_generation(target_session_id, prefix)
                    .await?
            }
            None => 0,
        };
        loop {
            let (reservation_wait, reservation_token) = {
                let mut states = self.states.lock().await;
                let state = states.entry(target_session_id.to_string()).or_default();
                state.latest_generation = state.latest_generation.max(inbox_generation);
                if let Some(owner) = state.owner.as_mut() {
                    if !owner.finalizing {
                        state.notify.send_replace(inbox_generation);
                        if owner
                            .delivery_sink
                            .as_ref()
                            .is_some_and(|sink| sink.send(inbox_generation).is_err())
                        {
                            owner.delivery_sink = None;
                        }
                        return Ok(SessionActivationDisposition::ActiveNotified);
                    }
                    return Ok(SessionActivationDisposition::ActivationCoalesced);
                }
                if inbox_generation <= state.last_dispatched_generation
                    && released_prefix <= state.last_dispatched_coordinator_generation
                {
                    drop(states);
                    return self
                        .reconcile_older_message(target_session_id)
                        .await
                        .map(|result| {
                            result.unwrap_or(SessionActivationDisposition::ActivationCoalesced)
                        });
                }
                if state.activation_reserved {
                    (Some(state.activation_epoch.subscribe()), None)
                } else {
                    let token = reserve_activation_token(state);
                    (None, Some(token))
                }
            };

            if let Some(mut reservation_wait) = reservation_wait {
                // A coalesced caller does not claim success until the preceding
                // reservation publishes an owner or releases its slot. If that
                // attempt returns NoWork/error, this caller wakes and reserves
                // its own (newer) generation, so no durable delivery is left
                // behind a false-positive coalesced response.
                if reservation_wait.changed().await.is_err() {
                    return Err(SessionActivationError::TargetNotFound(
                        target_session_id.to_string(),
                    ));
                }
                continue;
            }

            let reservation_token =
                reservation_token.expect("non-waiting activation owns a reservation token");
            return self
                .dispatch_reserved_with_recovery(
                    target_session_id,
                    inbox_generation,
                    reservation_token,
                    false,
                    None,
                )
                .await;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::sync::{Barrier, Notify};

    #[tokio::test]
    async fn wake_recovery_retries_same_candidate_only_after_owner_completion_and_backoff() {
        use bamboo_domain::{
            Session, SessionActivationPolicy, SessionInboxLimits, SessionMessageEnvelope, Storage,
        };
        use bamboo_storage::{FileSessionInbox, SessionStoreV2};

        let temp = tempfile::TempDir::new().unwrap();
        let store = Arc::new(SessionStoreV2::new(temp.path().into()).await.unwrap());
        store
            .save_session(&Session::new("target", "model"))
            .await
            .unwrap();
        let inbox = Arc::new(FileSessionInbox::new(store, SessionInboxLimits::default()));
        inbox
            .deliver_with_activation_intent(
                &SessionMessageEnvelope::user_input("target", "still pending"),
                SessionActivationPolicy::RespectSpecificWait,
                None,
            )
            .await
            .unwrap();
        let router = SessionActivationRouter::new();
        router.set_inbox(inbox);
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let now = Utc::now();
        assert_eq!(
            router
                .reconcile_wake("target", now)
                .await
                .unwrap()
                .disposition,
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(
            router
                .reconcile_wake("target", now)
                .await
                .unwrap()
                .disposition,
            Some(SessionActivationDisposition::ActiveNotified)
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        let mut registration = router.register_run("target", "run-1").await.unwrap();
        registration.begin_finalization().await;
        assert_eq!(registration.finish(0).await.unwrap(), None);

        let deferred = router
            .reconcile_wake("target", now + Duration::seconds(29))
            .await
            .unwrap();
        assert_eq!(deferred.disposition, None);
        assert_eq!(deferred.next_due_at, Some(now + INITIAL_RECOVERY_BACKOFF));
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(
            router
                .reconcile_wake("target", now + INITIAL_RECOVERY_BACKOFF)
                .await
                .unwrap()
                .disposition,
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn wake_recovery_waits_for_exact_owned_lease_expiry() {
        use bamboo_domain::{
            Session, SessionActivationPolicy, SessionInboxLeaseRequest, SessionInboxLimits,
            SessionMessageEnvelope, Storage,
        };
        use bamboo_storage::{FileSessionInbox, SessionStoreV2};

        let temp = tempfile::TempDir::new().unwrap();
        let store = Arc::new(SessionStoreV2::new(temp.path().into()).await.unwrap());
        store
            .save_session(&Session::new("target", "model"))
            .await
            .unwrap();
        let inbox = Arc::new(FileSessionInbox::new(store, SessionInboxLimits::default()));
        inbox
            .deliver_with_activation_intent(
                &SessionMessageEnvelope::user_input("target", "unacknowledged"),
                SessionActivationPolicy::RespectSpecificWait,
                None,
            )
            .await
            .unwrap();
        let router = SessionActivationRouter::new();
        router.set_inbox(inbox.clone());
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let now = Utc::now();
        assert_eq!(
            router
                .reconcile_wake("target", now)
                .await
                .unwrap()
                .disposition,
            Some(SessionActivationDisposition::ActivationReserved)
        );
        let claim = inbox
            .claim_owned(
                "target",
                1,
                None,
                &SessionInboxLeaseRequest {
                    consumer: bamboo_domain::SessionInboxConsumerId::new(),
                    now,
                    duration: Duration::seconds(10),
                },
            )
            .await
            .unwrap()
            .remove(0);
        let mut registration = router.register_run("target", "run-1").await.unwrap();
        registration.begin_finalization().await;
        assert_eq!(registration.finish(0).await.unwrap(), None);
        let deferred = router
            .reconcile_wake("target", claim.lease.expires_at - Duration::seconds(1))
            .await
            .unwrap();
        assert_eq!(deferred.disposition, None);
        assert_eq!(deferred.next_due_at, Some(claim.lease.expires_at));
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(
            router
                .reconcile_wake("target", claim.lease.expires_at)
                .await
                .unwrap()
                .disposition,
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn older_staged_release_after_immediate_ack_dispatches_once_without_poison_hot_loop() {
        use bamboo_domain::{
            Session, SessionActivationPolicy, SessionInboxLimits, SessionMessageEnvelope, Storage,
        };
        use bamboo_storage::{FileSessionInbox, SessionStoreV2};
        async fn release(
            inbox: &FileSessionInbox,
            receipt: &bamboo_domain::SessionInboxReceipt,
            precise: bool,
        ) {
            if precise {
                inbox
                    .mark_message_activation_eligible(
                        "parent",
                        receipt,
                        SessionActivationPolicy::InterruptSpecificWait,
                    )
                    .await
                    .unwrap();
                assert_eq!(
                    inbox
                        .coordinator_activation_generation("parent")
                        .await
                        .unwrap(),
                    0
                );
            } else {
                inbox
                    .mark_activation_eligible(
                        "parent",
                        receipt.generation,
                        SessionActivationPolicy::RespectSpecificWait,
                    )
                    .await
                    .unwrap();
            }
        }
        for (release_during_finalization, precise) in
            [(false, false), (true, false), (false, true), (true, true)]
        {
            let temp = tempfile::TempDir::new().unwrap();
            let store = Arc::new(SessionStoreV2::new(temp.path().into()).await.unwrap());
            store
                .save_session(&Session::new("parent", "model"))
                .await
                .unwrap();
            let inbox = Arc::new(FileSessionInbox::new(
                store.clone(),
                SessionInboxLimits::default(),
            ));
            let staged = SessionMessageEnvelope::user_input("parent", "staged result");
            let first = inbox.deliver(&staged).await.unwrap();
            let immediate = SessionMessageEnvelope::user_input("parent", "immediate steer");
            let second = inbox
                .deliver_with_activation_intent(
                    &immediate,
                    SessionActivationPolicy::RespectSpecificWait,
                    None,
                )
                .await
                .unwrap();
            let reopened_store = Arc::new(SessionStoreV2::new(temp.path().into()).await.unwrap());
            let restarted = Arc::new(FileSessionInbox::new(
                reopened_store,
                SessionInboxLimits::default(),
            ));
            let router = SessionActivationRouter::new();
            router.set_inbox(restarted.clone());
            let spawner = spawner();
            router.set_spawner(spawner.clone()).await;
            // Keep the high-generation router state after an idle finalization
            // so the test exercises hole recovery rather than state eviction.
            let _observer = router.subscribe("parent").await;
            let backlog = restarted.inspect("parent").await.unwrap();
            assert_eq!(
                router
                    .request_activation("parent", backlog.activation_generation)
                    .await
                    .unwrap(),
                SessionActivationDisposition::ActivationReserved
            );
            let claims = restarted.claim("parent", 128).await.unwrap();
            assert_eq!(claims.len(), 1);
            assert_eq!(claims[0].generation, second.generation);
            restarted.ack("parent", &claims[0]).await.unwrap();
            let mut registration = router.register_run("parent", "run-1").await.unwrap();
            registration.begin_finalization().await;
            if release_during_finalization {
                release(&restarted, &first, precise).await;
                assert_eq!(
                    router
                        .request_activation("parent", first.generation)
                        .await
                        .unwrap(),
                    SessionActivationDisposition::ActivationCoalesced
                );
                assert_eq!(
                    registration.finish(second.generation).await.unwrap(),
                    Some(SessionActivationDisposition::ActivationReserved)
                );
            } else {
                assert_eq!(registration.finish(second.generation).await.unwrap(), None);
                release(&restarted, &first, precise).await;
                assert_eq!(
                    router
                        .request_activation("parent", first.generation)
                        .await
                        .unwrap(),
                    SessionActivationDisposition::ActivationReserved
                );
            }
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
            let claims = restarted.claim("parent", 128).await.unwrap();
            assert_eq!(claims.len(), 1);
            assert_eq!(claims[0].envelope.id, staged.id);
            // An execution leaving the same claim pending gets no unbounded
            // retry just because its delivery generation is below the high one.
            let mut registration = router.register_run("parent", "run-2").await.unwrap();
            registration.begin_finalization().await;
            assert_eq!(registration.finish(second.generation).await.unwrap(), None);
            assert_eq!(
                router
                    .request_activation("parent", first.generation)
                    .await
                    .unwrap(),
                SessionActivationDisposition::ActivationCoalesced
            );
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
            restarted.ack("parent", &claims[0]).await.unwrap();
        }
    }

    #[tokio::test]
    async fn precise_older_interrupt_below_released_prefix_reaches_one_successor() {
        use bamboo_domain::{
            Session, SessionActivationPolicy, SessionInboxLimits, SessionMessageEnvelope, Storage,
        };
        use bamboo_storage::{FileSessionInbox, SessionStoreV2};
        for with_older_sibling in [false, true] {
            let temp = tempfile::TempDir::new().unwrap();
            let store = Arc::new(SessionStoreV2::new(temp.path().into()).await.unwrap());
            store
                .save_session(&Session::new("parent", "model"))
                .await
                .unwrap();
            let inbox = Arc::new(FileSessionInbox::new(store, SessionInboxLimits::default()));
            let sibling = if with_older_sibling {
                Some(
                    inbox
                        .deliver(&SessionMessageEnvelope::user_input(
                            "parent",
                            "older Respect sibling",
                        ))
                        .await
                        .unwrap(),
                )
            } else {
                None
            };
            let older = inbox
                .deliver(&SessionMessageEnvelope::user_input("parent", "older child"))
                .await
                .unwrap();
            let newer = inbox
                .deliver(&SessionMessageEnvelope::user_input("parent", "newer Bash"))
                .await
                .unwrap();
            inbox
                .mark_activation_eligible(
                    "parent",
                    newer.generation,
                    SessionActivationPolicy::RespectSpecificWait,
                )
                .await
                .unwrap();
            let router = SessionActivationRouter::new();
            router.set_inbox(inbox.clone());
            let spawner = spawner();
            router.set_spawner(spawner.clone()).await;
            router
                .request_activation("parent", newer.generation)
                .await
                .unwrap();
            let claims = inbox.claim("parent", 128).await.unwrap();
            assert_eq!(claims.len(), 2 + usize::from(with_older_sibling));
            let older_claim = claims
                .iter()
                .find(|claim| claim.envelope.id == older.id)
                .unwrap();
            assert_eq!(older_claim.generation, older.generation);
            assert_eq!(
                older_claim.activation_policy,
                SessionActivationPolicy::RespectSpecificWait
            );
            let newer_claim = claims
                .iter()
                .find(|claim| claim.envelope.id == newer.id)
                .unwrap();
            inbox.ack("parent", newer_claim).await.unwrap();
            let mut owner = router.register_run("parent", "run-1").await.unwrap();
            owner.begin_finalization().await;
            assert_eq!(owner.finish(newer.generation).await.unwrap(), None);
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);

            inbox
                .mark_message_activation_eligible(
                    "parent",
                    &older,
                    SessionActivationPolicy::InterruptSpecificWait,
                )
                .await
                .unwrap();
            let candidate = inbox
                .inspect_wake_readiness("parent", Utc::now())
                .await
                .unwrap()
                .ready
                .unwrap();
            assert_eq!(candidate.coordinator_generation, newer.generation);
            assert_eq!(
                candidate.id, older.id,
                "a Respect sibling cannot obscure the precise wake"
            );
            assert_eq!(
                candidate.coordinator_message_policy,
                Some(SessionActivationPolicy::InterruptSpecificWait)
            );
            assert_eq!(
                router
                    .request_activation("parent", older.generation)
                    .await
                    .unwrap(),
                SessionActivationDisposition::ActivationReserved
            );
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
            // Leaving the same exact item pending must retain bounded recovery.
            let mut successor = router.register_run("parent", "run-2").await.unwrap();
            successor.begin_finalization().await;
            assert_eq!(successor.finish(newer.generation).await.unwrap(), None);
            assert_eq!(
                router
                    .request_activation("parent", older.generation)
                    .await
                    .unwrap(),
                SessionActivationDisposition::ActivationCoalesced
            );
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
            inbox.ack("parent", older_claim).await.unwrap();
            if let Some(sibling) = sibling {
                let claim = claims
                    .iter()
                    .find(|claim| claim.envelope.id == sibling.id)
                    .unwrap();
                inbox.ack("parent", claim).await.unwrap();
            }
        }
    }

    #[tokio::test]
    async fn precise_older_grant_after_terminal_inspection_reaches_one_successor() {
        use bamboo_domain::{
            Session, SessionActivationPolicy, SessionInboxLimits, SessionMessageEnvelope, Storage,
        };
        use bamboo_storage::{FileSessionInbox, SessionStoreV2};
        for abandon in [false, true] {
            let temp = tempfile::TempDir::new().unwrap();
            let store = Arc::new(SessionStoreV2::new(temp.path().into()).await.unwrap());
            store
                .save_session(&Session::new("parent", "model"))
                .await
                .unwrap();
            let inbox = Arc::new(FileSessionInbox::new(store, SessionInboxLimits::default()));
            let older = inbox
                .deliver(&SessionMessageEnvelope::user_input(
                    "parent",
                    "staged child",
                ))
                .await
                .unwrap();
            let newer = inbox
                .deliver_with_activation_intent(
                    &SessionMessageEnvelope::user_input("parent", "newer user input"),
                    SessionActivationPolicy::InterruptSpecificWait,
                    None,
                )
                .await
                .unwrap();
            let router = SessionActivationRouter::new();
            router.set_inbox(inbox.clone());
            let spawner = spawner();
            router.set_spawner(spawner.clone()).await;
            router
                .request_activation("parent", newer.generation)
                .await
                .unwrap();
            let claims = inbox.claim("parent", 128).await.unwrap();
            assert_eq!(claims.len(), 1);
            inbox.ack("parent", &claims[0]).await.unwrap();

            let mut owner = router.register_run("parent", "run-1").await.unwrap();
            owner.begin_finalization().await;
            let entered = Arc::new(Notify::new());
            let release = Arc::new(Notify::new());
            *router.terminal_inspection_pause.lock().await =
                Some((entered.clone(), release.clone()));
            let finalizing = tokio::spawn(async move {
                if abandon {
                    owner.abandon().await;
                    None
                } else {
                    owner.finish(newer.generation).await.unwrap()
                }
            });
            entered.notified().await;
            assert!(!inbox.inspect("parent").await.unwrap().activation_pending());
            inbox
                .mark_message_activation_eligible(
                    "parent",
                    &older,
                    SessionActivationPolicy::InterruptSpecificWait,
                )
                .await
                .unwrap();
            assert_eq!(
                router
                    .request_activation("parent", older.generation)
                    .await
                    .unwrap(),
                SessionActivationDisposition::ActivationCoalesced
            );
            release.notify_one();
            let outcome = tokio::time::timeout(std::time::Duration::from_secs(2), finalizing)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(
                outcome,
                (!abandon).then_some(SessionActivationDisposition::ActivationReserved)
            );
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
            assert!(router.owns_run("parent", "run-2").await);

            // Leave the newly processed item pending to prove the raced grant
            // does not repeatedly restart a poisoned successor.
            let claims = inbox.claim("parent", 128).await.unwrap();
            assert_eq!(claims.len(), 1);
            let mut successor = router.register_run("parent", "run-2").await.unwrap();
            successor.begin_finalization().await;
            assert_eq!(successor.finish(2).await.unwrap(), None);
            assert_eq!(
                router
                    .request_activation("parent", older.generation)
                    .await
                    .unwrap(),
                SessionActivationDisposition::ActivationCoalesced
            );
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
            inbox.ack("parent", &claims[0]).await.unwrap();
        }
    }

    struct RecordingSpawner {
        reservations: AtomicUsize,
        launches: Arc<AtomicUsize>,
        entered: Option<Arc<Barrier>>,
        release: Option<Arc<Notify>>,
    }

    #[async_trait]
    impl SessionActivationSpawner for RecordingSpawner {
        async fn reserve_activation(
            &self,
            _target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            if let Some(entered) = &self.entered {
                entered.wait().await;
            }
            if let Some(release) = &self.release {
                release.notified().await;
            }
            let launches = self.launches.clone();
            Ok(SessionActivationReserveOutcome::Reserved(
                SessionActivationLaunch::new(format!("run-{ordinal}"), move || {
                    launches.fetch_add(1, Ordering::SeqCst);
                }),
            ))
        }
    }

    fn spawner() -> Arc<RecordingSpawner> {
        Arc::new(RecordingSpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
            entered: None,
            release: None,
        })
    }

    struct BlockingInspectInbox {
        entered: Arc<Notify>,
        release: Arc<Notify>,
        drained: Arc<std::sync::atomic::AtomicBool>,
        fail_once: Option<Arc<std::sync::atomic::AtomicBool>>,
    }

    #[async_trait]
    impl SessionInboxPort for BlockingInspectInbox {
        async fn inspect_wake_readiness(
            &self,
            _target_session_id: &str,
            _now: DateTime<Utc>,
        ) -> Result<bamboo_domain::SessionInboxWakeReadiness, bamboo_domain::SessionInboxError>
        {
            // This double models only coordinator-prefix work, never a
            // separately promoted per-message delivery below that prefix.
            Ok(bamboo_domain::SessionInboxWakeReadiness::default())
        }

        async fn coordinator_activation_generation(
            &self,
            _target_session_id: &str,
        ) -> Result<u64, bamboo_domain::SessionInboxError> {
            Ok(1)
        }

        async fn deliver(
            &self,
            _envelope: &bamboo_domain::SessionMessageEnvelope,
        ) -> Result<bamboo_domain::SessionInboxReceipt, bamboo_domain::SessionInboxError> {
            unreachable!("router cleanup only inspects the durable inbox")
        }

        async fn mark_activation_eligible(
            &self,
            _target_session_id: &str,
            _generation: u64,
            _policy: bamboo_domain::SessionActivationPolicy,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            unreachable!("router cleanup only inspects the durable inbox")
        }

        async fn claim(
            &self,
            _target_session_id: &str,
            _limit: usize,
        ) -> Result<Vec<bamboo_domain::SessionInboxClaim>, bamboo_domain::SessionInboxError>
        {
            unreachable!("router cleanup only inspects the durable inbox")
        }

        async fn was_admitted(
            &self,
            _target_session_id: &str,
            _id: &bamboo_domain::SessionMessageId,
        ) -> Result<bool, bamboo_domain::SessionInboxError> {
            unreachable!("router cleanup only inspects the durable inbox")
        }

        async fn ack(
            &self,
            _target_session_id: &str,
            _claim: &bamboo_domain::SessionInboxClaim,
        ) -> Result<(), bamboo_domain::SessionInboxError> {
            unreachable!("router cleanup only inspects the durable inbox")
        }

        async fn inspect(
            &self,
            _target_session_id: &str,
        ) -> Result<bamboo_domain::SessionInboxBacklog, bamboo_domain::SessionInboxError> {
            if self
                .fail_once
                .as_ref()
                .is_some_and(|flag| flag.swap(false, Ordering::SeqCst))
            {
                return Err(bamboo_domain::SessionInboxError::Storage(
                    "injected inspect failure".into(),
                ));
            }
            if self.drained.load(Ordering::SeqCst) {
                return Ok(bamboo_domain::SessionInboxBacklog {
                    generation: 1,
                    activation_generation: 1,
                    ..Default::default()
                });
            }
            self.entered.notify_one();
            self.release.notified().await;
            Ok(bamboo_domain::SessionInboxBacklog {
                pending: 1,
                claimed: 0,
                generation: 1,
                activation_generation: 1,
                coordinator_generation: 1,
                interrupt_generation: 1,
                oldest_generation: Some(1),
            })
        }
    }

    #[tokio::test]
    async fn rollback_completion_is_retained_before_waiter_subscribes() {
        let completion = RollbackCompletion::new();
        completion.complete();
        tokio::time::timeout(std::time::Duration::from_millis(100), completion.wait())
            .await
            .expect("completion-before-wait must not lose its wake");
    }

    #[derive(Clone, Copy)]
    enum InjectedFirstOutcome {
        NoWork,
        Error,
    }

    struct RetrySpawner {
        reservations: AtomicUsize,
        launches: Arc<AtomicUsize>,
        first_outcome: InjectedFirstOutcome,
        first_entered: Arc<Barrier>,
        release_first: Arc<Notify>,
    }

    struct CancelFirstSpawner {
        reservations: AtomicUsize,
        launches: Arc<AtomicUsize>,
        first_entered: Arc<Notify>,
    }

    struct PanicFirstSpawner {
        reservations: AtomicUsize,
        launches: Arc<AtomicUsize>,
    }

    struct AlreadyRunningThenReserveSpawner {
        reservations: AtomicUsize,
        launches: Arc<AtomicUsize>,
    }

    #[async_trait]
    impl SessionActivationSpawner for AlreadyRunningThenReserveSpawner {
        async fn reserve_activation(
            &self,
            _target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            if ordinal == 1 {
                return Ok(SessionActivationReserveOutcome::AlreadyRunning {
                    run_id: "adopted-run".to_string(),
                });
            }
            let launches = self.launches.clone();
            Ok(SessionActivationReserveOutcome::Reserved(
                SessionActivationLaunch::new("successor-run", move || {
                    launches.fetch_add(1, Ordering::SeqCst);
                }),
            ))
        }
    }

    #[async_trait]
    impl SessionActivationSpawner for CancelFirstSpawner {
        async fn reserve_activation(
            &self,
            _target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            if ordinal == 1 {
                self.first_entered.notify_one();
                std::future::pending::<()>().await;
            }
            let launches = self.launches.clone();
            Ok(SessionActivationReserveOutcome::Reserved(
                SessionActivationLaunch::new(format!("run-{ordinal}"), move || {
                    launches.fetch_add(1, Ordering::SeqCst);
                }),
            ))
        }
    }

    #[async_trait]
    impl SessionActivationSpawner for PanicFirstSpawner {
        async fn reserve_activation(
            &self,
            _target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            if ordinal == 1 {
                panic!("injected first activation-spawner panic");
            }
            let launches = self.launches.clone();
            Ok(SessionActivationReserveOutcome::Reserved(
                SessionActivationLaunch::new(format!("run-{ordinal}"), move || {
                    launches.fetch_add(1, Ordering::SeqCst);
                }),
            ))
        }
    }

    struct RollbackSpawner {
        entered: Arc<Barrier>,
        release: Arc<Notify>,
        launch_ready: Arc<Notify>,
        rollbacks: Arc<AtomicUsize>,
    }

    struct RealRegistryRollbackSpawner {
        runners: Arc<
            tokio::sync::RwLock<std::collections::HashMap<String, crate::execution::AgentRunner>>,
        >,
        senders: Arc<
            tokio::sync::RwLock<
                std::collections::HashMap<
                    String,
                    tokio::sync::broadcast::Sender<bamboo_agent_core::AgentEvent>,
                >,
            >,
        >,
        sender: tokio::sync::broadcast::Sender<bamboo_agent_core::AgentEvent>,
        reservations: AtomicUsize,
        first_reserved: Arc<tokio::sync::Notify>,
        allow_first_return: Arc<tokio::sync::Notify>,
        first_returning: Arc<tokio::sync::Notify>,
        rollback_started: Arc<tokio::sync::Notify>,
        allow_rollback: Arc<tokio::sync::Notify>,
        launches: Arc<AtomicUsize>,
    }

    #[async_trait]
    impl SessionActivationSpawner for RealRegistryRollbackSpawner {
        async fn reserve_activation(
            &self,
            target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            match crate::execution::reserve_runner_core(
                &self.runners,
                &self.senders,
                target_session_id,
                &self.sender,
            )
            .await
            {
                crate::execution::ReserveOutcome::AlreadyRunning(run_id) => {
                    Ok(SessionActivationReserveOutcome::AlreadyRunning { run_id })
                }
                crate::execution::ReserveOutcome::Reserved(reservation) => {
                    let run_id = reservation.run_id.clone();
                    if ordinal == 1 {
                        self.first_reserved.notify_one();
                        self.allow_first_return.notified().await;
                        self.first_returning.notify_one();
                    }
                    let rollback_runners = self.runners.clone();
                    let rollback_session_id = target_session_id.to_string();
                    let rollback_run_id = run_id.clone();
                    let rollback_started = self.rollback_started.clone();
                    let allow_rollback = self.allow_rollback.clone();
                    let launches = self.launches.clone();
                    Ok(SessionActivationReserveOutcome::Reserved(
                        SessionActivationLaunch::new_with_async_rollback(
                            run_id,
                            move || {
                                launches.fetch_add(1, Ordering::SeqCst);
                            },
                            move || async move {
                                rollback_started.notify_one();
                                allow_rollback.notified().await;
                                let mut runners = rollback_runners.write().await;
                                if runners
                                    .get(&rollback_session_id)
                                    .is_some_and(|runner| runner.run_id == rollback_run_id)
                                {
                                    runners.remove(&rollback_session_id);
                                }
                            },
                        ),
                    ))
                }
            }
        }
    }

    #[async_trait]
    impl SessionActivationSpawner for RollbackSpawner {
        async fn reserve_activation(
            &self,
            _target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            self.entered.wait().await;
            self.release.notified().await;
            let rollbacks = self.rollbacks.clone();
            let outcome = SessionActivationReserveOutcome::Reserved(
                SessionActivationLaunch::new_with_rollback(
                    "reserved-run",
                    || {},
                    move || {
                        rollbacks.fetch_add(1, Ordering::SeqCst);
                    },
                ),
            );
            self.launch_ready.notify_one();
            Ok(outcome)
        }
    }

    #[async_trait]
    impl SessionActivationSpawner for RetrySpawner {
        async fn reserve_activation(
            &self,
            _target_session_id: &str,
            _inbox_generation: u64,
        ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
            let ordinal = self.reservations.fetch_add(1, Ordering::SeqCst) + 1;
            if ordinal == 1 {
                self.first_entered.wait().await;
                self.release_first.notified().await;
                return match self.first_outcome {
                    InjectedFirstOutcome::NoWork => Ok(SessionActivationReserveOutcome::NoWork),
                    InjectedFirstOutcome::Error => Err(SessionActivationError::Internal(
                        "injected first reservation failure".to_string(),
                    )),
                };
            }
            let launches = self.launches.clone();
            Ok(SessionActivationReserveOutcome::Reserved(
                SessionActivationLaunch::new(format!("run-{ordinal}"), move || {
                    launches.fetch_add(1, Ordering::SeqCst);
                }),
            ))
        }
    }

    async fn assert_newer_generation_retries_after(
        first_outcome: InjectedFirstOutcome,
    ) -> Result<SessionActivationDisposition, SessionActivationError> {
        let router = SessionActivationRouter::new();
        let first_entered = Arc::new(Barrier::new(2));
        let release_first = Arc::new(Notify::new());
        let spawner = Arc::new(RetrySpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
            first_outcome,
            first_entered: first_entered.clone(),
            release_first: release_first.clone(),
        });
        router.set_spawner(spawner.clone()).await;

        let first_router = router.clone();
        let first =
            tokio::spawn(async move { first_router.request_activation("session", 1).await });
        first_entered.wait().await;

        let second_router = router.clone();
        let second =
            tokio::spawn(async move { second_router.request_activation("session", 2).await });
        tokio::task::yield_now().await;
        assert_eq!(
            spawner.reservations.load(Ordering::SeqCst),
            1,
            "generation 2 must coalesce while generation 1 owns the reservation"
        );

        release_first.notify_one();
        let first_result = first.await.unwrap();
        assert_eq!(
            second.await.unwrap().unwrap(),
            SessionActivationDisposition::ActivationReserved,
            "the coalesced newer delivery must take the released reservation"
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
        first_result
    }

    #[tokio::test]
    async fn active_owner_is_notified_without_second_reservation() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let mut registration = router.register_run("session", "run-live").await.unwrap();

        assert_eq!(
            router.request_activation("session", 7).await.unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        registration.notifications_mut().changed().await.unwrap();
        assert_eq!(*registration.notifications_mut().borrow(), 7);
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 0);
        registration.begin_finalization().await;
        assert_eq!(registration.finish(7).await.unwrap(), None);
    }

    #[tokio::test]
    async fn different_run_registration_never_overwrites_live_owner() {
        let router = SessionActivationRouter::new();
        let mut first = router
            .register_run("session", "run-1")
            .await
            .expect("first run owns the logical session");

        let error = router
            .register_run("session", "run-2")
            .await
            .err()
            .expect("a second exact run must collide");
        assert_eq!(
            error,
            SessionRunRegistrationError::OwnerCollision {
                target_session_id: "session".to_string(),
                existing_run_id: "run-1".to_string(),
                attempted_run_id: "run-2".to_string(),
            }
        );
        assert!(router.owns_run("session", "run-1").await);
        assert!(!router.owns_run("session", "run-2").await);

        first.begin_finalization().await;
        assert_eq!(first.finish(0).await.unwrap(), None);
    }

    #[tokio::test]
    async fn direct_registration_waits_for_activation_to_publish_its_exact_owner() {
        let router = SessionActivationRouter::new();
        let reservation_entered = Arc::new(Barrier::new(2));
        let allow_reservation = Arc::new(Notify::new());
        let launches = Arc::new(AtomicUsize::new(0));
        let spawner = Arc::new(RecordingSpawner {
            reservations: AtomicUsize::new(0),
            launches: launches.clone(),
            entered: Some(reservation_entered.clone()),
            release: Some(allow_reservation.clone()),
        });
        router.set_spawner(spawner.clone()).await;

        let activation_router = router.clone();
        let activation =
            tokio::spawn(async move { activation_router.request_activation("session", 1).await });
        reservation_entered.wait().await;

        let direct_router = router.clone();
        let direct =
            tokio::spawn(async move { direct_router.register_run("session", "manual-run").await });
        tokio::task::yield_now().await;
        assert!(
            !direct.is_finished(),
            "manual registration must not supersede an in-flight activation token"
        );
        assert!(!router.owns_run("session", "manual-run").await);

        allow_reservation.notify_one();
        assert_eq!(
            activation.await.unwrap().unwrap(),
            SessionActivationDisposition::ActivationReserved
        );
        let collision = match direct.await.unwrap() {
            Ok(_) => panic!("manual registration must collide with the published activation"),
            Err(error) => error,
        };
        assert_eq!(
            collision,
            SessionRunRegistrationError::OwnerCollision {
                target_session_id: "session".to_string(),
                existing_run_id: "run-1".to_string(),
                attempted_run_id: "manual-run".to_string(),
            }
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(launches.load(Ordering::SeqCst), 1);
        assert!(router.owns_run("session", "run-1").await);
        assert!(!router.owns_run("session", "manual-run").await);

        let mut registration = router.register_run("session", "run-1").await.unwrap();
        registration.begin_finalization().await;
        assert_eq!(registration.finish(1).await.unwrap(), None);
    }

    #[tokio::test]
    async fn cancelled_explicit_abandon_still_finishes_owned_registration_cleanup() {
        let router = SessionActivationRouter::new();
        let cleanup_entered = Arc::new(Notify::new());
        let cleanup_release = Arc::new(Notify::new());
        let cleanup_completed = Arc::new(AtomicUsize::new(0));
        let mut registration = router.register_run("session", "run-abandon").await.unwrap();
        let entered = cleanup_entered.clone();
        let release = cleanup_release.clone();
        let completed = cleanup_completed.clone();
        registration.set_abort_cleanup(move || async move {
            entered.notify_one();
            release.notified().await;
            completed.fetch_add(1, Ordering::SeqCst);
        });

        let abandon = tokio::spawn(registration.abandon());
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            cleanup_entered.notified(),
        )
        .await
        .expect("explicit abandon must start its owned cleanup");
        abandon.abort();
        assert!(abandon.await.unwrap_err().is_cancelled());
        cleanup_release.notify_one();

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                if cleanup_completed.load(Ordering::SeqCst) == 1
                    && !router.owns_run("session", "run-abandon").await
                {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("caller cancellation must not cancel detached registration cleanup");
    }

    #[tokio::test]
    async fn delayed_same_run_cannot_adopt_an_owner_during_abandoned_cleanup() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let inspect_entered = Arc::new(Notify::new());
        let inspect_release = Arc::new(Notify::new());
        let drained = Arc::new(std::sync::atomic::AtomicBool::new(false));
        router.set_inbox(Arc::new(BlockingInspectInbox {
            entered: inspect_entered.clone(),
            release: inspect_release.clone(),
            drained: drained.clone(),
            fail_once: None,
        }));

        let registration = router
            .register_run("session", "run-abandoned")
            .await
            .unwrap();
        drop(registration);
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            inspect_entered.notified(),
        )
        .await
        .expect("abandoned cleanup must reach durable inbox reconciliation");

        let error = router
            .register_run("session", "run-abandoned")
            .await
            .err()
            .expect("a finalizing abandoned owner is not an adoptable launch placeholder");
        assert_eq!(error.existing_run_id(), "run-abandoned");

        inspect_release.notify_one();
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while spawner.launches.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("durable pending work must launch one successor");
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
        assert!(!router.owns_run("session", "run-abandoned").await);

        let mut successor = router.register_run("session", "run-1").await.unwrap();
        drained.store(true, Ordering::SeqCst);
        successor.begin_finalization().await;
        assert_eq!(successor.finish(1).await.unwrap(), None);
    }

    #[tokio::test]
    async fn delayed_registry_owner_collision_rolls_back_only_its_exact_runner() {
        let router = SessionActivationRouter::new();
        let runners = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
        let senders = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
        let (sender, _receiver) = tokio::sync::broadcast::channel(8);
        let reserved =
            match crate::execution::reserve_runner_core(&runners, &senders, "session", &sender)
                .await
            {
                crate::execution::ReserveOutcome::Reserved(reservation) => reservation,
                crate::execution::ReserveOutcome::AlreadyRunning(_) => {
                    panic!("fixture must reserve a fresh server runner")
                }
            };

        // Model the gap between the server runner reservation and its delayed
        // router registration: an independent direct SDK entry point wins the
        // logical owner first.
        let mut direct = router.register_run("session", "sdk-direct").await.unwrap();
        let collision = router
            .register_run("session", &reserved.run_id)
            .await
            .err()
            .expect("delayed server registration must collide");
        let collision_result = Err(bamboo_agent_core::AgentError::LLM(collision.to_string()));
        assert!(
            crate::execution::finalize_runner_exact(
                &runners,
                "session",
                &reserved.run_id,
                &collision_result,
            )
            .await
        );
        assert!(router.owns_run("session", "sdk-direct").await);
        assert!(matches!(
            runners
                .read()
                .await
                .get("session")
                .map(|runner| &runner.status),
            Some(crate::execution::AgentStatus::Error(_))
        ));

        direct.begin_finalization().await;
        assert_eq!(direct.finish(0).await.unwrap(), None);
    }

    #[tokio::test]
    async fn concurrent_idle_deliveries_coalesce_into_one_launch() {
        let router = SessionActivationRouter::new();
        let entered = Arc::new(Barrier::new(2));
        let release = Arc::new(Notify::new());
        let spawner = Arc::new(RecordingSpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
            entered: Some(entered.clone()),
            release: Some(release.clone()),
        });
        router.set_spawner(spawner.clone()).await;

        let first_router = router.clone();
        let first =
            tokio::spawn(async move { first_router.request_activation("session", 1).await });
        entered.wait().await;
        let second_router = router.clone();
        let second =
            tokio::spawn(async move { second_router.request_activation("session", 2).await });
        release.notify_one();
        assert_eq!(
            first.await.unwrap().unwrap(),
            SessionActivationDisposition::ActivationReserved
        );
        assert_eq!(
            second.await.unwrap().unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn newer_generation_re_reserves_after_coalesced_no_work() {
        assert_eq!(
            assert_newer_generation_retries_after(InjectedFirstOutcome::NoWork)
                .await
                .unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );
    }

    #[tokio::test]
    async fn newer_generation_re_reserves_after_coalesced_error() {
        let error = assert_newer_generation_retries_after(InjectedFirstOutcome::Error)
            .await
            .unwrap_err();
        assert!(matches!(error, SessionActivationError::Internal(_)));
    }

    async fn assert_cancelled_finalization_recovers_without_redelivery(registered_owner: bool) {
        let router = SessionActivationRouter::new();
        let first_entered = Arc::new(Notify::new());
        let spawner = Arc::new(CancelFirstSpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
            first_entered: first_entered.clone(),
        });
        router.set_spawner(spawner.clone()).await;

        let finish = if registered_owner {
            let mut registration = router.register_run("session", "run-old").await.unwrap();
            registration.begin_finalization().await;
            assert_eq!(
                router.request_activation("session", 1).await.unwrap(),
                SessionActivationDisposition::ActivationCoalesced
            );
            tokio::spawn(async move { registration.finish(0).await })
        } else {
            // Reserved actor-child runs use the raw router handshake rather
            // than SessionRunRegistration, so recovery cannot depend on that
            // guard's Drop implementation.
            router.begin_finalization("session", "run-old").await;
            assert_eq!(
                router.request_activation("session", 1).await.unwrap(),
                SessionActivationDisposition::ActivationCoalesced
            );
            let finish_router = router.clone();
            tokio::spawn(async move {
                finish_router
                    .finish_finalization("session", "run-old", 0)
                    .await
            })
        };
        first_entered.notified().await;
        finish.abort();
        assert!(finish.await.unwrap_err().is_cancelled());

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while spawner.launches.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("cancelled finalization must retry pending work without redelivery");
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
        assert!(router.owns_run("session", "run-2").await);

        let mut successor = router.register_run("session", "run-2").await.unwrap();
        successor.begin_finalization().await;
        assert_eq!(successor.finish(1).await.unwrap(), None);
    }

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

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

    #[tokio::test]
    async fn panicking_finalization_spawner_gets_one_bounded_retry() {
        let router = SessionActivationRouter::new();
        let spawner = Arc::new(PanicFirstSpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
        });
        router.set_spawner(spawner.clone()).await;
        router.begin_finalization("session", "run-old").await;
        assert_eq!(
            router.request_activation("session", 1).await.unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );

        let finish_router = router.clone();
        let finish = tokio::spawn(async move {
            finish_router
                .finish_finalization("session", "run-old", 0)
                .await
        });
        assert!(finish.await.unwrap_err().is_panic());

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while spawner.launches.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("router Drop recovery must survive one spawner panic");
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);

        let mut successor = router.register_run("session", "run-2").await.unwrap();
        successor.begin_finalization().await;
        assert_eq!(successor.finish(1).await.unwrap(), None);
    }

    #[tokio::test]
    async fn cancelled_reservation_releases_token_and_newer_generation_launches() {
        let router = SessionActivationRouter::new();
        let first_entered = Arc::new(Notify::new());
        let spawner = Arc::new(CancelFirstSpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
            first_entered: first_entered.clone(),
        });
        router.set_spawner(spawner.clone()).await;

        let first_router = router.clone();
        let first =
            tokio::spawn(async move { first_router.request_activation("session", 1).await });
        first_entered.notified().await;
        let second_router = router.clone();
        let second =
            tokio::spawn(async move { second_router.request_activation("session", 2).await });
        tokio::task::yield_now().await;
        first.abort();
        assert!(first.await.unwrap_err().is_cancelled());

        assert_eq!(
            tokio::time::timeout(std::time::Duration::from_secs(1), second)
                .await
                .expect("coalesced caller must not hang behind a cancelled reservation")
                .unwrap()
                .unwrap(),
            SessionActivationDisposition::ActivationReserved
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn cancellation_after_external_reservation_rolls_back_unlaunched_slot() {
        let router = SessionActivationRouter::new();
        let entered = Arc::new(Barrier::new(2));
        let release = Arc::new(Notify::new());
        let launch_ready = Arc::new(Notify::new());
        let rollbacks = Arc::new(AtomicUsize::new(0));
        let spawner = Arc::new(RollbackSpawner {
            entered: entered.clone(),
            release: release.clone(),
            launch_ready: launch_ready.clone(),
            rollbacks: rollbacks.clone(),
        });
        router.set_spawner(spawner).await;

        let task_router = router.clone();
        let task = tokio::spawn(async move { task_router.request_activation("session", 1).await });
        entered.wait().await;
        // The spawner can now return its reserved slot, but publishing the
        // logical owner is blocked. Aborting in this exact window must drop the
        // launch and invoke its external rollback.
        let states = router.states.lock().await;
        release.notify_one();
        launch_ready.notified().await;
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        drop(states);

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while rollbacks.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("unlaunched reservation rollback");
        assert_eq!(rollbacks.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn redelivery_waits_for_real_runner_rollback_before_reserving() {
        let router = SessionActivationRouter::new();
        let runners = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
        let senders = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
        let (sender, _receiver) = tokio::sync::broadcast::channel(8);
        let first_reserved = Arc::new(tokio::sync::Notify::new());
        let allow_first_return = Arc::new(tokio::sync::Notify::new());
        let rollback_started = Arc::new(tokio::sync::Notify::new());
        let first_returning = Arc::new(tokio::sync::Notify::new());
        let allow_rollback = Arc::new(tokio::sync::Notify::new());
        let launches = Arc::new(AtomicUsize::new(0));
        let spawner = Arc::new(RealRegistryRollbackSpawner {
            runners: runners.clone(),
            senders,
            sender,
            reservations: AtomicUsize::new(0),
            first_reserved: first_reserved.clone(),
            allow_first_return: allow_first_return.clone(),
            first_returning: first_returning.clone(),
            rollback_started: rollback_started.clone(),
            allow_rollback: allow_rollback.clone(),
            launches: launches.clone(),
        });
        router.set_spawner(spawner.clone()).await;

        let first_router = router.clone();
        let first =
            tokio::spawn(async move { first_router.request_activation("session", 1).await });
        first_reserved.notified().await;

        // Force the first request to yield after receiving the rollback-capable
        // real registry reservation but before publishing router ownership.
        let state_guard = router.states.lock().await;
        allow_first_return.notify_one();
        first_returning.notified().await;
        first.abort();
        assert!(first.await.unwrap_err().is_cancelled());
        drop(state_guard);
        rollback_started.notified().await;

        let second_router = router.clone();
        let second =
            tokio::spawn(async move { second_router.request_activation("session", 2).await });
        tokio::task::yield_now().await;
        assert_eq!(
            spawner.reservations.load(Ordering::SeqCst),
            1,
            "redelivery must remain coalesced until exact external rollback completes"
        );

        allow_rollback.notify_one();
        assert_eq!(
            tokio::time::timeout(std::time::Duration::from_secs(1), second)
                .await
                .expect("redelivery must reserve after rollback")
                .unwrap()
                .unwrap(),
            SessionActivationDisposition::ActivationReserved
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
        assert_eq!(launches.load(Ordering::SeqCst), 1);
        let current = runners
            .read()
            .await
            .get("session")
            .map(|runner| runner.run_id.clone())
            .expect("second real registry reservation remains");
        assert_ne!(
            current, "",
            "the redelivery must never adopt an empty/stale run id"
        );
    }

    #[tokio::test]
    async fn delivery_during_finalization_launches_one_successor() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let mut registration = router.register_run("session", "run-old").await.unwrap();
        registration.begin_finalization().await;

        assert_eq!(
            router.request_activation("session", 11).await.unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );
        let disposition = registration.finish(10).await.unwrap();
        assert_eq!(
            disposition,
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn finalization_does_not_restart_when_cursor_caught_up() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let mut registration = router.register_run("session", "run-old").await.unwrap();
        assert_eq!(
            router.request_activation("session", 4).await.unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        registration.begin_finalization().await;
        assert_eq!(registration.finish(4).await.unwrap(), None);
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 0);
        assert!(
            router.states.lock().await.get("session").is_none(),
            "a caught-up completed session must not leak routing state"
        );
    }

    #[tokio::test]
    async fn successor_finalization_removes_state_after_raced_generation_catches_up() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner).await;
        let mut registration = router.register_run("session", "run-old").await.unwrap();
        registration.begin_finalization().await;

        assert_eq!(
            router.request_activation("session", 11).await.unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );
        assert_eq!(
            registration.finish(10).await.unwrap(),
            Some(SessionActivationDisposition::ActivationReserved)
        );
        let mut successor_registration = router.register_run("session", "run-1").await.unwrap();
        successor_registration.begin_finalization().await;
        assert_eq!(successor_registration.finish(11).await.unwrap(), None);
        assert!(
            router.states.lock().await.get("session").is_none(),
            "the successor's caught-up terminal state must be compacted"
        );
    }

    #[tokio::test]
    async fn failed_terminal_inspection_keeps_the_exact_owner_cleanup_armed() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let inspect_release = Arc::new(Notify::new());
        inspect_release.notify_one();
        router.set_inbox(Arc::new(BlockingInspectInbox {
            entered: Arc::new(Notify::new()),
            release: inspect_release,
            drained: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            fail_once: Some(Arc::new(std::sync::atomic::AtomicBool::new(true))),
        }));
        let mut registration = router
            .register_run("session", "failed-inspect-run")
            .await
            .unwrap();
        router.request_activation("session", 1).await.unwrap();
        registration.begin_finalization().await;
        assert!(registration.finish(1).await.is_err());
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while spawner.launches.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("failed inspection must not leave the old run owning the inbox");
        assert!(!router.owns_run("session", "failed-inspect-run").await);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn poison_generation_launches_only_one_successor_until_new_work_arrives() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let inspect_release = Arc::new(Notify::new());
        router.set_inbox(Arc::new(BlockingInspectInbox {
            entered: Arc::new(Notify::new()),
            release: inspect_release.clone(),
            drained: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            fail_once: None,
        }));
        let mut registration = router
            .register_run("session", "run-original")
            .await
            .unwrap();
        assert_eq!(
            router.request_activation("session", 7).await.unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        registration.begin_finalization().await;
        inspect_release.notify_one();
        assert_eq!(
            registration.finish(0).await.unwrap(),
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);

        // Simulate the successor hitting the same permanently failing
        // checkpoint/poison claim. The same generation remains inspectable but
        // cannot recursively launch provider loops.
        let mut successor_registration = router.register_run("session", "run-1").await.unwrap();
        successor_registration.begin_finalization().await;
        inspect_release.notify_one();
        assert_eq!(successor_registration.finish(0).await.unwrap(), None);
        assert_eq!(
            router.request_activation("session", 7).await.unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);

        // A genuinely newer delivery gets one new bounded attempt.
        assert_eq!(
            router.request_activation("session", 8).await.unwrap(),
            SessionActivationDisposition::ActivationReserved
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn adopted_terminal_run_preserves_generation_for_one_real_successor() {
        let router = SessionActivationRouter::new();
        let spawner = Arc::new(AlreadyRunningThenReserveSpawner {
            reservations: AtomicUsize::new(0),
            launches: Arc::new(AtomicUsize::new(0)),
        });
        router.set_spawner(spawner.clone()).await;

        assert_eq!(
            router.request_activation("session", 12).await.unwrap(),
            SessionActivationDisposition::ActiveNotified
        );
        router.begin_finalization("session", "adopted-run").await;
        assert_eq!(
            router
                .finish_finalization("session", "adopted-run", 0)
                .await
                .unwrap(),
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 2);
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
    }
    #[tokio::test]
    async fn quarantined_registration_never_releases_owner_or_launches_successor() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let mut registration = router
            .register_run("session", "quarantined-run")
            .await
            .unwrap();
        let cleaned = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let cleanup_flag = cleaned.clone();
        registration.set_abort_cleanup(move || async move {
            cleanup_flag.store(true, Ordering::SeqCst);
        });
        registration.quarantine().await;
        assert_eq!(
            router.request_activation("session", 19).await.unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );
        assert!(router.register_run("session", "successor").await.is_err());
        assert!(router
            .register_run("session", "quarantined-run")
            .await
            .is_err());
        tokio::task::yield_now().await;
        assert!(!cleaned.load(Ordering::SeqCst));
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 0);
        let states = router.states.lock().await;
        let owner = states["session"].owner.as_ref().unwrap();
        assert_eq!(owner.run_id, "quarantined-run");
        assert!(owner.finalizing);
    }

    #[tokio::test]
    async fn physical_execution_registration_drop_is_quarantined() {
        let router = SessionActivationRouter::new();
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        let mut registration = router
            .register_run("session", "physical-run")
            .await
            .unwrap();
        let cleaned = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let cleanup_flag = cleaned.clone();
        registration.set_abort_cleanup(move || async move {
            cleanup_flag.store(true, Ordering::SeqCst);
        });
        registration.quarantine_on_drop();
        drop(registration);
        // Drop retains the owner synchronously, then an owned cleanup task
        // marks it finalizing. A racing delivery can still notify that retained
        // owner before the task is polled; it must never spawn a successor.
        assert!(matches!(
            router.request_activation("session", 7).await.unwrap(),
            SessionActivationDisposition::ActiveNotified
                | SessionActivationDisposition::ActivationCoalesced
        ));
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                if router.states.lock().await["session"]
                    .owner
                    .as_ref()
                    .unwrap()
                    .finalizing
                {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        assert_eq!(
            router.request_activation("session", 8).await.unwrap(),
            SessionActivationDisposition::ActivationCoalesced
        );
        assert!(!cleaned.load(Ordering::SeqCst));
        assert_eq!(spawner.launches.load(Ordering::SeqCst), 0);
        assert!(router.register_run("session", "successor").await.is_err());
        let states = router.states.lock().await;
        assert!(states["session"].owner.as_ref().unwrap().finalizing);
    }

    #[tokio::test]
    async fn cancelling_quarantine_wait_does_not_arm_abandoned_cleanup() {
        let router = SessionActivationRouter::new();
        let registration = router
            .register_run("session", "quarantined-run")
            .await
            .unwrap();
        let states_guard = router.states.lock().await;
        let mut quarantine = Box::pin(registration.quarantine());
        assert!(futures::poll!(quarantine.as_mut()).is_pending());
        drop(quarantine);
        drop(states_guard);
        tokio::task::yield_now().await;
        assert!(router.register_run("session", "successor").await.is_err());
        assert_eq!(
            router.current_run_id("session").await.as_deref(),
            Some("quarantined-run")
        );
    }
    async fn selected_fixture() -> (
        tempfile::TempDir,
        Arc<SessionActivationRouter>,
        Arc<RecordingSpawner>,
        Arc<bamboo_storage::FileSessionInbox>,
    ) {
        use bamboo_domain::{
            Session, SessionActivationPolicy, SessionInboxLimits, SessionMessageEnvelope, Storage,
        };
        let temp = tempfile::tempdir().unwrap();
        let store = Arc::new(
            bamboo_storage::SessionStoreV2::new(temp.path().into())
                .await
                .unwrap(),
        );
        store
            .save_session(&Session::new("selected", "model"))
            .await
            .unwrap();
        let inbox = Arc::new(bamboo_storage::FileSessionInbox::new(
            store,
            SessionInboxLimits::default(),
        ));
        inbox
            .deliver_with_activation_intent(
                &SessionMessageEnvelope::user_input("selected", "other eligible input"),
                SessionActivationPolicy::RespectSpecificWait,
                None,
            )
            .await
            .unwrap();
        let router = SessionActivationRouter::new();
        router.set_inbox(inbox.clone());
        let spawner = spawner();
        router.set_spawner(spawner.clone()).await;
        (temp, router, spawner, inbox)
    }

    #[tokio::test]
    async fn receipt_run_selected_release_never_inherits_unrequested_durable_backlog() {
        for mode in ["finish", "abandon", "drop"] {
            let (_temp, router, spawner, inbox) = selected_fixture().await;
            let mut selected = router
                .register_run("selected", "manual-selected")
                .await
                .unwrap();
            selected.restrict_to_selected_input();
            match mode {
                "finish" => {
                    selected.begin_finalization().await;
                    assert_eq!(selected.finish(0).await.unwrap(), None);
                }
                "abandon" => selected.abandon().await,
                _ => drop(selected),
            }
            tokio::time::timeout(std::time::Duration::from_secs(2), async {
                while router.current_run_id("selected").await.is_some() {
                    tokio::task::yield_now().await;
                }
            })
            .await
            .unwrap();
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 0, "{mode}");
            assert_eq!(spawner.launches.load(Ordering::SeqCst), 0);
            assert_eq!(inbox.inspect("selected").await.unwrap().pending, 1);
            // A subsequent real producer request still owns normal scheduling.
            assert_eq!(
                router.request_activation("selected", 1).await.unwrap(),
                SessionActivationDisposition::ActivationReserved
            );
            assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
        }
    }

    #[tokio::test]
    async fn receipt_run_selected_release_preserves_explicit_coalesced_coordinator_wake() {
        for mode in ["finish", "abandon", "drop"] {
            for notify_before_scope in [false, true] {
                let (_temp, router, spawner, _inbox) = selected_fixture().await;
                let mut selected = router
                    .register_run("selected", "manual-selected")
                    .await
                    .unwrap();
                if !notify_before_scope {
                    selected.restrict_to_selected_input();
                }
                assert_eq!(
                    router.request_activation("selected", 1).await.unwrap(),
                    SessionActivationDisposition::ActiveNotified
                );
                if notify_before_scope {
                    selected.restrict_to_selected_input();
                }
                match mode {
                    "finish" => {
                        selected.begin_finalization().await;
                        assert_eq!(
                            selected.finish(0).await.unwrap(),
                            Some(SessionActivationDisposition::ActivationReserved)
                        );
                    }
                    "abandon" => selected.abandon().await,
                    _ => drop(selected),
                }
                tokio::time::timeout(std::time::Duration::from_secs(2), async {
                    while spawner.reservations.load(Ordering::SeqCst) == 0 {
                        tokio::task::yield_now().await;
                    }
                })
                .await
                .unwrap();
                assert_eq!(
                    spawner.reservations.load(Ordering::SeqCst),
                    1,
                    "{mode}/{notify_before_scope}"
                );
                assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
                assert!(router.owns_run("selected", "run-1").await);
            }
        }
    }

    #[tokio::test]
    async fn receipt_run_cancelled_selected_finish_retains_restricted_drop_cleanup() {
        let (_temp, router, spawner, inbox) = selected_fixture().await;
        let mut selected = router
            .register_run("selected", "manual-selected")
            .await
            .unwrap();
        selected.restrict_to_selected_input();
        let lock = router.states.lock().await;
        let mut finish = Box::pin(selected.finish(0));
        assert!(futures::poll!(finish.as_mut()).is_pending());
        drop(finish);
        drop(lock);
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            while router.current_run_id("selected").await.is_some() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        assert_eq!(spawner.reservations.load(Ordering::SeqCst), 0);
        assert_eq!(inbox.inspect("selected").await.unwrap().pending, 1);
    }
    struct PeerIntentFixture {
        _temp: tempfile::TempDir,
        store: Arc<bamboo_storage::SessionStoreV2>,
        inbox: Arc<bamboo_storage::FileSessionInbox>,
        router: Arc<SessionActivationRouter>,
        spawner: Arc<RecordingSpawner>,
        messenger: crate::SessionMessenger,
    }

    impl PeerIntentFixture {
        async fn new() -> Self {
            use bamboo_domain::{Session, SessionInboxLimits, Storage};
            let temp = tempfile::tempdir().unwrap();
            let store = Arc::new(
                bamboo_storage::SessionStoreV2::new(temp.path().into())
                    .await
                    .unwrap(),
            );
            let target = Session::new("target", "model");
            let source = Session::new_child_of("sender", &target, "model", "task");
            store.save_session(&target).await.unwrap();
            store.save_session(&source).await.unwrap();
            let inbox = Arc::new(bamboo_storage::FileSessionInbox::new(
                store.clone(),
                SessionInboxLimits::default(),
            ));
            let router = SessionActivationRouter::new();
            router.set_inbox(inbox.clone());
            let spawner = spawner();
            router.set_spawner(spawner.clone()).await;
            let messenger =
                crate::SessionMessenger::new(store.clone(), inbox.clone(), router.clone());
            Self {
                _temp: temp,
                store,
                inbox,
                router,
                spawner,
                messenger,
            }
        }
    }

    #[tokio::test]
    async fn queue_only_delivery_never_schedules_idle_finalizing_or_restarted_target() {
        use bamboo_domain::SessionMessageDeliveryIntent::QueueOnly;
        for timing in [
            "idle",
            "active",
            "finalizing",
            "after_terminal_inspection",
            "selected_finish",
            "selected_abandon",
        ] {
            let fixture = PeerIntentFixture::new().await;
            let mut registration = if timing == "idle" {
                None
            } else {
                Some(
                    fixture
                        .router
                        .register_run("target", "manual-run")
                        .await
                        .unwrap(),
                )
            };
            if timing == "selected_finish" || timing == "selected_abandon" {
                registration.as_mut().unwrap().restrict_to_selected_input();
            }
            if timing == "finalizing" || timing == "after_terminal_inspection" {
                registration.as_mut().unwrap().begin_finalization().await;
            }
            let mut race = None;
            let release = Arc::new(Notify::new());
            if timing == "after_terminal_inspection" {
                let entered = Arc::new(Notify::new());
                *fixture.router.terminal_inspection_pause.lock().await =
                    Some((entered.clone(), release.clone()));
                let registration = registration.take().unwrap();
                race = Some(tokio::spawn(async move { registration.finish(0).await }));
                tokio::time::timeout(std::time::Duration::from_secs(2), entered.notified())
                    .await
                    .unwrap();
            }
            let receipt = fixture
                .messenger
                .send_peer_with_intent("sender", "target", "queue", "queued", QueueOnly)
                .await
                .unwrap();
            assert_eq!(receipt.activation, None, "{timing}");
            assert_eq!(
                receipt.active_delivery_notified,
                matches!(timing, "active" | "selected_finish" | "selected_abandon")
            );
            if let Some(mut registration) = registration {
                if timing == "selected_abandon" {
                    registration.abandon().await;
                } else {
                    registration.begin_finalization().await;
                    assert_eq!(registration.finish(0).await.unwrap(), None);
                }
            }
            if let Some(race) = race {
                release.notify_one();
                assert_eq!(race.await.unwrap().unwrap(), None);
            }
            assert_eq!(
                fixture.spawner.reservations.load(Ordering::SeqCst),
                0,
                "{timing}"
            );
            assert_eq!(fixture.spawner.launches.load(Ordering::SeqCst), 0);
            assert_eq!(fixture.inbox.inspect("target").await.unwrap().pending, 1);
            // Startup recovery uses the durable Inbox, not the live router hint.
            let restarted = SessionActivationRouter::new();
            restarted.set_inbox(fixture.inbox.clone());
            restarted.set_spawner(fixture.spawner.clone()).await;
            assert_eq!(
                restarted
                    .reconcile_wake("target", Utc::now())
                    .await
                    .unwrap()
                    .disposition,
                None
            );
            assert_eq!(fixture.spawner.reservations.load(Ordering::SeqCst), 0);
        }
    }

    #[tokio::test]
    async fn queue_only_notifies_late_bound_active_driver_and_checkpoints_at_safe_point() {
        use bamboo_domain::{SessionMessageDeliveryIntent::QueueOnly, Storage};
        let fixture = PeerIntentFixture::new().await;
        let mut registration = fixture
            .router
            .register_run("target", "manual-run")
            .await
            .unwrap();
        let receipt = fixture
            .messenger
            .send_peer_with_intent("sender", "target", "queue", "queued", QueueOnly)
            .await
            .unwrap();
        assert!(receipt.active_delivery_notified);
        assert!(registration.notifications_mut().has_changed().unwrap());
        let (tx, mut rx) = mpsc::unbounded_channel();
        assert_eq!(
            fixture
                .router
                .attach_delivery_sink("target", tx)
                .await
                .as_deref(),
            Some("manual-run")
        );
        assert_eq!(rx.try_recv().unwrap(), receipt.delivery.generation);
        let claims = fixture
            .inbox
            .claim_for_turn("target", 8, Some("manual-run"))
            .await
            .unwrap();
        assert_eq!(claims.len(), 1);
        let mut saved = fixture.store.load_session("target").await.unwrap().unwrap();
        saved.add_message(claims[0].envelope.to_provider_message().unwrap());
        fixture.store.save_session(&saved).await.unwrap();
        fixture.inbox.ack("target", &claims[0]).await.unwrap();
        registration.begin_finalization().await;
        assert_eq!(
            registration
                .finish(receipt.delivery.generation)
                .await
                .unwrap(),
            None
        );
        assert_eq!(fixture.spawner.reservations.load(Ordering::SeqCst), 0);
        let saved = fixture.store.load_session("target").await.unwrap().unwrap();
        assert_eq!(
            saved
                .messages
                .iter()
                .filter(|message| message.id == receipt.delivery.id.as_str())
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn explicit_trigger_turn_can_start_a_turn_after_queue_only_delivery() {
        use bamboo_domain::SessionMessageDeliveryIntent::{QueueOnly, TriggerTurn};
        let fixture = PeerIntentFixture::new().await;
        fixture
            .messenger
            .send_peer_with_intent("sender", "target", "queue", "queued", QueueOnly)
            .await
            .unwrap();
        assert_eq!(fixture.spawner.reservations.load(Ordering::SeqCst), 0);
        let followup = fixture
            .messenger
            .send_peer_with_intent("sender", "target", "followup", "followup", TriggerTurn)
            .await
            .unwrap();
        assert_eq!(
            followup.activation,
            Some(SessionActivationDisposition::ActivationReserved)
        );
        assert_eq!(fixture.spawner.reservations.load(Ordering::SeqCst), 1);
        assert_eq!(fixture.spawner.launches.load(Ordering::SeqCst), 1);
        let claims = fixture
            .inbox
            .claim_for_turn("target", 8, Some("run-1"))
            .await
            .unwrap();
        assert_eq!(claims.len(), 2);
        assert!(claims.iter().all(|claim| claim.activation_policy
            == bamboo_domain::SessionActivationPolicy::RespectSpecificWait));
    }

    #[tokio::test]
    async fn acknowledged_explicit_peer_retry_cannot_activate_or_notify_a_new_owner() {
        use bamboo_domain::{SessionMessageDeliveryIntent, Storage};
        for intent in [
            SessionMessageDeliveryIntent::TriggerTurn,
            SessionMessageDeliveryIntent::QueueOnly,
        ] {
            for active_owner in [false, true] {
                let fixture = PeerIntentFixture::new().await;
                let first = fixture
                    .messenger
                    .send_peer_with_intent("sender", "target", "ack-operation", "input", intent)
                    .await
                    .unwrap();
                let claim = fixture
                    .inbox
                    .claim_for_turn("target", 1, Some("first-run"))
                    .await
                    .unwrap()
                    .remove(0);
                let mut saved = fixture.store.load_session("target").await.unwrap().unwrap();
                saved.add_message(claim.envelope.to_provider_message().unwrap());
                saved
                    .session_inbox_admission_mut()
                    .record(claim.envelope.id.clone(), claim.generation);
                fixture.store.save_session(&saved).await.unwrap();
                fixture.inbox.ack("target", &claim).await.unwrap();

                // This spawner has no independent Inbox filter. The messenger
                // must not ask a fresh router to launch an acknowledged input.
                let restarted = SessionActivationRouter::new();
                restarted.set_inbox(fixture.inbox.clone());
                let fresh_spawner = spawner();
                restarted.set_spawner(fresh_spawner.clone()).await;
                let mut registration = if active_owner {
                    Some(restarted.register_run("target", "new-owner").await.unwrap())
                } else {
                    None
                };
                let messenger = crate::SessionMessenger::new(
                    fixture.store.clone(),
                    fixture.inbox.clone(),
                    restarted,
                );
                let retry = messenger
                    .send_peer_with_intent("sender", "target", "ack-operation", "input", intent)
                    .await
                    .unwrap();
                assert_eq!(retry.delivery, first.delivery);
                assert_eq!(retry.activation, None, "{intent:?} active={active_owner}");
                assert!(!retry.active_delivery_notified);
                assert_eq!(fresh_spawner.reservations.load(Ordering::SeqCst), 0);
                assert_eq!(fresh_spawner.launches.load(Ordering::SeqCst), 0);
                if let Some(mut registration) = registration.take() {
                    assert!(!registration.notifications_mut().has_changed().unwrap());
                    registration.begin_finalization().await;
                    assert_eq!(registration.finish(claim.generation).await.unwrap(), None);
                }
            }
        }
    }
    #[tokio::test]
    async fn expected_run_guard_conflicts_and_blocks_finalization_until_publication_finishes() {
        use bamboo_domain::{SessionRunConflictReason, SessionRunDeliveryGuard};
        async fn retain(
            router: Arc<SessionActivationRouter>,
            birth: DateTime<Utc>,
            expected: &'static str,
        ) -> Result<Arc<dyn SessionRunDeliveryGuard>, bamboo_domain::SessionRunConflict> {
            tokio::task::spawn_blocking(move || {
                router.retain_expected_run_blocking("target", birth, expected)
            })
            .await
            .unwrap()
        }
        let router = SessionActivationRouter::new();
        let target = bamboo_domain::Session::new("target", "model");
        let birth = target.created_at;
        assert_eq!(
            retain(router.clone(), birth, "run-a")
                .await
                .err()
                .unwrap()
                .reason,
            SessionRunConflictReason::NoActiveRun
        );
        let mut registration = router.register_session_run(&target, "run-a").await.unwrap();
        assert_eq!(
            retain(router.clone(), birth, "replacement")
                .await
                .err()
                .unwrap()
                .reason,
            SessionRunConflictReason::RunChanged
        );
        let stale_birth = retain(
            router.clone(),
            birth + chrono::Duration::seconds(1),
            "run-a",
        )
        .await
        .err()
        .unwrap();
        assert_eq!(
            stale_birth.reason,
            SessionRunConflictReason::SessionBirthChanged
        );
        assert_eq!(stale_birth.observed_run_id, None);
        let guard = retain(router.clone(), birth, "run-a").await.unwrap();
        assert!(guard.matches("target", birth, "run-a"));
        assert!(!guard.matches("other-target", birth, "run-a"));
        let notify = guard.clone();
        assert!(
            tokio::task::spawn_blocking(move || notify.notify_committed_delivery(7))
                .await
                .unwrap()
        );
        let mut finalizing = Box::pin(router.begin_finalization("target", "run-a"));
        assert!(futures::poll!(finalizing.as_mut()).is_pending());
        drop(guard);
        finalizing.await;
        assert_eq!(
            retain(router.clone(), birth, "run-a")
                .await
                .err()
                .unwrap()
                .reason,
            SessionRunConflictReason::Finalizing
        );
        assert_eq!(*registration.notifications_mut().borrow(), 7);
        assert_eq!(registration.finish(0).await.unwrap(), None);
        assert_eq!(router.current_run_id("target").await, None);
    }

    #[tokio::test]
    async fn expected_run_publication_fence_does_not_block_other_sessions() {
        let router = SessionActivationRouter::new();
        let target = bamboo_domain::Session::new("target", "model");
        let registration = router.register_session_run(&target, "run-a").await.unwrap();
        let query = router.clone();
        let guard = tokio::task::spawn_blocking(move || {
            query.retain_expected_run_blocking(&target.id, target.created_at, "run-a")
        })
        .await
        .unwrap()
        .unwrap();
        // Keep the actual publication guard alive as if the final filesystem
        // job is parked. Every unrelated owner transition must still complete.
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            let other = bamboo_domain::Session::new("independent", "model");
            let mut other_run = router
                .register_session_run(&other, "independent-run")
                .await
                .unwrap();
            assert!(router.notify_active_delivery(&other.id, 11).await);
            assert_eq!(*other_run.notifications_mut().borrow(), 11);
            other_run.begin_finalization().await;
            assert_eq!(other_run.finish(0).await.unwrap(), None);
            assert_eq!(router.current_run_id(&other.id).await, None);
        })
        .await
        .expect("a parked publication must not hold the global router lock");
        drop(guard);
        assert_eq!(registration.finish(0).await.unwrap(), None);
    }

    #[tokio::test]
    async fn expected_run_requires_real_lifetime_binding_and_cannot_rebind() {
        use bamboo_domain::SessionRunConflictReason;
        let router = SessionActivationRouter::new();
        let target = bamboo_domain::Session::new("target", "model");
        let mut registration = router.register_run(&target.id, "run-a").await.unwrap();
        let query = router.clone();
        let birth = target.created_at;
        let conflict = tokio::task::spawn_blocking(move || {
            query.retain_expected_run_blocking("target", birth, "run-a")
        })
        .await
        .unwrap()
        .err()
        .unwrap();
        assert_eq!(conflict.reason, SessionRunConflictReason::UnboundLifetime);
        assert_eq!(conflict.observed_run_id, None);
        let other_router = SessionActivationRouter::new();
        assert!(
            !other_router
                .bind_run_lifetime(&registration.ownership(), &target)
                .await
        );
        assert!(
            router
                .bind_run_lifetime(&registration.ownership(), &target)
                .await
        );
        let mut replacement = target.clone();
        replacement.created_at += chrono::Duration::seconds(1);
        assert!(
            !router
                .bind_run_lifetime(&registration.ownership(), &replacement)
                .await
        );
        let query = router.clone();
        let guard = tokio::task::spawn_blocking(move || {
            query.retain_expected_run_blocking("target", birth, "run-a")
        })
        .await
        .unwrap()
        .unwrap();
        assert!(guard.matches("target", birth, "run-a"));
        drop(guard);
        registration.begin_finalization().await;
        assert!(
            !router
                .bind_run_lifetime(&registration.ownership(), &target)
                .await
        );
        assert_eq!(registration.finish(0).await.unwrap(), None);
    }

    #[tokio::test]
    async fn expected_run_guard_rejects_unregistered_reservations_without_notification() {
        let router = SessionActivationRouter::new();
        router
            .install_owner_placeholder_for_test("target", "run-a")
            .await;
        let query = router.clone();
        let result = tokio::task::spawn_blocking(move || {
            query.retain_expected_run_blocking("target", Utc::now(), "run-a")
        })
        .await
        .unwrap();
        assert_eq!(
            result.err().unwrap().reason,
            bamboo_domain::SessionRunConflictReason::NotRegistered
        );
        assert_eq!(
            router.current_run_id("target").await.as_deref(),
            Some("run-a")
        );
        assert_eq!(
            router.states.lock().await["target"].latest_delivery_generation,
            0
        );
    }

    mod tool_suspension_registration_tests {
        use super::*;
        use bamboo_agent_core::tools::{
            capture_suspension_restriction, observe_tool_suspension, with_suspension_disabled,
            AsyncWaitKind, RunningCompletion, RunningHandle, ToolOutcome, ToolResult,
            ToolSuspensionObservation,
        };

        async fn bind_running_probe(
            registration: &mut SessionRunRegistration,
            deny: bool,
            kills: Arc<AtomicUsize>,
        ) -> ToolSuspensionObservation {
            let (_, report) = observe_tool_suspension(false, async {
                registration
                    .bind_tool_suspension_observation(capture_suspension_restriction().unwrap());
                let collapse = async move {
                    ToolOutcome::Running(RunningHandle {
                        tool_call_id: "registration-running-probe".into(),
                        ack: ToolResult::text(true, "ordinary running ack"),
                        completion: RunningCompletion::Detached,
                        wait_kind: AsyncWaitKind::AsyncTools,
                        kill: Box::new(move || {
                            kills.fetch_add(1, Ordering::SeqCst);
                        }),
                    })
                    .into_tool_result()
                };
                let result = if deny {
                    with_suspension_disabled(collapse).await
                } else {
                    collapse.await
                };
                assert_eq!(result.success, !deny);
            })
            .await;
            report
        }

        #[tokio::test]
        async fn forbidden_observation_retains_exact_owner_after_drop_or_observer_cancel() {
            for cancel_observer in [false, true] {
                let router = SessionActivationRouter::new();
                let spawner = spawner();
                router.set_spawner(spawner.clone()).await;
                let mut registration = router
                    .register_run("session", "observed-running-owner")
                    .await
                    .unwrap();
                let cleaned = Arc::new(AtomicUsize::new(0));
                let clean_count = cleaned.clone();
                registration.set_abort_cleanup(move || async move {
                    clean_count.fetch_add(1, Ordering::SeqCst);
                });
                assert_eq!(
                    router.request_activation("session", 7).await.unwrap(),
                    SessionActivationDisposition::ActiveNotified
                );
                let kills = Arc::new(AtomicUsize::new(0));
                let report = if cancel_observer {
                    let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
                    let child_kills = kills.clone();
                    let task = tokio::spawn(async move {
                        observe_tool_suspension(false, async move {
                            let report =
                                bind_running_probe(&mut registration, true, child_kills).await;
                            assert!(registration.observed_forbidden_running());
                            let _ = ready_tx.send(report);
                            std::future::pending::<()>().await;
                            // Keep the registration owned across the pending
                            // await; cancellation drops it with its real token.
                            drop(registration);
                        })
                        .await;
                    });
                    let ready =
                        tokio::time::timeout(std::time::Duration::from_secs(2), ready_rx).await;
                    task.abort();
                    let task_exit = task.await;
                    assert!(task_exit.unwrap_err().is_cancelled());
                    ready.unwrap().unwrap()
                } else {
                    let report = bind_running_probe(&mut registration, true, kills.clone()).await;
                    assert!(registration.observed_forbidden_running());
                    // The observer is already gone: only the opaque token
                    // retained on this exact lease preserves the proof.
                    drop(registration);
                    report
                };
                assert!(report.running_seen && report.forbidden_running_seen);
                assert_eq!(kills.load(Ordering::SeqCst), 1);

                tokio::time::timeout(std::time::Duration::from_secs(2), async {
                    loop {
                        let finalized = router
                            .states
                            .lock()
                            .await
                            .get("session")
                            .and_then(|state| state.owner.as_ref())
                            .is_some_and(|owner| {
                                owner.run_id == "observed-running-owner" && owner.finalizing
                            });
                        if finalized {
                            break;
                        }
                        tokio::task::yield_now().await;
                    }
                })
                .await
                .expect("the exact retained owner must enter finalization");
                assert_eq!(
                    router.request_activation("session", 8).await.unwrap(),
                    SessionActivationDisposition::ActivationCoalesced
                );
                for attempted in ["successor", "observed-running-owner"] {
                    let collision = router
                        .register_run("session", attempted)
                        .await
                        .err()
                        .expect("a quarantined owner cannot be replaced or adopted");
                    assert_eq!(collision.existing_run_id(), "observed-running-owner");
                }
                assert_eq!(cleaned.load(Ordering::SeqCst), 0);
                assert_eq!(spawner.reservations.load(Ordering::SeqCst), 0);
                assert_eq!(spawner.launches.load(Ordering::SeqCst), 0);
                let states = router.states.lock().await;
                let owner = states["session"].owner.as_ref().unwrap();
                assert_eq!(owner.run_id, "observed-running-owner");
                assert!(owner.finalizing);
                assert_eq!(owner.registrations, 1);
            }
        }

        #[tokio::test]
        async fn allowed_observation_preserves_ordinary_drop_and_finish_successors() {
            for finish_normally in [false, true] {
                let router = SessionActivationRouter::new();
                let spawner = spawner();
                router.set_spawner(spawner.clone()).await;
                let mut registration = router
                    .register_run("session", "ordinary-observed-owner")
                    .await
                    .unwrap();
                let cleaned = Arc::new(AtomicUsize::new(0));
                let clean_count = cleaned.clone();
                registration.set_abort_cleanup(move || async move {
                    clean_count.fetch_add(1, Ordering::SeqCst);
                });
                let kills = Arc::new(AtomicUsize::new(0));
                let report = bind_running_probe(&mut registration, false, kills.clone()).await;
                assert!(report.running_seen);
                assert!(!report.forbidden_running_seen);
                assert!(!registration.observed_forbidden_running());
                assert_eq!(kills.load(Ordering::SeqCst), 0);
                assert_eq!(
                    router.request_activation("session", 7).await.unwrap(),
                    SessionActivationDisposition::ActiveNotified
                );
                if finish_normally {
                    registration.begin_finalization().await;
                    assert_eq!(
                        registration.finish(0).await.unwrap(),
                        Some(SessionActivationDisposition::ActivationReserved)
                    );
                } else {
                    drop(registration);
                }
                tokio::time::timeout(std::time::Duration::from_secs(2), async {
                    while spawner.launches.load(Ordering::SeqCst) == 0 {
                        tokio::task::yield_now().await;
                    }
                })
                .await
                .expect("ordinary handoff must still launch its one successor");
                assert_eq!(spawner.reservations.load(Ordering::SeqCst), 1);
                assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
                assert_eq!(
                    cleaned.load(Ordering::SeqCst),
                    usize::from(!finish_normally)
                );
                assert!(router.owns_run("session", "run-1").await);
                let mut successor = router.register_run("session", "run-1").await.unwrap();
                successor.begin_finalization().await;
                assert_eq!(successor.finish(7).await.unwrap(), None);
                assert!(router.current_run_id("session").await.is_none());
                assert_eq!(spawner.launches.load(Ordering::SeqCst), 1);
            }
        }
    }
}

#[cfg(test)]
#[path = "session_activation_child_completion_tests.rs"]
mod child_completion_fence_tests;

#[cfg(test)]
#[path = "session_activation/scoped_loop_tests.rs"]
mod scoped_loop_tests;