bamboo-storage 2026.10.13

Session storage backends for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
//! Session storage V2 (folder-per-session + global index).
//!
//! Storage layout under `bamboo_home_dir`:
//! - `sessions.json` (global index, O(1) session_id -> rel_path)
//! - `sessions/<root_id>/session.json`
//! - `sessions/<root_id>/children/<child_id>/session.json`
//! - `.../attachments/` (files; session.json stores references, never base64)
//!
//! Notes:
//! - This is a greenfield format (no migration). Old on-disk layouts are ignored.
//! - The global index is a rebuildable cache, not the source of truth. Each
//!   `session.json` is authoritative; the index only speeds up lookups. A
//!   *missing* `sessions.json` starts an empty index; a *corrupt/unparseable*
//!   one is backed up to `sessions.json.bak` and the index is rebuilt by
//!   scanning `sessions/<root>/[children/<child>/]session.json` (see
//!   [`SessionStoreV2::rebuild_index_from_disk`]) so a bad index is never
//!   boot-fatal and never orphans intact sessions. Directory scanning is used
//!   only for this recovery path, never in hot paths.

use std::collections::{HashMap, HashSet, VecDeque};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use base64::Engine;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tokio::fs;
use tokio::sync::{
    mpsc, Mutex, Notify, OwnedMutexGuard, OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock,
};
use uuid::Uuid;

use bamboo_domain::ProviderModelRef;
use bamboo_domain::ReasoningEffort;
use bamboo_domain::{
    is_matching_session_message, Message, MessagePart, ParentQuestion, ParentQuestionResolution,
    ParentRequest, ParentResolution, ProjectId, Role, RootModeOperationAction,
    RootModeOperationDecision, RootModeOperationOutcome, RootModeOperationReceipt,
    RootModeOperationRequest, RootToolAuthorityError, Session, SessionAuthorityIdentity,
    SessionKind, SessionMessageEnvelope, SupervisorBootstrapReceipt, TaskList, TokenBudgetUsage,
    DEFAULT_SUPERVISOR_SESSION_ID,
};

mod actor_checkpoint_lineage;
#[cfg(test)]
mod actor_checkpoint_lineage_tests;
mod actor_directory;
mod actor_input;
pub(crate) mod child_wait_control_plane;
// A private observation port, deliberately without an acting caller.
#[allow(dead_code)]
mod canonical_birth_census;
#[cfg(test)]
mod canonical_birth_census_tests;
pub(crate) use actor_input::ActorInputGuards;
pub use actor_input::{
    ActorClaimContextSeed, ActorInputCheckpoint, ActorInputCheckpointError,
    ActorInputCheckpointResult, ActorInputCheckpointStatus,
};
#[cfg(test)]
mod actor_input_tests;
mod actor_model_context;
mod actor_transcript;
mod broker_receipt;
pub use actor_model_context::{
    ActorModelContextCheckpoint, ActorModelContextError, ActorModelContextOutcome,
};
pub use actor_transcript::{
    ActorTranscriptAppend, ActorTranscriptAppendError, ActorTranscriptGroupAppend,
};
pub use broker_receipt::{
    BrokerTerminalCompleteness, BrokerTerminalReceipt, BrokerTerminalRoute,
    HostTerminalCompleteness, HostToolYield,
};
#[cfg(test)]
mod actor_directory_lifetime_tests;
mod actor_snapshot;
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod actor_snapshot_reader;
#[cfg(windows)]
#[path = "v2/actor_snapshot_reader_windows.rs"]
mod actor_snapshot_reader;
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod actor_snapshot_tests;
#[cfg(all(test, windows))]
mod actor_snapshot_windows_tests;
#[cfg(test)]
mod actor_transcript_tests;
mod child_actor_runtime;
#[cfg(test)]
mod child_actor_runtime_tests;
#[cfg(test)]
mod child_deletion_tests;
mod child_project;
mod compact_main;
#[cfg(test)]
mod compact_main_tests;
mod default_actor_context;
mod host_registry;
mod root_actor_input;
#[cfg(test)]
mod root_actor_input_tests;
mod root_actor_runtime;
mod scoped_loop_control;
#[cfg(test)]
mod scoped_loop_control_tests;
pub(crate) mod scoped_transport_expiry;
mod title_observations;
pub use host_registry::FileHostRegistry;
#[cfg(test)]
mod default_actor_context_tests;
#[cfg(test)]
mod host_registry_tests;
mod parent_question_answer_proof;
mod parent_question_checkpoint;
#[cfg(test)]
mod startup_sidecar_tests;
#[cfg(test)]
mod task_publication_lifetime_tests;
use default_actor_context::DefaultWriterGuards;
pub(crate) use default_actor_context::DefaultWriterPhysicalGuards;
mod root_context;
#[cfg(test)]
mod root_context_tests;
mod root_lifetime;
#[cfg(test)]
mod root_lifetime_tests;
#[cfg(test)]
mod root_mode_actor_context_tests;
mod supervisor;
mod supervisor_management;
pub(crate) use supervisor_management::SupervisorFollowupGuard;
#[cfg(test)]
mod supervisor_management_lifetime_tests;
#[cfg(test)]
mod supervisor_management_tests;
mod supervisor_proof;
#[cfg(test)]
mod supervisor_proof_tests;
#[cfg(test)]
mod supervisor_tests;

use crate::search_index::{should_index_session, SessionSearchIndex};
use bamboo_domain::AttachmentReader;
use bamboo_domain::Storage;

pub(crate) fn other_io_error(message: impl Into<String>) -> io::Error {
    io::Error::other(message.into())
}

/// A full-save snapshot predates a durable direct-parent decision. Callers that
/// checkpoint transcripts may reload and append the missing proof before retrying.
#[derive(Debug, thiserror::Error)]
#[error("durable direct-parent terminal changed while saving session")]
pub(crate) struct DirectParentTerminalConflict;

#[derive(Debug, thiserror::Error)]
#[error("invalid direct-parent terminal proof")]
pub(crate) struct DirectParentTerminalProofError;

fn canonical_session_message(message: &Message, envelope: &SessionMessageEnvelope) -> bool {
    is_matching_session_message(message, envelope)
        && envelope.to_provider_message().ok().is_some_and(|expected| {
            serde_json::to_value(message).ok() == serde_json::to_value(expected).ok()
        })
}

fn reject_regressing_direct_parent_terminals(
    incoming: &Session,
    durable: &Session,
) -> io::Result<()> {
    const PERMISSION_TERMINAL: &str = "direct_parent_forced_permission_terminal_v1";
    const CLARIFICATION_TERMINAL: &str = "direct_parent_clarification_terminal_v1";
    for (terminal_index, terminal_message) in durable.messages.iter().enumerate() {
        let Some(marker) = terminal_message
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("session_message"))
        else {
            continue;
        };
        let instruction = marker
            .pointer("/body/instruction")
            .and_then(serde_json::Value::as_str);
        if instruction != Some(PERMISSION_TERMINAL) && instruction != Some(CLARIFICATION_TERMINAL) {
            continue;
        }
        let invalid_proof =
            || io::Error::new(io::ErrorKind::InvalidData, DirectParentTerminalProofError);
        let terminal: SessionMessageEnvelope =
            serde_json::from_value(marker.clone()).map_err(|_| invalid_proof())?;
        if !canonical_session_message(terminal_message, &terminal)
            || durable
                .messages
                .iter()
                .filter(|message| message.id == terminal_message.id)
                .count()
                != 1
        {
            return Err(invalid_proof());
        }
        let request_id = terminal.in_reply_to.as_ref().ok_or_else(invalid_proof)?;
        let mut requests = durable.messages[..terminal_index]
            .iter()
            .filter(|message| message.id == request_id.as_str());
        let request_message = requests.next().ok_or_else(invalid_proof)?;
        if requests.next().is_some()
            || durable.messages[terminal_index + 1..]
                .iter()
                .any(|message| {
                    message.id == request_id.as_str() || message.id == terminal_message.id
                })
        {
            return Err(invalid_proof());
        }
        let request_marker = request_message
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("session_message"))
            .ok_or_else(invalid_proof)?;
        let request: SessionMessageEnvelope =
            serde_json::from_value(request_marker.clone()).map_err(|_| invalid_proof())?;
        let typed_proof = if instruction == Some(PERMISSION_TERMINAL) {
            ParentRequest::from_forced_permission_envelope(&request).is_some_and(|typed_request| {
                typed_request.parent.session_id == durable.id
                    && typed_request.parent.created_at == durable.created_at
                    && typed_request.root_session_id == durable.root_session_id
                    && ParentResolution::from_forced_permission_terminal(&request, &terminal)
                        .is_some()
            })
        } else {
            ParentQuestion::from_envelope(&request).is_some_and(|typed_request| {
                typed_request.parent.session_id == durable.id
                    && typed_request.parent.created_at == durable.created_at
                    && typed_request.root_session_id == durable.root_session_id
                    && ParentQuestionResolution::from_terminal(&request, &terminal).is_some()
            })
        };
        if !canonical_session_message(request_message, &request) || !typed_proof {
            return Err(invalid_proof());
        }

        for durable_message in [request_message, terminal_message] {
            let mut matching = incoming
                .messages
                .iter()
                .filter(|message| message.id == durable_message.id);
            let Some(matched) = matching.next() else {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    DirectParentTerminalConflict,
                ));
            };
            if matching.next().is_some()
                || serde_json::to_value(matched).ok() != serde_json::to_value(durable_message).ok()
            {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    DirectParentTerminalProofError,
                ));
            }
        }
    }
    Ok(())
}

/// Filename of the runtime control-plane sidecar, stored alongside
/// `session.json` in each session directory.
const RUNTIME_SIDECAR_FILE: &str = "runtime.json";
/// Private undo journals for recoverable two-session Task sidecar commits.
/// Filenames are random UUIDs; untrusted session ids are never used as paths.
const RUNTIME_TASK_TRANSACTION_DIR: &str = ".runtime-task-transactions";
const RUNTIME_TASK_TRANSACTION_LOCK_FILE: &str = ".runtime-task-transactions.lock";
const RUNTIME_TASK_TRANSACTION_VERSION: u32 = 1;
/// Private rollback markers for crash-safe session copies. A live `.json`
/// marker means the copy has not crossed its success boundary yet, so startup
/// must remove every target projection before exposing the store.
const SESSION_COPY_TRANSACTION_DIR: &str = ".session-copy-transactions";
const SESSION_COPY_TRANSACTION_VERSION: u32 = 1;
const SESSIONS_INDEX_VERSION: u32 = 4;

/// Filename of the append-only per-LLM-call token-usage log, stored alongside
/// `session.json` in each session directory. One JSON line per call.
const TOKEN_USAGE_FILE: &str = "token-usage.jsonl";

/// Marker (under `bamboo_home_dir`) recording that the one-shot runtime sidecar
/// migration has completed, so it is skipped on subsequent boots.
const RUNTIME_SIDECAR_MIGRATION_MARKER: &str = ".runtime_sidecar_migrated";
const SESSION_LIFECYCLE_LOCK_FILE: &str = ".session-lifecycle.lock";
const SESSION_INDEX_LOCK_FILE: &str = ".sessions-index.lock";
const SESSION_WRITE_LOCK_DIR: &str = ".session-write-locks";
const ACTOR_TREE_LOCK_DIR: &str = ".actor-tree-locks";
const ACTOR_TREE_REVISION_FILE: &str = ".actor-tree-revision.json";
const MAX_ACTOR_TREE_REVISION: u64 = (1_u64 << 53) - 1;

/// The revision is published before a tree-visible write. A failed write can
/// cause a harmless extra snapshot; a crash cannot leave changed public state
/// behind an unchanged cursor. The epoch distinguishes Root ID reuse.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ActorTreeRevision {
    version: u32,
    root_id: String,
    root_created_at: DateTime<Utc>,
    project_id: Option<String>,
    epoch: Uuid,
    revision: u64,
}

impl ActorTreeRevision {
    fn new(root: &Session) -> Self {
        Self {
            version: 1,
            root_id: root.id.clone(),
            root_created_at: root.created_at,
            project_id: normalized_project_id(root),
            epoch: Uuid::new_v4(),
            revision: 1,
        }
    }

    fn matches_root(&self, root: &Session) -> bool {
        self.version == 1
            && self.root_id == root.id
            && self.root_created_at == root.created_at
            && self.revision > 0
            && self.revision <= MAX_ACTOR_TREE_REVISION
            && root.project_id_meta() == normalized_project_id(root)
            && self.project_id == normalized_project_id(root)
    }

    fn cursor(&self) -> String {
        let mut hash = Sha256::new();
        hash.update(b"actor-tree-cursor-v1\0");
        hash.update(self.root_id.as_bytes());
        hash.update(b"\0");
        hash.update(self.root_created_at.to_rfc3339().as_bytes());
        hash.update(b"\0");
        hash.update(self.project_id.as_deref().unwrap_or("").as_bytes());
        hash.update(b"\0");
        hash.update(self.epoch.as_bytes());
        format!("at1-{:x}-{}", hash.finalize(), self.revision)
    }
}

/// Acquired after lifecycle, Task and exact Session locks. Its file lock spans
/// all background filesystem jobs through the owning writer guard.
struct ActorTreeWriteGuard {
    file: std::fs::File,
}

impl Drop for ActorTreeWriteGuard {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}
const SEARCH_INDEX_REVISION_FILE: &str = ".search-index-revision";
const PERSISTENCE_METRIC_WINDOW: usize = 1024;
const SEARCH_INDEX_MAX_ATTEMPTS: usize = 3;

struct SessionIndexFileGuard {
    file: std::fs::File,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TaskControlPlaneUndo {
    session_id: String,
    task_list: Option<TaskList>,
    task_list_version: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RuntimeTaskTransactionJournal {
    version: u32,
    transaction_id: String,
    first: TaskControlPlaneUndo,
    second: TaskControlPlaneUndo,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SessionCopyTransactionJournal {
    version: u32,
    transaction_id: String,
    source_id: String,
    target_id: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RuntimeTaskJournalMarkerState {
    Prepared,
    Committing,
    Committed,
}

impl RuntimeTaskJournalMarkerState {
    fn from_path(path: &Path) -> Option<Self> {
        match path.extension().and_then(|value| value.to_str()) {
            Some("json") => Some(Self::Prepared),
            Some("committing") => Some(Self::Committing),
            Some("committed") => Some(Self::Committed),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SessionCopyJournalMarkerState {
    Prepared,
    Committing,
    Committed,
}

impl SessionCopyJournalMarkerState {
    fn from_path(path: &Path) -> Option<Self> {
        match path.extension().and_then(|value| value.to_str()) {
            Some("json") => Some(Self::Prepared),
            Some("committing") => Some(Self::Committing),
            Some("committed") => Some(Self::Committed),
            _ => None,
        }
    }
}

enum RuntimeTaskJournalFinalizeError {
    Rollback(io::Error),
    RecoveryRequired(io::Error),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RuntimeTaskTransactionFault {
    FirstUpdatedWrite,
    SecondUpdatedWrite,
    JournalRemove,
    FirstRollbackWrite,
    SecondRollbackWrite,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RuntimeTaskDurabilityEvent {
    JournalPublished,
    SingleUpdatedSidecarPublished,
    FirstUpdatedSidecarPublished,
    SecondUpdatedSidecarPublished,
    FirstRollbackSidecarPublished,
    SecondRollbackSidecarPublished,
    JournalDeactivated,
}

struct RuntimeTaskTransactionReadGuard {
    _process: OwnedRwLockReadGuard<()>,
    file: std::fs::File,
}

impl Drop for RuntimeTaskTransactionReadGuard {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

/// Clones retain the same exclusive process gate and physical file lock.
/// A started filesystem job owns a clone independently of its async waiter.
#[derive(Clone)]
struct RuntimeTaskTransactionWriteGuard {
    _lease: Arc<RuntimeTaskTransactionWriteLease>,
}

struct RuntimeTaskTransactionWriteLease {
    _process: OwnedRwLockWriteGuard<()>,
    file: std::fs::File,
}

impl Drop for RuntimeTaskTransactionWriteLease {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

#[cfg(test)]
#[derive(Debug, Clone)]
struct RuntimeTaskFirstWritePause {
    reached: std::sync::Arc<tokio::sync::Barrier>,
    release: std::sync::Arc<tokio::sync::Barrier>,
}

#[cfg(any(test, feature = "test-utils"))]
#[derive(Debug, Clone)]
struct FullSavePause {
    session_id: String,
    reached: Arc<tokio::sync::Barrier>,
    release: Arc<tokio::sync::Barrier>,
}

impl Drop for SessionIndexFileGuard {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

async fn lock_index_file_exclusive_at(bamboo_home_dir: &Path) -> io::Result<SessionIndexFileGuard> {
    let path = bamboo_home_dir.join(SESSION_INDEX_LOCK_FILE);
    let file = tokio::task::spawn_blocking(move || {
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(path)?;
        FileExt::lock_exclusive(&file)?;
        Ok::<_, io::Error>(file)
    })
    .await
    .map_err(|error| other_io_error(format!("join session index lock task: {error}")))??;
    Ok(SessionIndexFileGuard { file })
}

async fn persist_index_path_locked(index_path: &Path, index: &SessionsIndex) -> io::Result<()> {
    let bytes = serde_json::to_vec_pretty(index).map_err(|e| other_io_error(e.to_string()))?;
    durable_atomic_write(index_path, &bytes).await
}

pub(crate) struct SessionLifecycleReadGuard {
    _process: OwnedRwLockReadGuard<()>,
    file: std::fs::File,
}

impl Drop for SessionLifecycleReadGuard {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

/// Existing authority locks retained by one peer Inbox admission.
pub(crate) struct PeerDeliveryGuard {
    pub(crate) inbox_dir: PathBuf,
    tree: Option<ActorTreeWriteGuard>,
    sessions: Vec<SessionWriteGuard>,
    _task: RuntimeTaskTransactionReadGuard,
    _lifecycle: SessionLifecycleReadGuard,
}

impl Drop for PeerDeliveryGuard {
    fn drop(&mut self) {
        drop(self.tree.take());
        while let Some(_guard) = self.sessions.pop() {}
    }
}

pub(crate) struct SessionLifecycleWriteGuard {
    _process: OwnedRwLockWriteGuard<()>,
    file: std::fs::File,
}

impl Drop for SessionLifecycleWriteGuard {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

// Field order releases Task before lifecycle, reversing acquisition order.
// Started Child removal jobs share these actual guards with their async caller.
struct SessionDeletionGuards {
    runtime_task: RuntimeTaskTransactionWriteGuard,
    _lifecycle: SessionLifecycleWriteGuard,
}

/// Keeps the just-published copy isolated from cross-process storage writers
/// while the HTTP layer mirrors it into process-local projections.
pub struct SessionCopyProjectionGuard {
    _lifecycle: SessionLifecycleWriteGuard,
    _runtime_task: RuntimeTaskTransactionWriteGuard,
}

/// Build the sidecar snapshot: the full session minus its `messages` history.
/// Every field except `messages` is authoritative in the sidecar; on load the
/// message history is taken back from `session.json`.
pub(crate) fn runtime_sidecar_snapshot(session: &Session) -> Session {
    let mut snapshot = session.clone();
    snapshot.messages.clear();
    // Native transcript groups are committed atomically with the ordinary
    // message that anchors them. Never let runtime.json expose a load/search
    // item without the corresponding session.json history boundary.
    snapshot.provider_transcript = Default::default();
    if let Some(metadata) = snapshot.runtime_metadata.as_mut() {
        // Admission ids must be committed atomically with their transcript
        // messages in session.json. Duplicating them into runtime.json would
        // allow a crash between the two files to expose dedupe state without
        // the corresponding message.
        metadata.session_inbox_admission = None;
    }
    snapshot
}

/// Overlay the runtime sidecar onto the session loaded from `session.json`.
///
/// The sidecar holds the freshest control-plane (metadata, `agent_runtime_state`,
/// title group, …) because every save — full or runtime-only — writes it. The
/// large `messages` history is only ever written by full saves into
/// `session.json`, so it is preserved from `main`.
fn overlay_runtime_sidecar(main: Session, sidecar: Option<Session>) -> Session {
    match sidecar {
        Some(mut side) => {
            let admission = main
                .runtime_metadata
                .as_ref()
                .and_then(|metadata| metadata.session_inbox_admission.clone());
            side.messages = main.messages;
            side.provider_transcript = main.provider_transcript;
            if let Some(admission) = admission {
                side.runtime_metadata
                    .get_or_insert_with(Default::default)
                    .session_inbox_admission = Some(admission);
            } else if let Some(metadata) = side.runtime_metadata.as_mut() {
                metadata.session_inbox_admission = None;
            }
            side
        }
        None => main,
    }
}

/// Normalize the persisted compatibility metadata through the authoritative
/// typed Project id parser before mirroring it into the rebuildable index.
/// Malformed legacy metadata is isolated to that session instead of poisoning
/// the entire session index.
fn normalized_project_id(session: &Session) -> Option<String> {
    let raw = session.project_id_meta()?;
    match raw.trim().parse::<ProjectId>() {
        Ok(project_id) => Some(project_id.into_string()),
        Err(error) => {
            tracing::warn!(
                session_id = %session.id,
                %error,
                "ignoring malformed Project id while updating session index"
            );
            None
        }
    }
}

/// Exactly the Session-owned inputs to PublicActorSnapshotNode, plus the
/// authority scope that makes a cursor unsafe across Project/Root rebinding.
/// Private transcript, model context and runtime heartbeats do not advance the
/// tree stream.
fn actor_tree_session_projection(session: &Session) -> serde_json::Value {
    serde_json::json!({
        "id": session.id,
        "created_at": session.created_at,
        "title": compact_main::public_title(&session.title),
        "metadata_version": session.metadata_version,
        "kind": session.kind,
        "parent_session_id": session.parent_session_id,
        "root_session_id": session.root_session_id,
        "spawn_depth": session.spawn_depth,
        "project_id": session.project_id_meta(),
        "authority_identity": session.authority_identity,
        "root_tool_authority_revision": session.root_tool_authority_revision,
        // Narrow diagnostic evidence changes wake existing at1 subscribers.
        // No private payload, resource instance or query-time expiry is a
        // public event; this tuple is only an internal equality comparison.
        "local_task": [
            session.metadata.get("runtime.local_task.state"),
            session.metadata.get("runtime.local_task.run_id"),
            session.metadata.get("runtime.local_task.child_birth"),
            session.metadata.get("runtime.local_task.observed_at"),
            session.metadata.get("runtime.local_task.reason"),
            session.metadata.get("runtime.local_task.instance"),
            session.metadata.get("runtime.kind"),
            session.metadata.get("external.agent_id"),
            session.metadata.get("external.protocol"),
        ],
    })
}

async fn read_actor_tree_session_projection(
    directory: &Path,
    expected: &Session,
) -> Option<serde_json::Value> {
    let path = directory.join(RUNTIME_SIDECAR_FILE);
    if !fs::symlink_metadata(&path)
        .await
        .ok()?
        .file_type()
        .is_file()
    {
        return None;
    }
    let bytes = fs::read(path).await.ok()?;
    let side: Session = serde_json::from_slice(&bytes).ok()?;
    if side.id != expected.id
        || side.created_at != expected.created_at
        || side.kind != expected.kind
        || side.parent_session_id != expected.parent_session_id
        || side.root_session_id != expected.root_session_id
        || side.spawn_depth != expected.spawn_depth
        || side.project_id_meta() != expected.project_id_meta()
    {
        return None;
    }
    Some(actor_tree_session_projection(&side))
}

/// Reject a session id that could escape the storage directory (empty, or
/// containing a path separator or `..`). Shared with [`crate::jsonl`] so every
/// store applies the same guard. #31.
pub(crate) fn validate_session_id(session_id: &str) -> io::Result<()> {
    if session_id.is_empty()
        || session_id.contains('/')
        || session_id.contains('\\')
        || session_id.contains("..")
    {
        return Err(other_io_error(format!("invalid session id: {session_id}")));
    }
    Ok(())
}

/// Where a session's agent physically runs: the deployment kind plus the host.
/// Mirrored into the index from `session.metadata["placement"]` so the frontend
/// can show "which machine this session runs on" without loading session.json.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SessionPlacement {
    /// Deployment kind: `"local"` (this backend's own host), `"docker"`, or
    /// `"ssh"` (a remote node the child was deployed to).
    pub kind: String,
    /// Host the agent runs on — the backend's hostname for `local`, or the
    /// target host for a remote/ssh deployment.
    pub host: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionIndexEntry {
    pub id: String,
    pub kind: SessionKind,
    /// Path relative to `bamboo_home_dir` (e.g. "sessions/<id>" or "sessions/<root>/children/<id>").
    pub rel_path: String,
    pub title: String,
    #[serde(default)]
    pub title_version: u64,
    #[serde(default = "default_title_generated")]
    pub title_generated: bool,
    pub pinned: bool,
    pub parent_session_id: Option<String>,
    pub root_session_id: String,
    pub spawn_depth: u32,
    #[serde(default)]
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_ref: Option<ProviderModelRef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<ReasoningEffort>,
    /// Workspace path mirrored from the session's typed runtime metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_path: Option<String>,
    /// Stable Project identity mirrored from typed session runtime metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// Raw session-level Gold config JSON mirrored from `session.metadata["gold_config"]`.
    /// Kept as a string here to avoid making infrastructure depend on bamboo-engine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gold_config_json: Option<String>,
    /// If the session was created by a schedule, store the schedule id here for fast filtering.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by_schedule_id: Option<String>,
    /// If the session was created by a specific schedule run, keep the run id here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schedule_run_id: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub last_activity_at: DateTime<Utc>,
    pub message_count: usize,
    pub has_attachments: bool,
    /// Whether the session currently has a pending question awaiting user response.
    /// Mirrored into the index from `session.has_pending_question()` so the frontend
    /// can display the question dialog badge without loading session.json.
    #[serde(default)]
    pub has_pending_question: bool,
    /// Active plan mode runtime state mirrored into the index from
    /// `session.agent_runtime_state.plan_mode`, so lightweight session-list/detail
    /// APIs can surface plan mode without loading every session.json.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan_mode: Option<bamboo_domain::PlanModeState>,
    /// Compatibility indicator mirrored from the effective permission mode, so
    /// old session-list clients still see a permissive session without loading
    /// every session.json. True for both Bypass and Auto.
    #[serde(default)]
    pub bypass_permissions: bool,
    /// Typed permission mode mirrored from the session runtime state.
    #[serde(default)]
    pub permission_mode: bamboo_domain::SessionPermissionMode,
    /// Last known run status for this session
    /// ("pending" | "running" | "completed" | "error" | "cancelled" | "skipped").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_run_status: Option<String>,
    /// Last known terminal error message, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_run_error: Option<String>,
    /// Last token usage information (updated after each LLM call).
    ///
    /// Stored in the global index so the frontend can display token usage without
    /// loading full session.json for every row.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_usage: Option<TokenBudgetUsage>,
    /// SubAgent profile id for child sessions spawned by `SubAgent.create`.
    /// Mirrored into the index from `session.metadata["subagent_type"]` so the
    /// frontend can render role badges (e.g. "general-purpose", "plan") on the
    /// child-session list without loading each session.json.
    /// `None` for root sessions and for legacy children created before this
    /// field was introduced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subagent_type: Option<String>,
    /// Child lifecycle: `Some("resident")` for a reusable resident agent (a
    /// stable session reused for successive tasks); `None`/absent for the
    /// default one-shot child. Mirrored from `session.metadata["lifecycle"]`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lifecycle: Option<String>,
    /// For a resident agent, the stable reuse key (scoped to `root_session_id`).
    /// Mirrored from `session.metadata["resident_name"]`; lets a later
    /// `SubAgent.create` find and reuse the resident without loading session.json.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resident_name: Option<String>,
    /// Where this session's agent physically runs (deployment kind + host).
    /// Mirrored from `session.metadata["placement"]`. `None` for legacy rows and
    /// for local sessions that were never stamped; the session DTO layer defaults
    /// `None` to the backend's own local host so the frontend always has a value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placement: Option<SessionPlacement>,
}

fn default_title_generated() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionsIndex {
    pub version: u32,
    pub updated_at: DateTime<Utc>,
    pub sessions: HashMap<String, SessionIndexEntry>,
    /// Durable crash-resume marker for an old/corrupt index rebuild. It lets a
    /// second constructor join an in-progress rebuild without clearing entries
    /// already recovered (or concurrently published by live session saves).
    #[serde(default)]
    rebuild_in_progress: bool,
}

impl SessionsIndex {
    fn empty() -> Self {
        Self {
            version: SESSIONS_INDEX_VERSION,
            updated_at: Utc::now(),
            sessions: HashMap::new(),
            rebuild_in_progress: false,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct DurationMetricsSnapshot {
    pub count: u64,
    pub total_ms: u64,
    pub last_ms: u64,
    pub max_ms: u64,
    pub p50_ms: u64,
    pub p95_ms: u64,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct SavePersistenceMetricsSnapshot {
    pub lock_wait: DurationMetricsSnapshot,
    pub lock_hold: DurationMetricsSnapshot,
    pub total: DurationMetricsSnapshot,
    pub directory_preparation: DurationMetricsSnapshot,
    pub serialization: DurationMetricsSnapshot,
    pub filesystem_commit: DurationMetricsSnapshot,
    pub index_publication: DurationMetricsSnapshot,
    pub search_enqueue: DurationMetricsSnapshot,
    pub last_serialized_bytes: usize,
    pub last_message_count: usize,
    pub last_index_entry_count: usize,
}

/// Bounded, aggregate persistence telemetry. Session ids are deliberately not
/// retained as metric labels; they appear only in structured traces for local
/// correlation, avoiding unbounded cardinality.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SessionPersistenceMetricsSnapshot {
    pub full_save: SavePersistenceMetricsSnapshot,
    pub runtime_save: SavePersistenceMetricsSnapshot,
    pub index_lock_wait: DurationMetricsSnapshot,
    pub index_lock_hold: DurationMetricsSnapshot,
    pub search_index: DurationMetricsSnapshot,
    pub create_latency: DurationMetricsSnapshot,
    pub waiting_saves: usize,
    pub active_saves: usize,
    pub pending_search_jobs: usize,
    pub active_search_jobs: usize,
}

#[derive(Debug, Default)]
struct DurationMetrics {
    count: u64,
    total_ms: u64,
    last_ms: u64,
    max_ms: u64,
    recent_ms: VecDeque<u64>,
}

impl DurationMetrics {
    fn record(&mut self, duration: Duration) {
        let millis = u64::try_from(duration.as_millis()).unwrap_or(u64::MAX);
        self.count = self.count.saturating_add(1);
        self.total_ms = self.total_ms.saturating_add(millis);
        self.last_ms = millis;
        self.max_ms = self.max_ms.max(millis);
        if self.recent_ms.len() == PERSISTENCE_METRIC_WINDOW {
            self.recent_ms.pop_front();
        }
        self.recent_ms.push_back(millis);
    }

    fn snapshot(&self) -> DurationMetricsSnapshot {
        let mut samples = self.recent_ms.iter().copied().collect::<Vec<_>>();
        samples.sort_unstable();
        let percentile = |percent: usize| {
            if samples.is_empty() {
                return 0;
            }
            let index = ((samples.len() - 1) * percent).div_ceil(100);
            samples[index]
        };
        DurationMetricsSnapshot {
            count: self.count,
            total_ms: self.total_ms,
            last_ms: self.last_ms,
            max_ms: self.max_ms,
            p50_ms: percentile(50),
            p95_ms: percentile(95),
        }
    }
}

#[derive(Debug, Default)]
struct SavePersistenceMetrics {
    lock_wait: DurationMetrics,
    lock_hold: DurationMetrics,
    total: DurationMetrics,
    directory_preparation: DurationMetrics,
    serialization: DurationMetrics,
    filesystem_commit: DurationMetrics,
    index_publication: DurationMetrics,
    search_enqueue: DurationMetrics,
    last_serialized_bytes: usize,
    last_message_count: usize,
    last_index_entry_count: usize,
}

impl SavePersistenceMetrics {
    fn snapshot(&self) -> SavePersistenceMetricsSnapshot {
        SavePersistenceMetricsSnapshot {
            lock_wait: self.lock_wait.snapshot(),
            lock_hold: self.lock_hold.snapshot(),
            total: self.total.snapshot(),
            directory_preparation: self.directory_preparation.snapshot(),
            serialization: self.serialization.snapshot(),
            filesystem_commit: self.filesystem_commit.snapshot(),
            index_publication: self.index_publication.snapshot(),
            search_enqueue: self.search_enqueue.snapshot(),
            last_serialized_bytes: self.last_serialized_bytes,
            last_message_count: self.last_message_count,
            last_index_entry_count: self.last_index_entry_count,
        }
    }
}

#[derive(Debug, Default)]
struct PersistenceMetricsState {
    full_save: SavePersistenceMetrics,
    runtime_save: SavePersistenceMetrics,
    index_lock_wait: DurationMetrics,
    index_lock_hold: DurationMetrics,
    search_index: DurationMetrics,
    create_latency: DurationMetrics,
}

#[derive(Debug, Default)]
struct SessionPersistenceMetrics {
    state: std::sync::Mutex<PersistenceMetricsState>,
    waiting_saves: AtomicUsize,
    active_saves: AtomicUsize,
}

#[derive(Debug, Clone, Copy)]
enum SaveKind {
    Full,
    Runtime,
}

impl SaveKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Runtime => "runtime",
        }
    }
}

#[derive(Debug, Default)]
struct SaveStageDurations {
    directory_preparation: Duration,
    serialization: Duration,
    filesystem_commit: Duration,
    index_publication: Duration,
    search_enqueue: Duration,
}

impl SessionPersistenceMetrics {
    fn with_save_mut<T>(
        &self,
        kind: SaveKind,
        f: impl FnOnce(&mut SavePersistenceMetrics) -> T,
    ) -> T {
        let mut state = self.state.lock().expect("session persistence metrics lock");
        match kind {
            SaveKind::Full => f(&mut state.full_save),
            SaveKind::Runtime => f(&mut state.runtime_save),
        }
    }

    fn record_lock_wait(&self, kind: SaveKind, duration: Duration) {
        self.with_save_mut(kind, |metrics| metrics.lock_wait.record(duration));
    }

    fn record_lock_hold(&self, kind: SaveKind, duration: Duration) {
        self.with_save_mut(kind, |metrics| metrics.lock_hold.record(duration));
    }

    fn record_save(
        &self,
        kind: SaveKind,
        total: Duration,
        stages: SaveStageDurations,
        serialized_bytes: usize,
        message_count: usize,
        index_entry_count: usize,
    ) {
        self.with_save_mut(kind, |metrics| {
            metrics.total.record(total);
            metrics
                .directory_preparation
                .record(stages.directory_preparation);
            metrics.serialization.record(stages.serialization);
            metrics.filesystem_commit.record(stages.filesystem_commit);
            metrics.index_publication.record(stages.index_publication);
            metrics.search_enqueue.record(stages.search_enqueue);
            metrics.last_serialized_bytes = serialized_bytes;
            metrics.last_message_count = message_count;
            metrics.last_index_entry_count = index_entry_count;
        });
    }

    fn record_index_lock_wait(&self, duration: Duration) {
        self.state
            .lock()
            .expect("session persistence metrics lock")
            .index_lock_wait
            .record(duration);
    }

    fn record_index_lock_hold(&self, duration: Duration) {
        self.state
            .lock()
            .expect("session persistence metrics lock")
            .index_lock_hold
            .record(duration);
    }

    fn record_search_index(&self, duration: Duration) {
        self.state
            .lock()
            .expect("session persistence metrics lock")
            .search_index
            .record(duration);
    }

    fn record_create_latency(&self, duration: Duration) {
        self.state
            .lock()
            .expect("session persistence metrics lock")
            .create_latency
            .record(duration);
    }

    fn snapshot(
        &self,
        pending_search_jobs: usize,
        active_search_jobs: usize,
    ) -> SessionPersistenceMetricsSnapshot {
        let state = self.state.lock().expect("session persistence metrics lock");
        SessionPersistenceMetricsSnapshot {
            full_save: state.full_save.snapshot(),
            runtime_save: state.runtime_save.snapshot(),
            index_lock_wait: state.index_lock_wait.snapshot(),
            index_lock_hold: state.index_lock_hold.snapshot(),
            search_index: state.search_index.snapshot(),
            create_latency: state.create_latency.snapshot(),
            waiting_saves: self.waiting_saves.load(Ordering::Relaxed),
            active_saves: self.active_saves.load(Ordering::Relaxed),
            pending_search_jobs,
            active_search_jobs,
        }
    }
}

#[derive(Debug)]
struct SessionWriteGuard {
    guard: Option<OwnedMutexGuard<()>>,
    file: Option<std::fs::File>,
    locks: Arc<DashMap<String, Arc<Mutex<()>>>>,
    session_id: String,
    kind: Option<SaveKind>,
    acquired: Instant,
    metrics: Arc<SessionPersistenceMetrics>,
}

#[derive(Debug)]
struct WaitingSaveCounter {
    metrics: Arc<SessionPersistenceMetrics>,
}

impl Drop for WaitingSaveCounter {
    fn drop(&mut self) {
        self.metrics.waiting_saves.fetch_sub(1, Ordering::Relaxed);
    }
}

impl Drop for SessionWriteGuard {
    fn drop(&mut self) {
        if let Some(file) = self.file.take() {
            let _ = FileExt::unlock(&file);
        }
        self.guard.take();
        if let Some(kind) = self.kind {
            self.metrics.active_saves.fetch_sub(1, Ordering::Relaxed);
            let held = self.acquired.elapsed();
            self.metrics.record_lock_hold(kind, held);
            tracing::debug!(
                target: "bamboo.session_persistence",
                session_id = %self.session_id,
                save_type = kind.as_str(),
                phase = "session_lock_released",
                lock_hold_ms = held.as_millis() as u64,
                "session persistence lock released"
            );
        }
        self.locks
            .remove_if(&self.session_id, |_, lock| Arc::strong_count(lock) == 1);
    }
}

#[derive(Debug)]
enum SearchIndexMutation {
    Upsert {
        session: Box<Session>,
        revision_path: PathBuf,
        expected_revision: String,
    },
    Delete {
        session_id: String,
        revision_path: PathBuf,
    },
}

impl SearchIndexMutation {
    fn session_id(&self) -> &str {
        match self {
            Self::Upsert { session, .. } => &session.id,
            Self::Delete { session_id, .. } => session_id,
        }
    }
}

#[derive(Debug)]
struct PendingSearchIndexMutation {
    generation: u64,
    mutation: SearchIndexMutation,
}

#[derive(Debug, Default)]
struct SearchIndexQueueState {
    pending: HashMap<String, PendingSearchIndexMutation>,
    order: VecDeque<String>,
}

#[derive(Debug)]
struct SearchIndexQueue {
    state: Arc<std::sync::Mutex<SearchIndexQueueState>>,
    signal: mpsc::Sender<()>,
    next_generation: AtomicU64,
    in_flight: Arc<AtomicUsize>,
    idle: Arc<Notify>,
}

impl SearchIndexQueue {
    fn new(index: SessionSearchIndex, metrics: Arc<SessionPersistenceMetrics>) -> Self {
        let state = Arc::new(std::sync::Mutex::new(SearchIndexQueueState::default()));
        let in_flight = Arc::new(AtomicUsize::new(0));
        let idle = Arc::new(Notify::new());
        // The signal only means "inspect the coalescing map". One buffered
        // wake-up is sufficient even under a large save burst, so the channel
        // itself cannot become another unbounded queue.
        let (signal, mut receiver) = mpsc::channel(1);
        let worker_state = state.clone();
        let worker_in_flight = in_flight.clone();
        let worker_idle = idle.clone();
        tokio::spawn(async move {
            while receiver.recv().await.is_some() {
                loop {
                    let next = {
                        let mut state = worker_state.lock().expect("session search queue lock");
                        let session_id = state.order.pop_front();
                        let next =
                            session_id.and_then(|session_id| state.pending.remove(&session_id));
                        if next.is_some() {
                            worker_in_flight.fetch_add(1, Ordering::Relaxed);
                        }
                        next
                    };
                    let Some(job) = next else {
                        worker_idle.notify_waiters();
                        break;
                    };

                    let started = Instant::now();
                    let session_id = job.mutation.session_id().to_string();
                    let operation = match &job.mutation {
                        SearchIndexMutation::Upsert { .. } => "upsert",
                        SearchIndexMutation::Delete { .. } => "delete",
                    };
                    let mut result = Ok(());
                    for attempt in 1..=SEARCH_INDEX_MAX_ATTEMPTS {
                        result = match &job.mutation {
                            SearchIndexMutation::Upsert {
                                session,
                                revision_path,
                                expected_revision,
                            } => {
                                index
                                    .upsert_session_if_current(
                                        session,
                                        revision_path,
                                        expected_revision,
                                    )
                                    .await
                            }
                            SearchIndexMutation::Delete {
                                session_id,
                                revision_path,
                            } => {
                                index
                                    .delete_session_if_source_missing(session_id, revision_path)
                                    .await
                            }
                        };
                        if result.is_ok() {
                            break;
                        }
                        if attempt < SEARCH_INDEX_MAX_ATTEMPTS {
                            tokio::time::sleep(Duration::from_millis(25 * attempt as u64)).await;
                        }
                    }
                    let elapsed = started.elapsed();
                    metrics.record_search_index(elapsed);
                    if let Err(error) = result {
                        tracing::warn!(
                            target: "bamboo.session_persistence",
                            session_id,
                            generation = job.generation,
                            operation,
                            elapsed_ms = elapsed.as_millis() as u64,
                            %error,
                            "deferred session search-index mutation failed; startup rebuild will retry"
                        );
                    } else {
                        tracing::debug!(
                            target: "bamboo.session_persistence",
                            session_id,
                            generation = job.generation,
                            operation,
                            elapsed_ms = elapsed.as_millis() as u64,
                            "deferred session search-index mutation completed"
                        );
                    }
                    worker_in_flight.fetch_sub(1, Ordering::Relaxed);
                    worker_idle.notify_waiters();
                }
            }
        });
        Self {
            state,
            signal,
            next_generation: AtomicU64::new(1),
            in_flight,
            idle,
        }
    }

    fn enqueue(&self, mutation: SearchIndexMutation) -> u64 {
        let generation = self.next_generation.fetch_add(1, Ordering::Relaxed);
        let session_id = mutation.session_id().to_string();
        let mut state = self.state.lock().expect("session search queue lock");
        if !state.pending.contains_key(&session_id) {
            state.order.push_back(session_id.clone());
        }
        state.pending.insert(
            session_id,
            PendingSearchIndexMutation {
                generation,
                mutation,
            },
        );
        drop(state);
        if let Err(mpsc::error::TrySendError::Closed(_)) = self.signal.try_send(()) {
            tracing::error!(
                target: "bamboo.session_persistence",
                generation,
                "session search-index worker stopped unexpectedly"
            );
        }
        generation
    }

    fn enqueue_upsert(
        &self,
        session: &Session,
        revision_path: PathBuf,
        expected_revision: String,
    ) -> u64 {
        self.enqueue(SearchIndexMutation::Upsert {
            session: Box::new(session.clone()),
            revision_path,
            expected_revision,
        })
    }

    fn enqueue_delete(&self, session_id: &str, revision_path: PathBuf) -> u64 {
        self.enqueue(SearchIndexMutation::Delete {
            session_id: session_id.to_string(),
            revision_path,
        })
    }

    fn pending_len(&self) -> usize {
        self.state
            .lock()
            .expect("session search queue lock")
            .pending
            .len()
    }

    async fn flush(&self) {
        loop {
            let notified = self.idle.notified();
            tokio::pin!(notified);
            // Register before observing the queue. `notify_waiters` does not
            // retain a permit, so checking first would leave a lost-wakeup
            // window between the idle observation and `.await`.
            notified.as_mut().enable();
            if self.pending_len() == 0 && self.in_flight.load(Ordering::Acquire) == 0 {
                return;
            }
            notified.await;
        }
    }
}

#[derive(Debug)]
pub struct SessionStoreV2 {
    bamboo_home_dir: PathBuf,
    sessions_dir: PathBuf,
    index_path: PathBuf,
    search_index: SessionSearchIndex,
    search_index_queue: SearchIndexQueue,
    index: RwLock<SessionsIndex>,
    /// Serializes on-disk index writes (and any multi-step operations that must be atomic-ish).
    write_lock: Mutex<()>,
    /// Serializes full and runtime-only writes for the same session while
    /// allowing unrelated session ids to make progress independently.
    session_write_locks: Arc<DashMap<String, Arc<Mutex<()>>>>,
    persistence_metrics: Arc<SessionPersistenceMetrics>,
    /// Coordinates destructive target lifecycle transitions with durable inbox
    /// operations. The Tokio lock covers one runtime; the file lock covers
    /// independent Bamboo processes sharing the same data directory.
    session_lifecycle_lock: std::sync::Arc<RwLock<()>>,
    /// Coordinates every runtime-sidecar read/write with paired Task commits
    /// and orphan recovery. The Tokio gate prevents same-instance re-entry;
    /// the dedicated fs2 file lock covers independent store instances and
    /// processes sharing this Bamboo home.
    runtime_task_transaction_gate: std::sync::Arc<RwLock<()>>,
    /// When true, ordinary control-plane access fails closed until the retained
    /// undo journal has restored both sides of an interrupted transaction.
    runtime_task_recovery_required: AtomicBool,
    #[cfg(test)]
    runtime_task_faults: std::sync::Mutex<Vec<RuntimeTaskTransactionFault>>,
    #[cfg(test)]
    runtime_task_first_write_pause: std::sync::Mutex<Option<RuntimeTaskFirstWritePause>>,
    #[cfg(test)]
    runtime_task_durability_events: std::sync::Mutex<Vec<RuntimeTaskDurabilityEvent>>,
    #[cfg(any(test, feature = "test-utils"))]
    full_save_pause: std::sync::Mutex<Option<FullSavePause>>,
    #[cfg(test)]
    root_publication_fault: std::sync::Mutex<Option<root_lifetime::RootPublicationFault>>,
    #[cfg(test)]
    root_tool_proof_fault: std::sync::Mutex<Option<root_context::RootToolProofFault>>,
    #[cfg(test)]
    supervisor_proof_fault: std::sync::Mutex<Option<supervisor_proof::SupervisorProofFault>>,
    #[cfg(test)]
    management_write_hook:
        std::sync::Mutex<Option<Arc<supervisor_management_lifetime_tests::ManagementWriteHook>>>,
    #[cfg(test)]
    actor_write_hook: std::sync::Mutex<Option<Arc<actor_directory_lifetime_tests::ActorWriteHook>>>,
    #[cfg(test)]
    transcript_write_hook:
        std::sync::Mutex<Option<Arc<actor_transcript_tests::TranscriptWriteHook>>>,
    #[cfg(any(test, feature = "test-utils"))]
    child_wait_registration_pause:
        std::sync::Mutex<Option<(Arc<tokio::sync::Barrier>, Arc<tokio::sync::Barrier>)>>,
    #[cfg(test)]
    default_write_hook:
        std::sync::Mutex<Option<Arc<default_actor_context_tests::DefaultWriteHook>>>,
    #[cfg(test)]
    child_delete_hook: std::sync::Mutex<Option<Arc<child_deletion_tests::ChildDeleteHook>>>,
    #[cfg(test)]
    migration_scan_pause: std::sync::Mutex<Option<startup_sidecar_tests::ScanPause>>,
    #[cfg(test)]
    task_write_hook: std::sync::Mutex<Option<Arc<task_publication_lifetime_tests::TaskWriteHook>>>,
    #[cfg(test)]
    census_read_hook: std::sync::Mutex<Option<Arc<canonical_birth_census_tests::ReadHook>>>,
}

const COPY_TRANSIENT_METADATA_KEYS: &[&str] = &[
    "agent.runtime.state",
    "assignment_prompt",
    "clarification_resume_pending",
    "conclusion_with_options_resume_pending",
    "created_by_connect_key",
    "created_by_schedule_id",
    "disabled_tools",
    "external_memory_rendered",
    "execute.startup_handoff_at",
    "execute.pending_turn_message_id",
    "goal.state",
    "gold.auto_continue_count",
    "gold.evaluation_count",
    "guardian.config",
    "guardian.state",
    "context_pressure_last_level",
    "llm_request_render",
    "last_run_error",
    "last_run_status",
    "lifecycle",
    "pending_injected_messages",
    "placement",
    "project_resources_rendered",
    "prompt_component_flags",
    "prompt_component_lengths",
    "prompt_composer_version",
    "prompt_fingerprint",
    "permission.reexecute_request_generation",
    "permission.reexecute_tool_call_id",
    "resident_context",
    "resident_name",
    "responses.previous_response_id",
    "responsibility",
    "retry_resume_pending",
    "retry_resume_reason",
    "runtime.budget_exceeded_kind",
    "runtime.completion_reason",
    "runtime.kind",
    "runtime.session_start_source",
    "runtime.suspend_reason",
    "schedule_run_id",
    "skill.context",
    "spawned_by",
    "subagent_type",
    "task_list_version",
    "todo_list_version",
];

fn copied_session_snapshot(source: &Session, new_id: &str) -> Session {
    let now = Utc::now();
    let mut copy = source.clone();
    copy.authority_identity = SessionAuthorityIdentity::Ordinary;
    copy.supervisor_management = None;
    copy.id = new_id.to_string();
    copy.kind = SessionKind::Root;
    copy.parent_session_id = None;
    copy.parent_created_at = None;
    copy.root_session_id = new_id.to_string();
    copy.spawn_depth = 0;
    copy.title = format!("{} (copy)", source.title.trim_end());
    copy.title_version = 0;
    copy.title_generated = true;
    copy.metadata_version = 0;
    copy.root_mode_transition_epoch = 0;
    copy.root_mode_operations.clear();
    copy.pinned = false;
    copy.created_at = now;
    copy.updated_at = now;
    copy.pending_question = None;
    // A child budget belongs to its original tree. The independent root must
    // resolve the current model limit on its first execution instead.
    copy.token_budget = None;
    copy.resolved_token_budget = None;
    copy.agent_runtime_state = source.agent_runtime_state.as_ref().map(|state| {
        let mut clean = bamboo_domain::AgentRuntimeState::default();
        clean.set_permission_mode(state.effective_permission_mode());
        clean
    });
    copy.force_manual_compression = None;
    // Preserve every transcript message, but detach it from the source's
    // provider cache/compression epoch so the first copied turn is a clean
    // history reconstruction rather than a continuation of the source run.
    // A trailing system-resume user message is still pending execution. It is
    // control-plane state rather than completed conversation history, so strip
    // only the consecutive tail. A resume message followed by an assistant
    // response has already been consumed and remains part of the transcript.
    while copy
        .messages
        .last()
        .is_some_and(bamboo_domain::is_system_resume_message)
    {
        copy.messages.pop();
    }
    copy.clear_derived_context_state();
    // A copied conversation is a normalized history fork, not a continuation
    // of the source provider's native loading/cache epoch.
    copy.provider_transcript = Default::default();
    copy.model_context_state = None;
    copy.prompt_snapshot = None;
    for message in &mut copy.messages {
        message.compression_level = 0;
    }
    // Task progress/generations belong to the source execution control plane,
    // not to the copied conversation transcript.
    copy.task_list = None;

    for key in COPY_TRANSIENT_METADATA_KEYS {
        copy.metadata.remove(*key);
    }
    for key in bamboo_domain::PERMISSION_AUDIT_METADATA_KEYS {
        copy.metadata.remove(*key);
    }
    copy.metadata.retain(|key, _| {
        let durable_workflow_config = matches!(
            key.as_str(),
            "workflow.selection.v1"
                | "workflow.orchestration_opt_in"
                | "workflow.active.v1"
                | "workflow.active.snapshot.v1"
        );
        !key.starts_with("a2a.")
            && !key.starts_with("execute.")
            && !key.starts_with("external.")
            && !key.starts_with("gold.last_")
            && !key.starts_with("prefix_cache_")
            && !key.starts_with("runtime_prompt_")
            && !key.starts_with("skill_runtime_")
            && (!key.starts_with("workflow.") || durable_workflow_config)
    });
    if let Some(runtime) = copy.runtime_metadata.as_mut() {
        runtime.subagent_type = None;
        runtime.last_run_status = None;
        runtime.last_run_error = None;
        runtime.pending_injected_messages = None;
        runtime.task_list_version = None;
        runtime.todo_list_version = None;
        runtime.session_inbox_admission = None;
        if runtime.is_empty() {
            copy.runtime_metadata = None;
        }
    }
    copy
}

fn rewrite_attachment_session_urls(session: &mut Session, source_id: &str, new_id: &str) {
    let source_prefix = format!("bamboo-attachment://{source_id}/");
    let target_prefix = format!("bamboo-attachment://{new_id}/");
    for message in &mut session.messages {
        if let Some(parts) = message.content_parts.as_mut() {
            for part in parts {
                if let MessagePart::ImageUrl { image_url } = part {
                    if let Some(attachment_id) = image_url.url.strip_prefix(&source_prefix) {
                        image_url.url = format!("{target_prefix}{attachment_id}");
                    }
                }
            }
        }
        if let Some(results) = message.image_ocr.as_mut() {
            for result in results {
                if let Some(attachment_id) = result.image_url.strip_prefix(&source_prefix) {
                    result.image_url = format!("{target_prefix}{attachment_id}");
                }
            }
        }
    }
}

impl SessionStoreV2 {
    /// Open (or create) the V2 session store rooted at `bamboo_home_dir`.
    ///
    /// Loading the global index (`sessions.json`) is fault-tolerant, because it
    /// is only a cache over the authoritative per-session `session.json` files:
    /// - **missing** → start with a fresh empty index (normal first boot);
    /// - **valid** → use it as-is;
    /// - **corrupt/unparseable** → back it up to `sessions.json.bak`, log an
    ///   error, start empty, and rebuild the index from disk (see
    ///   [`Self::rebuild_index_from_disk`]) so a single bad byte can never make
    ///   the server refuse to boot or orphan intact sessions on disk.
    pub async fn new(bamboo_home_dir: PathBuf) -> io::Result<Self> {
        let sessions_dir = bamboo_home_dir.join("sessions");
        let index_path = bamboo_home_dir.join("sessions.json");
        let search_index = SessionSearchIndex::new(bamboo_home_dir.join("session_search.db"));

        fs::create_dir_all(&sessions_dir).await?;
        search_index.init().await?;

        // Index inspection and every decision that can publish, rename, or
        // replace sessions.json share the same cross-process claim. In
        // particular, a constructor that waited behind another process must
        // re-read the now-current file instead of publishing a stale empty or
        // corrupt-rebuild decision.
        let index_file_claim = lock_index_file_exclusive_at(&bamboo_home_dir).await?;

        // A corrupt index must not be boot-fatal: back it up and rebuild from
        // the on-disk session tree after construction. Only a *corrupt* file
        // triggers this; a *missing* one keeps the fresh-empty-index path.
        let mut needs_rebuild = false;
        let index = match fs::read_to_string(&index_path).await {
            Ok(raw) => match serde_json::from_str::<SessionsIndex>(&raw) {
                Ok(index) if index.version >= SESSIONS_INDEX_VERSION => index,
                Ok(index) => {
                    tracing::info!(
                        "migrating sessions index from version {} to version {} by rebuilding from session.json",
                        index.version,
                        SESSIONS_INDEX_VERSION,
                    );
                    needs_rebuild = true;
                    if index.rebuild_in_progress {
                        // Join/resume an existing rebuild without clearing
                        // entries already recovered or added by live writers.
                        index
                    } else {
                        let mut rebuilding = SessionsIndex::empty();
                        // Publish the old-version marker while the inspection
                        // claim is still held. Incremental rebuild writes keep
                        // this marker so a crash forces the next boot to resume.
                        rebuilding.version = index.version.min(SESSIONS_INDEX_VERSION - 1);
                        rebuilding.rebuild_in_progress = true;
                        persist_index_path_locked(&index_path, &rebuilding).await?;
                        rebuilding
                    }
                }
                Err(error) => {
                    // Best-effort backup so the corrupt bytes are preserved for
                    // forensics but no longer block the (about to be rebuilt)
                    // index. If the backup rename fails we still rebuild — the
                    // rebuild's fresh persist would overwrite the corrupt file
                    // anyway, and the session.json files remain untouched.
                    // NOTE: `fs::rename` clobbers any pre-existing
                    // `sessions.json.bak` (only the latest corruption is kept) —
                    // an accepted tradeoff for the recovery path.
                    let backup_path = bamboo_home_dir.join("sessions.json.bak");
                    match fs::rename(&index_path, &backup_path).await {
                        Ok(()) => tracing::error!(
                            "sessions.json is corrupt ({error}); backed up to {} and rebuilding \
                             the index by scanning the session tree",
                            backup_path.display()
                        ),
                        Err(rename_error) => tracing::error!(
                            "sessions.json is corrupt ({error}); failed to back it up to {} \
                             ({rename_error}); rebuilding the index from disk anyway",
                            backup_path.display()
                        ),
                    }
                    needs_rebuild = true;
                    let mut rebuilding = SessionsIndex::empty();
                    rebuilding.version = 0;
                    rebuilding.rebuild_in_progress = true;
                    // The corrupt-read decision, backup, and replacement marker
                    // are one claimed boundary. A waiting constructor re-reads
                    // this marker instead of acting on stale corrupt bytes.
                    persist_index_path_locked(&index_path, &rebuilding).await?;
                    rebuilding
                }
            },
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                let index = SessionsIndex::empty();
                // Persist immediately so "index is mandatory" holds from boot.
                // The missing-file decision and publish are indivisible with
                // respect to every other constructor/index writer.
                persist_index_path_locked(&index_path, &index).await?;
                index
            }
            Err(error) => return Err(error),
        };

        // Rebuild scanning and FTS work can be large. Release the global claim
        // after the atomic marker decision; each incremental index mutation
        // below takes only the ordinary short update_index claim and rebases
        // from disk, preserving concurrent live writes.
        drop(index_file_claim);

        let persistence_metrics = Arc::new(SessionPersistenceMetrics::default());
        let search_index_queue =
            SearchIndexQueue::new(search_index.clone(), persistence_metrics.clone());
        #[cfg(test)]
        let task_write_hook = task_publication_lifetime_tests::constructor_hook(&bamboo_home_dir);
        let storage = Self {
            bamboo_home_dir,
            sessions_dir,
            index_path,
            search_index,
            search_index_queue,
            index: RwLock::new(index),
            write_lock: Mutex::new(()),
            session_write_locks: Arc::new(DashMap::new()),
            persistence_metrics,
            session_lifecycle_lock: std::sync::Arc::new(RwLock::new(())),
            runtime_task_transaction_gate: std::sync::Arc::new(RwLock::new(())),
            runtime_task_recovery_required: AtomicBool::new(false),
            #[cfg(test)]
            runtime_task_faults: std::sync::Mutex::new(Vec::new()),
            #[cfg(test)]
            runtime_task_first_write_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            runtime_task_durability_events: std::sync::Mutex::new(Vec::new()),
            #[cfg(any(test, feature = "test-utils"))]
            full_save_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            root_publication_fault: std::sync::Mutex::new(None),
            #[cfg(test)]
            root_tool_proof_fault: std::sync::Mutex::new(None),
            #[cfg(test)]
            supervisor_proof_fault: std::sync::Mutex::new(None),
            #[cfg(test)]
            management_write_hook: std::sync::Mutex::new(None),
            #[cfg(test)]
            actor_write_hook: std::sync::Mutex::new(None),
            #[cfg(test)]
            transcript_write_hook: std::sync::Mutex::new(None),
            #[cfg(any(test, feature = "test-utils"))]
            child_wait_registration_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            default_write_hook: std::sync::Mutex::new(None),
            #[cfg(test)]
            child_delete_hook: std::sync::Mutex::new(None),
            #[cfg(test)]
            migration_scan_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            task_write_hook: std::sync::Mutex::new(task_write_hook),
            #[cfg(test)]
            census_read_hook: std::sync::Mutex::new(None),
        };

        // Create and permission the private journal directory once at store
        // initialization. Clean hot-path reads only probe it and never repeat
        // mkdir/chmod work; journal creation also revalidates it before write.
        storage.ensure_runtime_task_transaction_dir().await?;
        storage.ensure_session_copy_transaction_dir().await?;
        storage.ensure_session_write_lock_dir().await?;

        // Constructor recovery takes the same cross-process exclusive gate as
        // a live commit. A second store can therefore recover an orphan, but
        // can never mistake another process's in-flight journal for one.
        {
            let _lifecycle = storage.lock_session_lifecycle_exclusive().await?;
            let _runtime_task = storage.lock_runtime_task_transaction_exclusive().await?;
            // Upgrade old valid Root pairs before journal recovery invokes the
            // strict sidecar writer. Scan again afterward for any Root a copy
            // recovery completed, then publish the one-shot migration marker.
            storage.migrate_root_tool_authority_proofs(false).await?;
            storage.migrate_supervisor_proof(false).await?;
            storage
                .recover_all_runtime_task_transactions_locked(&_runtime_task)
                .await?;
            storage
                .recover_all_session_copy_transactions_locked()
                .await?;
            storage.migrate_root_tool_authority_proofs(true).await?;
            storage.migrate_supervisor_proof(true).await?;
            storage.reconcile_root_revocations().await?;
        }

        if needs_rebuild {
            storage.rebuild_index_from_disk().await?;
            // Compatibility rebuild reads can recover children or a main-file
            // fallback from an unavailable recreated Root. Reconcile the same
            // canonical revocation evidence after the scan as well, without
            // introducing another durable quarantine or recovery state.
            let _lifecycle = storage.lock_session_lifecycle_exclusive().await?;
            let _runtime_task = storage.lock_runtime_task_transaction_exclusive().await?;
            storage
                .recover_all_runtime_task_transactions_locked(&_runtime_task)
                .await?;
            storage
                .recover_all_session_copy_transactions_locked()
                .await?;
            storage.reconcile_root_revocations().await?;
        }

        Ok(storage)
    }

    /// Rebuild the global index by scanning the on-disk session tree.
    ///
    /// Called by [`Self::new`] after a corrupt `sessions.json` was backed up and
    /// replaced with an empty index. The layout is deterministic:
    /// - `sessions/<root_id>/session.json`
    /// - `sessions/<root_id>/children/<child_id>/session.json`
    ///
    /// so every session is recoverable without the index. Each session is loaded
    /// from its directory via [`Self::load_session_from_dir`] — which parses
    /// `session.json` and **overlays the `runtime.json` sidecar exactly like
    /// [`Storage::load_session`]**, so recovered index entries reflect the
    /// freshest control-plane (a runtime-only save updates only the sidecar) and
    /// agree with the FTS index that [`Self::rebuild_search_index`] builds via
    /// `load_session`. The result is folded back in via the guarded,
    /// no-regression index repair path with the same `rel_path`
    /// [`Self::save_session`] would compute — derived from the on-disk directory
    /// names (the physical location), which is what `abs_path_from_rel` + load
    /// rely on. A single unreadable/corrupt session is skipped with a warning,
    /// and directory-level read errors are logged + tolerated (never
    /// `?`-propagated) so one bad file/dir never re-introduces a boot-fatal
    /// failure or aborts recovery of the rest.
    /// Explicit recovery after a verified offline Session tree import. Reuses
    /// the normal derived-index rebuild and its lifecycle/index publication
    /// locks; callers must stop the importing Host before copying the tree.
    /// This does not confer execution, Supervisor, or owned-Inbox authority.
    pub async fn rebuild_index_from_disk(&self) -> io::Result<()> {
        let mut recovered = 0usize;

        let mut root_dirs = match fs::read_dir(&self.sessions_dir).await {
            Ok(rd) => rd,
            // No sessions directory at all — nothing to recover.
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
            Err(error) => return Err(error),
        };

        loop {
            // Directory-iteration errors are tolerated, not `?`-propagated: an
            // error here would abort the whole rebuild and make `new()` return
            // Err — the exact boot-fatal failure this rebuild exists to prevent.
            let root_entry = match root_dirs.next_entry().await {
                Ok(Some(entry)) => entry,
                Ok(None) => break,
                Err(error) => {
                    tracing::warn!("index rebuild: error scanning sessions dir: {error}");
                    break;
                }
            };
            if !root_entry
                .file_type()
                .await
                .map(|t| t.is_dir())
                .unwrap_or(false)
            {
                continue;
            }
            let Ok(root_id) = root_entry.file_name().into_string() else {
                // Non-UTF-8 directory name cannot be a valid session id.
                continue;
            };

            // Re-probe and publish under the shared lifecycle boundary so a
            // concurrent exclusive delete either completes before this read or
            // removes the entry after this upsert; a late rebuild can never
            // resurrect a deleted directory.
            match self
                .rebuild_index_entry_from_dir(
                    &root_entry.path(),
                    &root_id,
                    Self::root_rel_path(&root_id),
                )
                .await
            {
                Ok(true) => recovered += 1,
                Ok(false) => {}
                Err(error) => {
                    tracing::warn!("index rebuild: failed to index root {root_id}: {error}")
                }
            }

            // Recover its children (a flat `children/<child_id>/` layer).
            let children_dir = root_entry.path().join("children");
            let mut child_dirs = match fs::read_dir(&children_dir).await {
                Ok(rd) => rd,
                Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
                Err(error) => {
                    tracing::warn!("index rebuild: cannot read children of {root_id}: {error}");
                    continue;
                }
            };
            loop {
                let child_entry = match child_dirs.next_entry().await {
                    Ok(Some(entry)) => entry,
                    Ok(None) => break,
                    Err(error) => {
                        tracing::warn!(
                            "index rebuild: error scanning children of {root_id}: {error}"
                        );
                        break;
                    }
                };
                if !child_entry
                    .file_type()
                    .await
                    .map(|t| t.is_dir())
                    .unwrap_or(false)
                {
                    continue;
                }
                let Ok(child_id) = child_entry.file_name().into_string() else {
                    continue;
                };
                match self
                    .rebuild_index_entry_from_dir(
                        &child_entry.path(),
                        &child_id,
                        Self::child_rel_path(&root_id, &child_id),
                    )
                    .await
                {
                    Ok(true) => recovered += 1,
                    Ok(false) => {}
                    Err(error) => {
                        tracing::warn!("index rebuild: failed to index child {child_id}: {error}")
                    }
                }
            }
        }

        // The per-entry lifecycle -> shared-Task probes above must not be held
        // across this final phase: deletion owns lifecycle -> shared-Task, so
        // taking Task first and then attempting another lifecycle probe would
        // invert that order. A single shared Task guard here instead seals the
        // scan result against a new paired transaction and rejects any durable
        // journal left by a transaction that crashed between entry probes. In
        // that case the old rebuild marker remains retryable for the next boot.
        {
            let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;

            // Re-materialize sessions.json even when nothing was recovered (we
            // may have renamed the only copy to sessions.json.bak), so the
            // "index file always exists after boot" invariant holds.
            self.update_index(|index| {
                // Publishing the current version is the commit point for a complete rebuild.
                // `persist_index_locked` writes a temp file and atomically renames it.
                index.version = SESSIONS_INDEX_VERSION;
                index.rebuild_in_progress = false;
                Ok(())
            })
            .await?;
        }

        tracing::info!("index rebuild from disk complete: recovered {recovered} session(s)");

        // Pair transactions only modify Task list/generation, neither of which
        // is indexed by FTS. Keep this best-effort pass outside the final guard
        // so the server's background rebuild retains per-session lock scope.
        if let Err(error) = self.rebuild_search_index().await {
            tracing::warn!("index rebuild: failed to rebuild search index: {error}");
        }
        Ok(())
    }

    async fn rebuild_index_entry_from_dir(
        &self,
        abs_dir: &Path,
        session_id: &str,
        rel_path: String,
    ) -> io::Result<bool> {
        let _lifecycle = self.lock_session_lifecycle_shared().await?;
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let Some(session) = self.load_session_from_dir(abs_dir, session_id).await else {
            return Ok(false);
        };
        self.repair_index_from_authoritative_session(&session, rel_path)
            .await?;
        Ok(true)
    }

    /// Load a session from a known on-disk directory during index rebuild,
    /// mirroring [`Storage::load_session`] but resolving the directory by scan
    /// (the index is not yet populated during rebuild): parse `session.json`,
    /// overlay the `runtime.json` sidecar via the shared
    /// [`Self::read_runtime_sidecar_at`] + [`overlay_runtime_sidecar`] so the
    /// freshest control-plane wins, then drop a stale Root token_budget. A
    /// missing `session.json` yields `None` silently; a corrupt/unreadable one is
    /// skipped with a warning; a sidecar read error degrades to "no sidecar"
    /// rather than failing recovery. `id` is used only for log context.
    async fn load_session_from_dir(&self, abs_dir: &Path, id: &str) -> Option<Session> {
        let raw = match fs::read_to_string(abs_dir.join("session.json")).await {
            Ok(raw) => raw,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return None,
            Err(error) => {
                tracing::warn!("index rebuild: skipping unreadable session {id}: {error}");
                return None;
            }
        };
        if let Err(error) = compact_main::validate_full_main(raw.as_bytes()) {
            tracing::warn!("index rebuild: skipping invalid compact Main for {id}: {error}");
            return None;
        }
        let mut main: Session = match serde_json::from_str(&raw) {
            Ok(session) => session,
            Err(error) => {
                tracing::warn!("index rebuild: skipping corrupt session {id}: {error}");
                return None;
            }
        };
        match self.session_lifetime_is_live(&main).await {
            Ok(true) => {}
            Ok(false) => return None,
            Err(error) => {
                tracing::warn!("index rebuild: skipping unavailable Root lifetime {id}: {error}");
                return None;
            }
        }
        let sidecar =
            match Self::read_runtime_sidecar_at(&abs_dir.join(RUNTIME_SIDECAR_FILE), id).await {
                Ok(sidecar) => sidecar,
                Err(error) => {
                    tracing::warn!("index rebuild: cannot read runtime sidecar for {id}: {error}");
                    None
                }
            };
        if let Err(error) = supervisor::validate_overlay(&main, sidecar.as_ref()) {
            tracing::warn!("index rebuild: skipping invalid authority for {id}: {error}");
            return None;
        }
        if let Err(error) = self
            .validate_root_tool_authority_overlay(id, &main, sidecar.as_ref())
            .await
        {
            // Preserve a valid Root's lookup row so direct reads report the
            // concrete recovery conflict. Never project an unverified runtime
            // sidecar into the rebuildable index.
            if main.kind == SessionKind::Root && main.id == id {
                tracing::warn!("index rebuild: Root {id} is unavailable: {error}");
                main.clear_stale_root_token_budget();
                return Some(main);
            }
            tracing::warn!("index rebuild: skipping invalid authority for {id}: {error}");
            return None;
        }
        let mut session = overlay_runtime_sidecar(main, sidecar);
        session.clear_stale_root_token_budget();
        Some(session)
    }

    /// Strict operation loader: unlike rebuild recovery, copy must distinguish
    /// a missing source from corrupt/unreadable authoritative state and must
    /// never silently fall back to stale `session.json` control-plane data.
    async fn load_session_from_dir_strict(
        &self,
        abs_dir: &Path,
        id: &str,
        expected_kind: SessionKind,
        expected_root_id: &str,
    ) -> io::Result<Option<Session>> {
        let raw = match fs::read_to_string(abs_dir.join("session.json")).await {
            Ok(raw) => raw,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        compact_main::validate_full_main(raw.as_bytes())?;
        let mut main: Session = serde_json::from_str(&raw).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid source session.json: {error}"),
            )
        })?;
        let canonical_legacy_root = expected_kind == SessionKind::Root
            && expected_root_id == id
            && main.root_session_id.is_empty();
        if main.id != id
            || main.kind != expected_kind
            || (!canonical_legacy_root && main.root_session_id != expected_root_id)
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "session identity does not match its expected canonical path",
            ));
        }
        // `root_session_id` predates some on-disk root sessions and therefore
        // deserializes to an empty string through serde(default). Only a root
        // found at its own canonical root path may use that legacy encoding;
        // normalize it before comparing/overlaying the runtime sidecar.
        if canonical_legacy_root {
            main.root_session_id = id.to_string();
        }
        if !self.session_lifetime_is_live(&main).await? {
            return Ok(None);
        }
        let runtime_path = abs_dir.join(RUNTIME_SIDECAR_FILE);
        let sidecar = match fs::read_to_string(&runtime_path).await {
            Ok(raw) => {
                let mut sidecar: Session = serde_json::from_str(&raw).map_err(|error| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("invalid source runtime.json: {error}"),
                    )
                })?;
                if expected_kind == SessionKind::Root
                    && expected_root_id == id
                    && sidecar.root_session_id.is_empty()
                {
                    sidecar.root_session_id = id.to_string();
                }
                if sidecar.id != id
                    || sidecar.kind != main.kind
                    || sidecar.root_session_id != main.root_session_id
                    || sidecar.parent_session_id != main.parent_session_id
                    || sidecar.parent_created_at != main.parent_created_at
                    || sidecar.spawn_depth != main.spawn_depth
                    || sidecar.created_at != main.created_at
                {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "source runtime sidecar identity does not match session.json",
                    ));
                }
                Some(sidecar)
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => return Err(error),
        };
        supervisor::validate_overlay(&main, sidecar.as_ref())?;
        self.validate_root_tool_authority_overlay(id, &main, sidecar.as_ref())
            .await?;
        let mut session = overlay_runtime_sidecar(main, sidecar);
        session.clear_stale_root_token_budget();
        Ok(Some(session))
    }

    async fn directory_has_regular_files(path: &Path) -> io::Result<bool> {
        let mut entries = match fs::read_dir(path).await {
            Ok(entries) => entries,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
        };
        while let Some(entry) = entries.next_entry().await? {
            if entry.file_type().await?.is_file() {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn copy_source_identity_from_rel(
        source_id: &str,
        source_rel: &str,
    ) -> io::Result<(SessionKind, String)> {
        let parts = source_rel.split('/').collect::<Vec<_>>();
        match parts.as_slice() {
            ["sessions", id] if *id == source_id => Ok((SessionKind::Root, source_id.to_string())),
            ["sessions", root_id, "children", id] if *id == source_id => {
                validate_session_id(root_id)?;
                Ok((SessionKind::Child, (*root_id).to_string()))
            }
            _ => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "source session index path is not canonical",
            )),
        }
    }

    pub fn search_index(&self) -> &SessionSearchIndex {
        &self.search_index
    }

    /// Wait until every search-index mutation accepted before this observation
    /// has completed or exhausted its bounded retries. Durable session reads do
    /// not require this; it exists for callers that require search read-after-write.
    pub async fn flush_search_index(&self) {
        self.search_index_queue.flush().await;
    }

    /// Read the durable source revision paired with a Session's derived search
    /// snapshot. Callers compare this marker with the revision stored in SQLite
    /// after a queue flush; absence or mismatch means search completeness is
    /// unknown and must fail over to canonical Session data.
    pub async fn search_source_revision(&self, session_id: &str) -> io::Result<Option<String>> {
        let Some(session_json) = self.session_json_path(session_id).await? else {
            return Ok(None);
        };
        let session_dir = session_json.parent().ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidData, "session path has no parent")
        })?;
        match fs::read_to_string(session_dir.join(SEARCH_INDEX_REVISION_FILE)).await {
            Ok(revision) => {
                let revision = revision.trim();
                if revision.is_empty() {
                    Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "empty search-index revision marker",
                    ))
                } else {
                    Ok(Some(revision.to_string()))
                }
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error),
        }
    }

    pub fn persistence_metrics(&self) -> SessionPersistenceMetricsSnapshot {
        self.persistence_metrics.snapshot(
            self.search_index_queue.pending_len(),
            self.search_index_queue.in_flight.load(Ordering::Relaxed),
        )
    }

    pub fn record_session_create_latency(&self, duration: Duration) {
        self.persistence_metrics.record_create_latency(duration);
    }

    /// Publish a tiny, atomic revision marker after `session.json` is visible.
    /// The FTS worker checks this marker while holding SQLite's write
    /// transaction, so a delayed upsert cannot resurrect a deleted session or
    /// overwrite a later full save. Directory durability is not required for
    /// the marker: startup rebuild publishes a fresh revision after a crash.
    async fn publish_search_revision(&self, abs_dir: &Path) -> io::Result<(PathBuf, String)> {
        let revision_path = abs_dir.join(SEARCH_INDEX_REVISION_FILE);
        let revision = Uuid::new_v4().to_string();
        let tmp = revision_path.with_extension(format!("tmp.{}", Uuid::new_v4()));
        if let Err(error) = fs::write(&tmp, revision.as_bytes()).await {
            let _ = fs::remove_file(&tmp).await;
            return Err(error);
        }
        if let Err(error) = atomic_rename(&tmp, &revision_path).await {
            let _ = fs::remove_file(&tmp).await;
            return Err(error);
        }
        Ok((revision_path, revision))
    }

    async fn acquire_session_write_lock(
        &self,
        session_id: &str,
        kind: SaveKind,
    ) -> io::Result<SessionWriteGuard> {
        self.acquire_session_lock(session_id, Some(kind)).await
    }

    async fn acquire_session_maintenance_lock(
        &self,
        session_id: &str,
    ) -> io::Result<SessionWriteGuard> {
        self.acquire_session_lock(session_id, None).await
    }

    async fn acquire_actor_tree_write_guard(
        &self,
        root_id: &str,
    ) -> io::Result<ActorTreeWriteGuard> {
        validate_session_id(root_id)?;
        let mut hash = Sha256::new();
        hash.update(root_id.as_bytes());
        let directory = self.bamboo_home_dir.join(ACTOR_TREE_LOCK_DIR);
        fs::create_dir_all(&directory).await?;
        let path = directory.join(format!("{:x}.lock", hash.finalize()));
        let file = tokio::task::spawn_blocking(move || {
            let file = std::fs::OpenOptions::new()
                .create(true)
                .truncate(false)
                .read(true)
                .write(true)
                .open(path)?;
            FileExt::lock_exclusive(&file)?;
            Ok::<_, io::Error>(file)
        })
        .await
        .map_err(|error| other_io_error(format!("join Actor tree lock task: {error}")))??;
        Ok(ActorTreeWriteGuard { file })
    }

    async fn canonical_actor_tree_root(&self, root_id: &str) -> io::Result<Session> {
        let root = self
            .load_session_from_dir_strict(
                &self.sessions_dir.join(root_id),
                root_id,
                SessionKind::Root,
                root_id,
            )
            .await?
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Actor tree Root is missing"))?;
        if !self.session_lifetime_is_live(&root).await? {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Actor tree Root was revoked",
            ));
        }
        Ok(root)
    }

    /// An isolated worker cache stores the host's canonical Child without a
    /// local Root. Such a cache has no public Actor tree or cursor to advance.
    /// Only the bare `children/` layout qualifies: any Root file, index entry,
    /// or revocation evidence means a Host Root is missing or damaged instead.
    async fn actor_tree_root_for_child_write(&self, root_id: &str) -> io::Result<Option<Session>> {
        match self.canonical_actor_tree_root(root_id).await {
            Ok(root) => return Ok(Some(root)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        if self.get_index_entry(root_id).await.is_some()
            || self.root_revocation(root_id).await?.is_some()
        {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Actor tree Root is missing",
            ));
        }
        let directory = self.sessions_dir.join(root_id);
        let metadata = fs::symlink_metadata(&directory).await?;
        if !metadata.file_type().is_dir() {
            return Err(other_io_error(
                "Actor tree Root path is not a real directory",
            ));
        }
        let mut entries = fs::read_dir(&directory).await?;
        while let Some(entry) = entries.next_entry().await? {
            if entry.file_name() != "children" || !entry.file_type().await?.is_dir() {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    "Actor tree Root is missing",
                ));
            }
        }
        Ok(None)
    }

    /// Caller holds lifecycle, Task, exact Session and Root tree locks, in that
    /// order. This publication precedes every public tree write, so an
    /// interrupted operation creates at most an unnecessary gap.
    async fn bump_actor_tree_revision(&self, root: &Session) -> io::Result<()> {
        if root.kind != SessionKind::Root
            || (!root.root_session_id.is_empty() && root.id != root.root_session_id)
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Actor tree revision requires canonical Root identity",
            ));
        }
        let path = self
            .sessions_dir
            .join(&root.id)
            .join(ACTOR_TREE_REVISION_FILE);
        let mut marker = match fs::symlink_metadata(&path).await {
            Ok(metadata) if metadata.file_type().is_file() => {
                let bytes = fs::read(&path).await?;
                if bytes.len() > 4096 {
                    return Err(other_io_error("Actor tree revision marker is oversized"));
                }
                let marker: ActorTreeRevision = serde_json::from_slice(&bytes)
                    .map_err(|_| other_io_error("Actor tree revision marker is invalid"))?;
                if marker.version != 1
                    || marker.root_id != root.id
                    || marker.root_created_at != root.created_at
                    || marker.revision == 0
                    || marker.revision > MAX_ACTOR_TREE_REVISION
                {
                    return Err(other_io_error("Actor tree revision identity mismatch"));
                }
                marker
            }
            Ok(_) => return Err(other_io_error("Actor tree revision marker is not regular")),
            Err(error) if error.kind() == io::ErrorKind::NotFound => ActorTreeRevision::new(root),
            Err(error) => return Err(error),
        };
        if path.exists() {
            marker.revision = marker
                .revision
                .checked_add(1)
                .filter(|revision| *revision <= MAX_ACTOR_TREE_REVISION)
                .ok_or_else(|| other_io_error("Actor tree revision exhausted"))?;
        }
        marker.project_id = normalized_project_id(root);
        let bytes = serde_json::to_vec(&marker).map_err(io::Error::other)?;
        durable_atomic_write(&path, &bytes).await
    }

    /// For a Root that is still invisible in a staging directory. The marker
    /// and both Session files become visible together at directory rename.
    async fn stage_actor_tree_revision(directory: &Path, root: &Session) -> io::Result<()> {
        let marker = ActorTreeRevision::new(root);
        let bytes = serde_json::to_vec(&marker).map_err(io::Error::other)?;
        durable_atomic_write(&directory.join(ACTOR_TREE_REVISION_FILE), &bytes).await
    }

    async fn open_session_write_lock_file_at(path: PathBuf) -> io::Result<std::fs::File> {
        tokio::task::spawn_blocking(move || {
            let file = std::fs::OpenOptions::new()
                .create(true)
                .truncate(false)
                .read(true)
                .write(true)
                .open(path)?;
            FileExt::lock_exclusive(&file)?;
            Ok(file)
        })
        .await
        .map_err(|error| other_io_error(format!("join session write-lock task: {error}")))?
    }

    async fn open_session_write_lock_file(&self, session_id: &str) -> io::Result<std::fs::File> {
        let path = self.session_write_lock_path(session_id);
        match Self::open_session_write_lock_file_at(path.clone()).await {
            Ok(file) => Ok(file),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                self.ensure_session_write_lock_dir().await?;
                Self::open_session_write_lock_file_at(path).await
            }
            Err(error) => Err(error),
        }
    }

    async fn acquire_session_lock(
        &self,
        session_id: &str,
        kind: Option<SaveKind>,
    ) -> io::Result<SessionWriteGuard> {
        validate_session_id(session_id)?;
        let waiting = kind.map(|_| {
            self.persistence_metrics
                .waiting_saves
                .fetch_add(1, Ordering::Relaxed);
            WaitingSaveCounter {
                metrics: self.persistence_metrics.clone(),
            }
        });
        let started = Instant::now();
        let lock = self
            .session_write_locks
            .entry(session_id.to_string())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .clone();
        // Arm cleanup before either the process-local or cross-process wait.
        let mut session_guard = SessionWriteGuard {
            guard: None,
            file: None,
            locks: self.session_write_locks.clone(),
            session_id: session_id.to_string(),
            kind: None,
            acquired: Instant::now(),
            metrics: self.persistence_metrics.clone(),
        };
        session_guard.guard = Some(lock.lock_owned().await);
        let file = self.open_session_write_lock_file(session_id).await?;
        session_guard.file = Some(file);
        drop(waiting);
        if let Some(kind) = kind {
            self.persistence_metrics
                .active_saves
                .fetch_add(1, Ordering::Relaxed);
            let waited = started.elapsed();
            self.persistence_metrics.record_lock_wait(kind, waited);
            tracing::debug!(
                target: "bamboo.session_persistence",
                session_id,
                save_type = kind.as_str(),
                phase = "session_lock_acquired",
                lock_wait_ms = waited.as_millis() as u64,
                waiting_saves = self.persistence_metrics.waiting_saves.load(Ordering::Relaxed),
                "session persistence lock acquired"
            );
            session_guard.kind = Some(kind);
            session_guard.acquired = Instant::now();
        }
        Ok(session_guard)
    }

    #[cfg(any(test, feature = "test-utils"))]
    #[doc(hidden)]
    pub fn pause_full_save_before_filesystem_commit_for_test(
        &self,
        session_id: &str,
    ) -> (Arc<tokio::sync::Barrier>, Arc<tokio::sync::Barrier>) {
        let reached = Arc::new(tokio::sync::Barrier::new(2));
        let release = Arc::new(tokio::sync::Barrier::new(2));
        *self.full_save_pause.lock().expect("full save pause lock") = Some(FullSavePause {
            session_id: session_id.to_string(),
            reached: reached.clone(),
            release: release.clone(),
        });
        (reached, release)
    }

    #[cfg(any(test, feature = "test-utils"))]
    async fn maybe_pause_full_save_before_filesystem_commit(&self, session_id: &str) {
        let pause = {
            let mut configured = self.full_save_pause.lock().expect("full save pause lock");
            if configured
                .as_ref()
                .is_some_and(|pause| pause.session_id == session_id)
            {
                configured.take()
            } else {
                None
            }
        };
        if let Some(pause) = pause {
            pause.reached.wait().await;
            pause.release.wait().await;
        }
    }

    pub fn bamboo_home_dir(&self) -> &Path {
        &self.bamboo_home_dir
    }

    async fn open_session_lifecycle_file(&self, exclusive: bool) -> io::Result<std::fs::File> {
        let path = self.bamboo_home_dir.join(SESSION_LIFECYCLE_LOCK_FILE);
        tokio::task::spawn_blocking(move || {
            let file = std::fs::OpenOptions::new()
                .create(true)
                .truncate(false)
                .read(true)
                .write(true)
                .open(&path)?;
            if exclusive {
                FileExt::lock_exclusive(&file)?;
            } else {
                FileExt::lock_shared(&file)?;
            }
            Ok(file)
        })
        .await
        .map_err(|error| other_io_error(format!("join session lifecycle lock task: {error}")))?
    }

    async fn open_runtime_task_transaction_file(
        &self,
        exclusive: bool,
    ) -> io::Result<std::fs::File> {
        let path = self
            .bamboo_home_dir
            .join(RUNTIME_TASK_TRANSACTION_LOCK_FILE);
        let open = |path: PathBuf| async move {
            tokio::task::spawn_blocking(move || {
                let file = std::fs::OpenOptions::new()
                    .create(true)
                    .truncate(false)
                    .read(true)
                    .write(true)
                    .open(&path)?;
                if exclusive {
                    FileExt::lock_exclusive(&file)?;
                } else {
                    FileExt::lock_shared(&file)?;
                }
                Ok::<_, io::Error>(file)
            })
            .await
            .map_err(|error| other_io_error(format!("join runtime Task lock task: {error}")))?
        };

        match open(path.clone()).await {
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                // Keep the existing save-session recovery contract when an
                // embedding removes an otherwise idle Bamboo home between
                // construction and first use. The normal hot path performs no
                // mkdir; only a missing lock-file parent takes this retry.
                fs::create_dir_all(&self.bamboo_home_dir).await?;
                open(path).await
            }
            result => result,
        }
    }

    async fn lock_index_file_exclusive(&self) -> io::Result<SessionIndexFileGuard> {
        lock_index_file_exclusive_at(&self.bamboo_home_dir).await
    }

    pub(crate) async fn lock_session_lifecycle_shared(
        &self,
    ) -> io::Result<SessionLifecycleReadGuard> {
        let process = self.session_lifecycle_lock.clone().read_owned().await;
        let file = self.open_session_lifecycle_file(false).await?;
        Ok(SessionLifecycleReadGuard {
            _process: process,
            file,
        })
    }

    /// Validate both observations under the locks held through Inbox commit.
    /// Private canonical reads avoid reentering Task or Session locks.
    pub(crate) async fn lock_peer_delivery(
        &self,
        source: &bamboo_domain::ActorSession,
        target: &bamboo_domain::ActorSession,
        reply_to: Option<&SessionMessageEnvelope>,
    ) -> io::Result<PeerDeliveryGuard> {
        let denied = || other_io_error("peer Session identity or tree changed");
        if source.actor_id == target.actor_id
            || source.root_actor_id != target.root_actor_id
            || source.project_id != target.project_id
        {
            return Err(denied());
        }
        for id in [&source.actor_id, &target.actor_id, &source.root_actor_id] {
            validate_session_id(id)?;
        }
        let matches = |current: &bamboo_domain::ActorSession,
                       expected: &bamboo_domain::ActorSession| {
            current.schema_version == expected.schema_version
                && current.actor_id == expected.actor_id
                && current.session_created_at == expected.session_created_at
                && current.parent_actor_id == expected.parent_actor_id
                && current.root_actor_id == expected.root_actor_id
                && current.spawn_depth == expected.spawn_depth
                && current.project_id == expected.project_id
        };
        let lifecycle = self.lock_session_lifecycle_shared().await?;
        let task = self.lock_runtime_task_sidecar_shared().await?;
        let mut ids = vec![(0, source.root_actor_id.as_str())];
        for expected in [source, target] {
            let current = self
                .peer_delivery_actor(&expected.actor_id, &expected.root_actor_id)
                .await?;
            if !matches(&current, expected) {
                return Err(denied());
            }
            ids.push((current.spawn_depth, expected.actor_id.as_str()));
        }
        // ParentQuestion also locks ancestor before child. Canonical depths
        // prevent forged observations from selecting a conflicting order.
        ids.sort_unstable();
        ids.dedup();
        let mut sessions = Vec::with_capacity(ids.len());
        for (_, id) in ids {
            sessions.push(self.acquire_session_maintenance_lock(id).await?);
        }
        // Writers take the same tree lock after their Session lock. It freezes
        // ancestor context without acquiring ancestor Session locks out of order.
        let tree = self
            .acquire_actor_tree_write_guard(&source.root_actor_id)
            .await?;
        let guard = PeerDeliveryGuard {
            inbox_dir: self
                .abs_path_from_rel(&if target.actor_id == target.root_actor_id {
                    Self::root_rel_path(&target.actor_id)
                } else {
                    Self::child_rel_path(&target.root_actor_id, &target.actor_id)
                })
                .join("inbox"),
            tree: Some(tree),
            sessions,
            _task: task,
            _lifecycle: lifecycle,
        };
        for expected in [source, target] {
            let mut current = self
                .peer_delivery_actor(&expected.actor_id, &expected.root_actor_id)
                .await?;
            if !matches(&current, expected) {
                return Err(denied());
            }
            let mut seen = HashSet::from([current.actor_id.clone()]);
            while let Some(parent_id) = &current.parent_actor_id {
                if !seen.insert(parent_id.clone()) || seen.len() > 5000 {
                    return Err(denied());
                }
                let parent = self
                    .peer_delivery_actor(parent_id, &expected.root_actor_id)
                    .await?;
                // Preserve the existing owned-tree reader's legacy semantics:
                // no new parent_created_at or Actor-ledger prerequisite.
                if parent.project_id != expected.project_id
                    || parent.spawn_depth.checked_add(1) != Some(current.spawn_depth)
                    || parent.session_created_at > current.session_created_at
                {
                    return Err(denied());
                }
                current = parent;
            }
            if current.actor_id != expected.root_actor_id
                || current.spawn_depth != 0
                || seen.len() != expected.spawn_depth as usize + 1
            {
                return Err(denied());
            }
        }
        if let Some(proof) = reply_to {
            // Use a private canonical read while the source Session writer and
            // lifecycle locks are retained. Reentering the public loader could
            // deadlock behind a queued lifecycle writer. The same guard keeps
            // this received proof present through the physical Inbox commit.
            let current = self
                .peer_delivery_session(&source.actor_id, &source.root_actor_id)
                .await?;
            if !current
                .messages
                .iter()
                .any(|message| is_matching_session_message(message, proof))
            {
                return Err(other_io_error("peer reply proof changed before admission"));
            }
        }
        Ok(guard)
    }

    async fn peer_delivery_actor(
        &self,
        id: &str,
        root_id: &str,
    ) -> io::Result<bamboo_domain::ActorSession> {
        let session = self.peer_delivery_session(id, root_id).await?;
        bamboo_domain::ActorSession::from_session(&session)
            .map_err(|error| other_io_error(error.to_string()))
    }

    async fn peer_delivery_session(&self, id: &str, root_id: &str) -> io::Result<Session> {
        let kind = if id == root_id {
            SessionKind::Root
        } else {
            SessionKind::Child
        };
        let rel = if kind == SessionKind::Root {
            Self::root_rel_path(id)
        } else {
            Self::child_rel_path(root_id, id)
        };
        let session = self
            .load_session_from_dir_strict(&self.abs_path_from_rel(&rel), id, kind, root_id)
            .await?
            .ok_or_else(|| other_io_error("peer Session no longer exists"))?;
        if session
            .runtime_metadata
            .as_ref()
            .and_then(|m| m.project_id.as_ref())
            .zip(session.metadata.get("project_id"))
            .is_some_and(|(typed, legacy)| typed != legacy)
        {
            return Err(other_io_error("peer Session Project mirror changed"));
        }
        Ok(session)
    }

    async fn lock_session_lifecycle_exclusive(&self) -> io::Result<SessionLifecycleWriteGuard> {
        let process = self.session_lifecycle_lock.clone().write_owned().await;
        let file = self.open_session_lifecycle_file(true).await?;
        Ok(SessionLifecycleWriteGuard {
            _process: process,
            file,
        })
    }

    async fn lock_runtime_task_transaction_shared(
        &self,
    ) -> io::Result<RuntimeTaskTransactionReadGuard> {
        let process = self
            .runtime_task_transaction_gate
            .clone()
            .read_owned()
            .await;
        let file = self.open_runtime_task_transaction_file(false).await?;
        Ok(RuntimeTaskTransactionReadGuard {
            _process: process,
            file,
        })
    }

    async fn lock_runtime_task_transaction_exclusive(
        &self,
    ) -> io::Result<RuntimeTaskTransactionWriteGuard> {
        let process = self
            .runtime_task_transaction_gate
            .clone()
            .write_owned()
            .await;
        let file = self.open_runtime_task_transaction_file(true).await?;
        Ok(RuntimeTaskTransactionWriteGuard {
            _lease: Arc::new(RuntimeTaskTransactionWriteLease {
                _process: process,
                file,
            }),
        })
    }

    pub fn index_path(&self) -> &Path {
        &self.index_path
    }

    pub async fn rebuild_search_index(&self) -> io::Result<()> {
        let session_ids = {
            let index = self.index.read().await;
            index.sessions.keys().cloned().collect::<Vec<_>>()
        };
        for session_id in session_ids {
            // Use the same lock order as foreground saves. Serializing the
            // load+enqueue pair with that session's durable commit prevents a
            // background rebuild snapshot from being assigned a later queue
            // generation than a newer foreground save.
            let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
            let _session_write = self.acquire_session_maintenance_lock(&session_id).await?;
            if let Some(session) = self.load_session_unlocked(&session_id).await? {
                if !should_index_session(session.updated_at) {
                    continue;
                }
                let Some(session_path) = self.session_json_path(&session_id).await? else {
                    continue;
                };
                let abs_dir = session_path.parent().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "session path has no parent")
                })?;
                let (revision_path, revision) = self.publish_search_revision(abs_dir).await?;
                self.search_index_queue
                    .enqueue_upsert(&session, revision_path, revision);
            }
        }
        self.flush_search_index().await;
        Ok(())
    }

    pub fn sessions_root_dir(&self) -> &Path {
        &self.sessions_dir
    }

    fn root_rel_path(session_id: &str) -> String {
        format!("sessions/{session_id}")
    }

    fn child_rel_path(root_id: &str, child_id: &str) -> String {
        format!("sessions/{root_id}/children/{child_id}")
    }

    fn abs_path_from_rel(&self, rel: &str) -> PathBuf {
        self.bamboo_home_dir.join(rel)
    }

    async fn persist_index_locked(&self, index: &SessionsIndex) -> io::Result<()> {
        persist_index_path_locked(&self.index_path, index).await
    }

    async fn update_index<F, T>(&self, f: F) -> io::Result<T>
    where
        F: FnOnce(&mut SessionsIndex) -> io::Result<T>,
    {
        let wait_started = Instant::now();
        let _process = self.write_lock.lock().await;
        let _file = self.lock_index_file_exclusive().await?;
        let waited = wait_started.elapsed();
        self.persistence_metrics.record_index_lock_wait(waited);
        let hold_started = Instant::now();
        let result = self.update_index_under_claim(f).await;
        let held = hold_started.elapsed();
        self.persistence_metrics.record_index_lock_hold(held);
        tracing::debug!(
            target: "bamboo.session_persistence",
            phase = "index_published",
            index_lock_wait_ms = waited.as_millis() as u64,
            index_lock_hold_ms = held.as_millis() as u64,
            outcome = if result.is_ok() { "ok" } else { "error" },
            "session index mutation completed"
        );
        result
    }

    async fn update_index_under_claim<F, T>(&self, f: F) -> io::Result<T>
    where
        F: FnOnce(&mut SessionsIndex) -> io::Result<T>,
    {
        let mut memory = self.index.write().await;
        // Independent stores/processes have distinct in-memory snapshots. The
        // fixed file claim makes disk the rebase point for every mutation so a
        // stale writer cannot erase another process's just-published entries.
        // Missing disk falls back to this process's old-version rebuild marker.
        let mut index = match fs::read_to_string(&self.index_path).await {
            Ok(raw) => match serde_json::from_str::<SessionsIndex>(&raw) {
                Ok(index) => index,
                Err(_) if memory.version < SESSIONS_INDEX_VERSION => memory.clone(),
                Err(error) => {
                    return Err(other_io_error(format!(
                        "invalid sessions.json during locked update: {error}"
                    )))
                }
            },
            Err(error) if error.kind() == io::ErrorKind::NotFound => memory.clone(),
            Err(error) => return Err(error),
        };
        let out = f(&mut index)?;
        index.updated_at = Utc::now();
        self.persist_index_locked(&index).await?;
        *memory = index;
        Ok(out)
    }

    pub async fn list_index_entries(&self) -> Vec<SessionIndexEntry> {
        let index = self.index.read().await;
        let mut items: Vec<_> = index.sessions.values().cloned().collect();
        items.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
        items
    }

    pub async fn get_index_entry(&self, session_id: &str) -> Option<SessionIndexEntry> {
        let index = self.index.read().await;
        index.sessions.get(session_id).cloned()
    }

    /// Recover a root session by its deterministic authoritative directory,
    /// without trusting the rebuildable global index.
    ///
    /// Session-create idempotency uses this after an ambiguous commit: a crash
    /// can happen after `session.json` is durable but before `sessions.json` is
    /// published. When the authoritative file exists, this method loads it
    /// directly (including the runtime sidecar overlay) and repairs the global
    /// index before returning. FTS remains best-effort and is deliberately not
    /// part of this recovery barrier.
    pub async fn recover_root_session_from_disk(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Session>> {
        validate_session_id(session_id)?;
        let _lifecycle = self.lock_session_lifecycle_shared().await?;
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let Some(session) = self.load_authoritative_root_session(session_id).await? else {
            return Ok(None);
        };
        self.repair_index_from_authoritative_session(&session, Self::root_rel_path(session_id))
            .await?;
        Ok(Some(session))
    }

    /// Strictly probe the deterministic root `session.json` without consulting
    /// or mutating the rebuildable index. Missing is distinct from corrupt or
    /// unreadable so an idempotent pending retry never overwrites damaged
    /// authoritative data with the reserved UUID.
    pub async fn probe_root_session_from_disk(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Session>> {
        validate_session_id(session_id)?;
        let _lifecycle = self.lock_session_lifecycle_shared().await?;
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        self.load_authoritative_root_session(session_id).await
    }

    async fn load_authoritative_root_session(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Session>> {
        if self.root_directory_is_revoked(session_id).await? {
            return Ok(None);
        }
        let abs_dir = self.sessions_dir.join(session_id);
        let raw = match fs::read_to_string(abs_dir.join("session.json")).await {
            Ok(raw) => raw,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        compact_main::validate_full_main(raw.as_bytes()).map_err(|error| {
            io::Error::new(
                error.kind(),
                format!("invalid authoritative session.json: {error}"),
            )
        })?;
        // Unlike best-effort global-index rebuild, operation recovery must not
        // collapse an unreadable/corrupt authoritative result into "missing":
        // doing so could turn a repairable failure into terminal 410 truth.
        let main: Session = serde_json::from_str(&raw).map_err(|error| {
            other_io_error(format!("invalid authoritative session.json: {error}"))
        })?;
        let sidecar =
            Self::read_runtime_sidecar_at(&abs_dir.join(RUNTIME_SIDECAR_FILE), session_id).await?;
        supervisor::validate_overlay(&main, sidecar.as_ref())?;
        self.validate_root_tool_authority_overlay(session_id, &main, sidecar.as_ref())
            .await?;
        let mut session = overlay_runtime_sidecar(main, sidecar);
        session.clear_stale_root_token_budget();
        if session.id != session_id || session.kind != SessionKind::Root {
            return Err(other_io_error(
                "authoritative root session identity or kind mismatch",
            ));
        }
        Ok(Some(session))
    }

    pub async fn resolve_rel_path(&self, session_id: &str) -> Option<String> {
        self.get_index_entry(session_id).await.map(|e| e.rel_path)
    }

    async fn ensure_session_dirs(&self, session: &Session) -> io::Result<String> {
        validate_session_id(&session.id)?;

        let rel_path = match session.kind {
            SessionKind::Root => Self::root_rel_path(&session.id),
            SessionKind::Child => {
                let root_id = session.root_session_id.trim();
                let parent_id = session.parent_session_id.as_deref().unwrap_or("").trim();
                if root_id.is_empty() || parent_id.is_empty() {
                    return Err(other_io_error(
                        "child session missing root_session_id/parent_session_id",
                    ));
                }
                // Nesting is allowed: a child's parent may itself be a child.
                // All descendants live flat under the tree root's directory
                // (`child_rel_path` keys on `root_id`, which stays constant for
                // the whole tree), so depth needs no path change.
                validate_session_id(root_id)?;
                Self::child_rel_path(root_id, &session.id)
            }
        };

        let abs_dir = self.abs_path_from_rel(&rel_path);
        fs::create_dir_all(&abs_dir).await?;
        // Ensure expected subdirs (lazy; cheap).
        fs::create_dir_all(abs_dir.join("attachments")).await?;
        if session.kind == SessionKind::Root {
            fs::create_dir_all(abs_dir.join("children")).await?;
        }
        Ok(rel_path)
    }

    async fn session_json_path(&self, session_id: &str) -> io::Result<Option<PathBuf>> {
        if let Some(rel) = self.resolve_rel_path(session_id).await {
            Ok(Some(self.abs_path_from_rel(&rel).join("session.json")))
        } else {
            Ok(None)
        }
    }

    async fn runtime_json_path(&self, session_id: &str) -> io::Result<Option<PathBuf>> {
        if let Some(rel) = self.resolve_rel_path(session_id).await {
            Ok(Some(
                self.abs_path_from_rel(&rel).join(RUNTIME_SIDECAR_FILE),
            ))
        } else {
            Ok(None)
        }
    }

    fn runtime_task_transaction_dir(&self) -> PathBuf {
        self.bamboo_home_dir.join(RUNTIME_TASK_TRANSACTION_DIR)
    }

    fn session_copy_transaction_dir(&self) -> PathBuf {
        self.bamboo_home_dir.join(SESSION_COPY_TRANSACTION_DIR)
    }

    fn session_write_lock_dir(&self) -> PathBuf {
        self.bamboo_home_dir.join(SESSION_WRITE_LOCK_DIR)
    }

    fn session_write_lock_path(&self, session_id: &str) -> PathBuf {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let digest = Sha256::digest(session_id.as_bytes());
        let mut name = String::with_capacity(digest.len() * 2 + 5);
        for byte in digest {
            name.push(HEX[(byte >> 4) as usize] as char);
            name.push(HEX[(byte & 0x0f) as usize] as char);
        }
        name.push_str(".lock");
        self.session_write_lock_dir().join(name)
    }

    fn session_copy_staging_dir(&self, journal: &SessionCopyTransactionJournal) -> PathBuf {
        self.bamboo_home_dir
            .join(format!(".session-copy-{}", journal.transaction_id))
    }

    async fn ensure_private_transaction_dir(&self, path: PathBuf) -> io::Result<PathBuf> {
        let home_existed = fs::try_exists(&self.bamboo_home_dir).await?;
        fs::create_dir_all(&self.bamboo_home_dir).await?;
        if !home_existed {
            sync_parent_directory_entry(&self.bamboo_home_dir).await?;
        }
        let path_existed = fs::try_exists(&path).await?;
        fs::create_dir_all(&path).await?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).await?;
        }
        if !path_existed {
            sync_parent_directory_entry(&path).await?;
        }
        Ok(path)
    }

    async fn ensure_runtime_task_transaction_dir(&self) -> io::Result<PathBuf> {
        self.ensure_private_transaction_dir(self.runtime_task_transaction_dir())
            .await
    }

    async fn ensure_session_copy_transaction_dir(&self) -> io::Result<PathBuf> {
        self.ensure_private_transaction_dir(self.session_copy_transaction_dir())
            .await
    }

    async fn ensure_session_write_lock_dir(&self) -> io::Result<PathBuf> {
        self.ensure_private_transaction_dir(self.session_write_lock_dir())
            .await
    }

    fn runtime_task_recovery_error() -> io::Error {
        other_io_error("runtime Task transaction recovery is required before control-plane access")
    }

    async fn ensure_no_runtime_task_journal_locked(&self) -> io::Result<()> {
        match self.runtime_task_journal_paths().await {
            Ok(paths) if paths.is_empty() => {
                self.runtime_task_recovery_required
                    .store(false, Ordering::Release);
                Ok(())
            }
            Ok(_) => {
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                Err(Self::runtime_task_recovery_error())
            }
            Err(error) => {
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                Err(error)
            }
        }
    }

    /// Acquire the ordinary shared sidecar boundary, then consult the durable
    /// journal directory rather than this instance's in-memory flag. Once the
    /// shared file lock is held no live commit can create/remove a journal, so
    /// an existing entry is necessarily recovery-required and access fails
    /// closed even in a freshly constructed independent store.
    async fn lock_runtime_task_sidecar_shared(
        &self,
    ) -> io::Result<RuntimeTaskTransactionReadGuard> {
        let guard = self.lock_runtime_task_transaction_shared().await?;
        self.ensure_no_runtime_task_journal_locked().await?;
        Ok(guard)
    }

    #[cfg(test)]
    pub(crate) fn inject_runtime_task_transaction_fault(&self, fault: RuntimeTaskTransactionFault) {
        self.runtime_task_faults
            .lock()
            .expect("runtime task fault lock")
            .push(fault);
    }

    fn record_runtime_task_durability_event(&self, event: RuntimeTaskDurabilityEvent) {
        #[cfg(test)]
        self.runtime_task_durability_events
            .lock()
            .expect("runtime task durability event lock")
            .push(event);
        #[cfg(not(test))]
        let _ = event;
    }

    #[cfg(test)]
    fn take_runtime_task_durability_events(&self) -> Vec<RuntimeTaskDurabilityEvent> {
        std::mem::take(
            &mut *self
                .runtime_task_durability_events
                .lock()
                .expect("runtime task durability event lock"),
        )
    }

    #[cfg(test)]
    fn pause_runtime_task_transaction_after_first_write(
        &self,
    ) -> (
        std::sync::Arc<tokio::sync::Barrier>,
        std::sync::Arc<tokio::sync::Barrier>,
    ) {
        let pause = RuntimeTaskFirstWritePause {
            reached: std::sync::Arc::new(tokio::sync::Barrier::new(2)),
            release: std::sync::Arc::new(tokio::sync::Barrier::new(2)),
        };
        *self
            .runtime_task_first_write_pause
            .lock()
            .expect("runtime task pause lock") = Some(pause.clone());
        (pause.reached, pause.release)
    }

    #[cfg(test)]
    async fn maybe_pause_runtime_task_transaction_after_first_write(&self) {
        let pause = self
            .runtime_task_first_write_pause
            .lock()
            .expect("runtime task pause lock")
            .take();
        if let Some(pause) = pause {
            pause.reached.wait().await;
            pause.release.wait().await;
        }
    }

    fn maybe_fail_runtime_task_transaction(
        &self,
        fault: RuntimeTaskTransactionFault,
    ) -> io::Result<()> {
        #[cfg(test)]
        {
            let mut faults = self
                .runtime_task_faults
                .lock()
                .expect("runtime task fault lock");
            if let Some(index) = faults.iter().position(|candidate| *candidate == fault) {
                faults.remove(index);
                return Err(other_io_error(format!(
                    "injected runtime Task transaction fault: {fault:?}"
                )));
            }
        }
        #[cfg(not(test))]
        let _ = fault;
        Ok(())
    }

    async fn load_runtime_control_plane_unchecked(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Session>> {
        Ok(self
            .load_runtime_control_plane_boxed_unchecked(session_id)
            .await?
            .map(|session| *session))
    }

    async fn load_runtime_control_plane_boxed_unchecked(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Box<Session>>> {
        validate_session_id(session_id)?;
        if session_id == DEFAULT_SUPERVISOR_SESSION_ID {
            if let Some(root) = self.load_root_authority_unchecked(session_id).await? {
                return Ok(Some(Box::new(root)));
            }
            // An Ordinary Child may already own this ID in another tree.
            // Only canonical Root absence permits its normal control-plane read.
        }
        if let Some(side) = self.read_runtime_sidecar_boxed(session_id).await? {
            self.validate_root_tool_authority_against_proof(session_id, &side)
                .await?;
            return Ok(self.session_lifetime_is_live(&side).await?.then_some(side));
        }
        let Some(path) = self.session_json_path(session_id).await? else {
            self.ensure_no_unindexed_root(session_id).await?;
            return Ok(None);
        };
        let raw = match fs::read_to_string(path).await {
            Ok(raw) => raw,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                self.ensure_no_unindexed_root(session_id).await?;
                return Ok(None);
            }
            Err(error) => return Err(error),
        };
        compact_main::validate_full_main(raw.as_bytes())?;
        let mut session: Box<Session> = serde_json::from_str(&raw)
            .map_err(|error| other_io_error(format!("invalid session.json: {error}")))?;
        supervisor::validate_identity(&session)?;
        self.validate_root_tool_authority_overlay(session_id, &session, None)
            .await?;
        if !self.session_lifetime_is_live(&session).await? {
            return Ok(None);
        }
        session.messages.clear();
        session.clear_stale_root_token_budget();
        Ok(Some(session))
    }

    fn validate_runtime_task_recovery_identity(
        session: &Session,
        session_id: &str,
        expected_kind: SessionKind,
        expected_root_id: &str,
    ) -> io::Result<()> {
        if session.id != session_id
            || session.kind != expected_kind
            || session.root_session_id != expected_root_id
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "runtime Task recovery identity mismatch for {session_id}: found id={}, kind={:?}, root={}",
                    session.id, session.kind, session.root_session_id
                ),
            ));
        }
        Ok(())
    }

    async fn runtime_task_recovery_real_directory(path: &Path) -> io::Result<bool> {
        let metadata = match fs::symlink_metadata(path).await {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
        };
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "runtime Task recovery candidate is not a real directory: {}",
                    path.display()
                ),
            ));
        }
        Ok(true)
    }

    async fn runtime_task_recovery_real_file(path: &Path) -> io::Result<bool> {
        let metadata = match fs::symlink_metadata(path).await {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
        };
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "runtime Task recovery candidate is not a real file: {}",
                    path.display()
                ),
            ));
        }
        Ok(true)
    }

    async fn read_runtime_task_recovery_main_at(
        abs_dir: &Path,
        session_id: &str,
        expected_kind: SessionKind,
        expected_root_id: &str,
    ) -> io::Result<Option<Session>> {
        if !Self::runtime_task_recovery_real_directory(abs_dir).await? {
            return Ok(None);
        }
        let path = abs_dir.join("session.json");
        if !Self::runtime_task_recovery_real_file(&path).await? {
            return Ok(None);
        }
        let raw = fs::read_to_string(&path).await?;
        compact_main::validate_full_main(raw.as_bytes())?;
        let session: Session = serde_json::from_str(&raw).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "invalid authoritative session.json for runtime Task recovery at {}: {error}",
                    path.display()
                ),
            )
        })?;
        Self::validate_runtime_task_recovery_identity(
            &session,
            session_id,
            expected_kind,
            expected_root_id,
        )?;
        Ok(Some(session))
    }

    /// Resolve one journal target without consulting the rebuildable index.
    ///
    /// Constructor recovery deliberately runs before corrupt-index rebuild so
    /// no half-published Task sidecar can be folded into index/FTS state. The
    /// caller holds the cross-process runtime-Task lock exclusively: session
    /// deletion therefore cannot mutate the tree while this strict scan finds
    /// either `sessions/<id>` or the unique
    /// `sessions/*/children/<id>`. Corrupt identity or duplicate candidates
    /// fail closed instead of selecting an arbitrary sidecar.
    async fn load_runtime_task_recovery_target(
        &self,
        session_id: &str,
    ) -> io::Result<Option<(PathBuf, Session)>> {
        validate_session_id(session_id)?;
        if !Self::runtime_task_recovery_real_directory(&self.sessions_dir).await? {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "runtime Task recovery sessions directory is missing",
            ));
        }
        let mut candidates = Vec::new();

        let root_dir = self.sessions_dir.join(session_id);
        if let Some(session) = Self::read_runtime_task_recovery_main_at(
            &root_dir,
            session_id,
            SessionKind::Root,
            session_id,
        )
        .await?
        {
            candidates.push((root_dir, session));
        }

        let mut root_dirs = match fs::read_dir(&self.sessions_dir).await {
            Ok(entries) => entries,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(candidates.pop()),
            Err(error) => return Err(error),
        };
        while let Some(root_entry) = root_dirs.next_entry().await? {
            if !root_entry.file_type().await?.is_dir() {
                continue;
            }
            let Ok(root_id) = root_entry.file_name().into_string() else {
                continue;
            };
            if validate_session_id(&root_id).is_err() {
                continue;
            }
            let children_dir = root_entry.path().join("children");
            let children_metadata = match fs::symlink_metadata(&children_dir).await {
                Ok(metadata) => metadata,
                Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error),
            };
            // This is an intermediate container rather than an exact journal
            // target. Match rebuild semantics by ignoring malformed/symlinked
            // children trees; the exact target will then remain missing and
            // recovery fails closed without following it outside sessions/.
            if children_metadata.file_type().is_symlink() || !children_metadata.is_dir() {
                continue;
            }
            let child_dir = children_dir.join(session_id);
            if let Some(session) = Self::read_runtime_task_recovery_main_at(
                &child_dir,
                session_id,
                SessionKind::Child,
                &root_id,
            )
            .await?
            {
                if Self::read_runtime_task_recovery_main_at(
                    &root_entry.path(),
                    &root_id,
                    SessionKind::Root,
                    &root_id,
                )
                .await?
                .is_none()
                {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!(
                            "runtime Task recovery child {session_id} has no authoritative root {root_id}"
                        ),
                    ));
                }
                candidates.push((child_dir, session));
            }
        }

        match candidates.len() {
            0 => Ok(None),
            1 => Ok(candidates.pop()),
            count => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "runtime Task recovery target {session_id} is ambiguous across {count} authoritative directories"
                ),
            )),
        }
    }

    async fn validate_runtime_task_recovery_write_target(
        &self,
        abs_dir: &Path,
        current: &Session,
    ) -> io::Result<()> {
        if !Self::runtime_task_recovery_real_directory(&self.sessions_dir).await? {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "runtime Task recovery sessions directory is missing",
            ));
        }
        let expected_dir = match current.kind {
            SessionKind::Root => self.sessions_dir.join(&current.id),
            SessionKind::Child => self
                .sessions_dir
                .join(&current.root_session_id)
                .join("children")
                .join(&current.id),
        };
        if abs_dir != expected_dir {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "runtime Task recovery path mismatch for {}: {}",
                    current.id,
                    abs_dir.display()
                ),
            ));
        }

        if current.kind == SessionKind::Child {
            let root_dir = self.sessions_dir.join(&current.root_session_id);
            if Self::read_runtime_task_recovery_main_at(
                &root_dir,
                &current.root_session_id,
                SessionKind::Root,
                &current.root_session_id,
            )
            .await?
            .is_none()
            {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "runtime Task recovery child {} lost authoritative root {}",
                        current.id, current.root_session_id
                    ),
                ));
            }
            let children_dir = root_dir.join("children");
            if !Self::runtime_task_recovery_real_directory(&children_dir).await? {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!(
                        "runtime Task recovery children directory disappeared for {}",
                        current.id
                    ),
                ));
            }
        }
        let Some(main) = Self::read_runtime_task_recovery_main_at(
            abs_dir,
            &current.id,
            current.kind,
            &current.root_session_id,
        )
        .await?
        else {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "runtime Task recovery target disappeared for {}",
                    current.id
                ),
            ));
        };
        if main.parent_session_id != current.parent_session_id
            || main.parent_created_at != current.parent_created_at
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "runtime Task recovery parent identity changed for {}",
                    current.id
                ),
            ));
        }

        let runtime_path = abs_dir.join(RUNTIME_SIDECAR_FILE);
        let _ = Self::runtime_task_recovery_real_file(&runtime_path).await?;
        Ok(())
    }

    async fn load_runtime_task_recovery_control_plane(
        &self,
        session_id: &str,
    ) -> io::Result<Option<(PathBuf, Session)>> {
        let Some((abs_dir, main)) = self.load_runtime_task_recovery_target(session_id).await?
        else {
            return Ok(None);
        };
        let runtime_path = abs_dir.join(RUNTIME_SIDECAR_FILE);
        let sidecar = if Self::runtime_task_recovery_real_file(&runtime_path).await? {
            Self::read_runtime_sidecar_at(&runtime_path, session_id).await?
        } else {
            None
        };
        if let Some(sidecar) = sidecar.as_ref() {
            Self::validate_runtime_task_recovery_identity(
                sidecar,
                session_id,
                main.kind,
                &main.root_session_id,
            )?;
            if sidecar.parent_session_id != main.parent_session_id
                || sidecar.parent_created_at != main.parent_created_at
            {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("runtime Task recovery parent identity mismatch for {session_id}"),
                ));
            }
        }
        supervisor::validate_overlay(&main, sidecar.as_ref())?;
        let mut session = overlay_runtime_sidecar(main, sidecar);
        session.messages.clear();
        session.clear_stale_root_token_budget();
        self.validate_root_context_for_save(&session).await?;
        Ok(Some((abs_dir, session)))
    }

    async fn write_existing_runtime_sidecar_durable_unchecked(
        &self,
        session: &Session,
        event: RuntimeTaskDurabilityEvent,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        validate_session_id(&session.id)?;
        let Some(rel) = self.resolve_rel_path(&session.id).await else {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("session {} has no persisted runtime target", session.id),
            ));
        };
        self.write_runtime_sidecar_durable(&self.abs_path_from_rel(&rel), session, guard)
            .await?;
        self.record_runtime_task_durability_event(event);
        Ok(())
    }

    async fn runtime_task_journal_paths(&self) -> io::Result<Vec<PathBuf>> {
        let dir = self.runtime_task_transaction_dir();
        let mut entries = match fs::read_dir(dir).await {
            Ok(entries) => entries,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => return Err(error),
        };
        let mut paths = Vec::new();
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if entry
                .file_type()
                .await
                .map(|kind| kind.is_file())
                .unwrap_or(false)
                && RuntimeTaskJournalMarkerState::from_path(&path).is_some()
            {
                paths.push(path);
            }
        }
        paths.sort();
        Ok(paths)
    }

    fn validate_runtime_task_journal(
        path: &Path,
        journal: &RuntimeTaskTransactionJournal,
    ) -> io::Result<()> {
        if journal.version != RUNTIME_TASK_TRANSACTION_VERSION {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "unsupported runtime Task transaction journal version {}",
                    journal.version
                ),
            ));
        }
        let file_id = path
            .file_stem()
            .and_then(|value| value.to_str())
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid journal name"))?;
        Uuid::parse_str(file_id).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid runtime Task transaction journal UUID: {error}"),
            )
        })?;
        if journal.transaction_id != file_id {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "runtime Task transaction journal id does not match its filename",
            ));
        }
        validate_session_id(&journal.first.session_id)?;
        validate_session_id(&journal.second.session_id)?;
        if journal.first.session_id >= journal.second.session_id {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "runtime Task transaction journal pair is not lexically ordered",
            ));
        }
        Ok(())
    }

    async fn read_runtime_task_journal(
        &self,
        path: &Path,
    ) -> io::Result<RuntimeTaskTransactionJournal> {
        let raw = fs::read_to_string(path).await?;
        let journal: RuntimeTaskTransactionJournal =
            serde_json::from_str(&raw).map_err(|error| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("invalid runtime Task transaction journal: {error}"),
                )
            })?;
        Self::validate_runtime_task_journal(path, &journal)?;
        Ok(journal)
    }

    async fn write_runtime_task_journal(
        &self,
        journal: &RuntimeTaskTransactionJournal,
    ) -> io::Result<PathBuf> {
        let dir = self.ensure_runtime_task_transaction_dir().await?;
        let path = dir.join(format!("{}.json", journal.transaction_id));
        let bytes = serde_json::to_vec(journal)
            .map_err(|error| other_io_error(format!("serialize Task undo journal: {error}")))?;
        durable_atomic_write(&path, &bytes).await?;
        self.record_runtime_task_durability_event(RuntimeTaskDurabilityEvent::JournalPublished);
        Ok(path)
    }

    async fn remove_runtime_task_journal(&self, path: &Path) -> io::Result<()> {
        durable_deactivate_recovery_marker(path).await?;
        self.record_runtime_task_durability_event(RuntimeTaskDurabilityEvent::JournalDeactivated);
        Ok(())
    }

    async fn remove_runtime_task_journal_family(
        &self,
        journal: &RuntimeTaskTransactionJournal,
    ) -> io::Result<()> {
        let dir = self.runtime_task_transaction_dir();
        for extension in ["json", "committing", "committed"] {
            let path = dir.join(format!("{}.{}", journal.transaction_id, extension));
            match fs::try_exists(&path).await {
                Ok(true) => self.remove_runtime_task_journal(&path).await?,
                Ok(false) => {}
                Err(error) => return Err(error),
            }
        }
        Ok(())
    }

    /// Transition a prepared undo journal through a fail-closed intermediate
    /// name to a committed marker, then durably deactivate it. Recovery rolls
    /// back `.json`/`.committing`, but never rolls back `.committed`; a failure
    /// after the committed rename therefore cannot turn two durable sidecars
    /// into a later undo.
    async fn finalize_runtime_task_journal(
        &self,
        path: &Path,
    ) -> Result<(), RuntimeTaskJournalFinalizeError> {
        self.maybe_fail_runtime_task_transaction(RuntimeTaskTransactionFault::JournalRemove)
            .map_err(RuntimeTaskJournalFinalizeError::Rollback)?;

        let committing = path.with_extension("committing");
        atomic_rename(path, &committing)
            .await
            .map_err(RuntimeTaskJournalFinalizeError::Rollback)?;
        sync_parent_directory_entry(&committing)
            .await
            .map_err(RuntimeTaskJournalFinalizeError::Rollback)?;

        let committed = path.with_extension("committed");
        atomic_rename(&committing, &committed)
            .await
            .map_err(RuntimeTaskJournalFinalizeError::Rollback)?;
        sync_parent_directory_entry(&committed)
            .await
            .map_err(RuntimeTaskJournalFinalizeError::RecoveryRequired)?;
        self.remove_runtime_task_journal(&committed)
            .await
            .map_err(RuntimeTaskJournalFinalizeError::RecoveryRequired)
    }

    async fn restore_runtime_task_undo(
        &self,
        undo: &TaskControlPlaneUndo,
        fault: RuntimeTaskTransactionFault,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        self.maybe_fail_runtime_task_transaction(fault)?;
        let Some((abs_dir, mut current)) = self
            .load_runtime_task_recovery_control_plane(&undo.session_id)
            .await?
        else {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("cannot recover missing session {}", undo.session_id),
            ));
        };
        current.task_list = undo.task_list.clone();
        current.set_task_list_version_meta(undo.task_list_version.clone());
        let event = match fault {
            RuntimeTaskTransactionFault::FirstRollbackWrite => {
                RuntimeTaskDurabilityEvent::FirstRollbackSidecarPublished
            }
            RuntimeTaskTransactionFault::SecondRollbackWrite => {
                RuntimeTaskDurabilityEvent::SecondRollbackSidecarPublished
            }
            _ => unreachable!("rollback helper only accepts rollback write faults"),
        };
        self.validate_runtime_task_recovery_write_target(&abs_dir, &current)
            .await?;
        self.write_runtime_sidecar_durable(&abs_dir, &current, guard)
            .await?;
        self.record_runtime_task_durability_event(event);
        Ok(())
    }

    async fn rollback_runtime_task_journal(
        &self,
        journal: &RuntimeTaskTransactionJournal,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        let mut errors = Vec::new();
        if let Err(error) = self
            .restore_runtime_task_undo(
                &journal.first,
                RuntimeTaskTransactionFault::FirstRollbackWrite,
                guard,
            )
            .await
        {
            errors.push(format!("{}: {error}", journal.first.session_id));
        }
        if let Err(error) = self
            .restore_runtime_task_undo(
                &journal.second,
                RuntimeTaskTransactionFault::SecondRollbackWrite,
                guard,
            )
            .await
        {
            errors.push(format!("{}: {error}", journal.second.session_id));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(other_io_error(format!(
                "runtime Task transaction rollback failed for {}",
                errors.join(", ")
            )))
        }
    }

    async fn recover_runtime_task_journal(
        &self,
        path: &Path,
        journal: &RuntimeTaskTransactionJournal,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        let state = RuntimeTaskJournalMarkerState::from_path(path).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid runtime Task journal marker extension",
            )
        })?;
        if state != RuntimeTaskJournalMarkerState::Committed {
            self.rollback_runtime_task_journal(journal, guard).await?;
        }
        self.remove_runtime_task_journal(path).await
    }

    async fn recover_all_runtime_task_transactions_locked(
        &self,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        let paths = self.runtime_task_journal_paths().await?;
        for path in paths {
            let journal = match self.read_runtime_task_journal(&path).await {
                Ok(journal) => journal,
                Err(error) => {
                    self.runtime_task_recovery_required
                        .store(true, Ordering::Release);
                    return Err(error);
                }
            };
            if let Err(error) = self
                .recover_runtime_task_journal(&path, &journal, guard)
                .await
            {
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                return Err(error);
            }
        }
        self.runtime_task_recovery_required
            .store(false, Ordering::Release);
        Ok(())
    }

    async fn session_copy_journal_paths(&self) -> io::Result<Vec<PathBuf>> {
        let mut entries = match fs::read_dir(self.session_copy_transaction_dir()).await {
            Ok(entries) => entries,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => return Err(error),
        };
        let mut paths = Vec::new();
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if entry.file_type().await?.is_file()
                && SessionCopyJournalMarkerState::from_path(&path).is_some()
            {
                paths.push(path);
            }
        }
        paths.sort();
        Ok(paths)
    }

    fn validate_session_copy_journal(
        path: &Path,
        journal: &SessionCopyTransactionJournal,
    ) -> io::Result<()> {
        if journal.version != SESSION_COPY_TRANSACTION_VERSION {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "unsupported session copy transaction journal version {}",
                    journal.version
                ),
            ));
        }
        let file_id = path
            .file_stem()
            .and_then(|value| value.to_str())
            .ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidData, "invalid copy journal name")
            })?;
        Uuid::parse_str(file_id).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid session copy transaction UUID: {error}"),
            )
        })?;
        if journal.transaction_id != file_id {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "session copy transaction id does not match its filename",
            ));
        }
        validate_session_id(&journal.source_id)?;
        validate_session_id(&journal.target_id)?;
        if journal.source_id == journal.target_id {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "session copy transaction source and target must differ",
            ));
        }
        Ok(())
    }

    async fn read_session_copy_journal(
        &self,
        path: &Path,
    ) -> io::Result<SessionCopyTransactionJournal> {
        let raw = fs::read_to_string(path).await?;
        let journal = serde_json::from_str(&raw).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid session copy transaction journal: {error}"),
            )
        })?;
        Self::validate_session_copy_journal(path, &journal)?;
        Ok(journal)
    }

    async fn write_session_copy_journal(
        &self,
        journal: &SessionCopyTransactionJournal,
    ) -> io::Result<PathBuf> {
        let dir = self.ensure_session_copy_transaction_dir().await?;
        let path = dir.join(format!("{}.json", journal.transaction_id));
        let bytes = serde_json::to_vec(journal)
            .map_err(|error| other_io_error(format!("serialize session copy journal: {error}")))?;
        durable_atomic_write(&path, &bytes).await?;
        Ok(path)
    }

    async fn remove_session_copy_journal_family(
        &self,
        journal: &SessionCopyTransactionJournal,
    ) -> io::Result<()> {
        for extension in ["json", "committing", "committed"] {
            let path = self
                .session_copy_transaction_dir()
                .join(format!("{}.{}", journal.transaction_id, extension));
            match fs::try_exists(&path).await {
                Ok(true) => durable_deactivate_recovery_marker(&path).await?,
                Ok(false) => {}
                Err(error) => return Err(error),
            }
        }
        Ok(())
    }

    async fn rollback_session_copy_transaction(
        &self,
        journal: &SessionCopyTransactionJournal,
    ) -> io::Result<()> {
        // Hide the target first. If cleanup later fails, the retained marker
        // makes startup retry before the store becomes available.
        let mut errors = Vec::new();
        if let Err(error) = self
            .update_index(|index| {
                index.sessions.remove(&journal.target_id);
                Ok(())
            })
            .await
        {
            errors.push(format!("index cleanup: {error}"));
            // The durable index could not be rewritten, but readers of this
            // still-live store must not retain a target whose directory is
            // about to be removed. The journal keeps cross-process recovery
            // retryable; this in-memory removal closes the local visibility gap.
            self.index.write().await.sessions.remove(&journal.target_id);
        }
        let target_dir = self.sessions_dir.join(&journal.target_id);
        let revision_path = target_dir.join(SEARCH_INDEX_REVISION_FILE);
        let staging_dir = self.session_copy_staging_dir(journal);
        for path in [&target_dir, &staging_dir] {
            match fs::remove_dir_all(path).await {
                Ok(()) => {
                    if let Err(error) = sync_parent_directory_entry(path).await {
                        errors.push(format!("sync cleanup {}: {error}", path.display()));
                    }
                }
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => errors.push(format!("remove {}: {error}", path.display())),
            }
        }
        self.search_index_queue
            .enqueue_delete(&journal.target_id, revision_path);
        if errors.is_empty() {
            Ok(())
        } else {
            Err(other_io_error(format!(
                "session copy rollback incomplete: {}",
                errors.join("; ")
            )))
        }
    }

    async fn recover_session_copy_journal(
        &self,
        path: &Path,
        journal: &SessionCopyTransactionJournal,
    ) -> io::Result<()> {
        let state = SessionCopyJournalMarkerState::from_path(path).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid session copy journal marker extension",
            )
        })?;
        if state == SessionCopyJournalMarkerState::Committed {
            let target_dir = self.sessions_dir.join(&journal.target_id);
            let target = self
                .load_session_from_dir_strict(
                    &target_dir,
                    &journal.target_id,
                    SessionKind::Root,
                    &journal.target_id,
                )
                .await?
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::NotFound,
                        "committed copied session target is missing",
                    )
                })?;
            if target.kind != SessionKind::Root || target.root_session_id != target.id {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "committed copied session is not an independent root",
                ));
            }
            let has_attachments =
                Self::directory_has_regular_files(&target_dir.join("attachments")).await?;
            self.upsert_index_from_session_inner(
                &target,
                Self::root_rel_path(&target.id),
                false,
                Some(has_attachments),
            )
            .await?;
            let (revision_path, revision) = self.publish_search_revision(&target_dir).await?;
            self.search_index_queue
                .enqueue_upsert(&target, revision_path, revision);
        } else {
            self.rollback_session_copy_transaction(journal).await?;
        }
        durable_deactivate_recovery_marker(path).await
    }

    async fn recover_all_session_copy_transactions_locked(&self) -> io::Result<()> {
        for path in self.session_copy_journal_paths().await? {
            let journal = self.read_session_copy_journal(&path).await?;
            self.recover_session_copy_journal(&path, &journal).await?;
        }
        // A previous marker deactivation may have completed its rename to an
        // inert tombstone but failed the directory sync. Lifecycle mutations
        // that could remove a target must not proceed until every such visible
        // rename is itself durable, or power loss could resurrect a committed
        // marker after the target was deleted.
        sync_directory(&self.session_copy_transaction_dir()).await?;
        Ok(())
    }

    async fn recover_runtime_task_transaction_for_pair_locked(
        &self,
        first_session_id: &str,
        second_session_id: &str,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        validate_session_id(first_session_id)?;
        validate_session_id(second_session_id)?;
        if first_session_id >= second_session_id {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "runtime Task recovery pair must be lexically ordered",
            ));
        }

        let paths = self.runtime_task_journal_paths().await?;
        for path in paths {
            let journal = self.read_runtime_task_journal(&path).await?;
            if RuntimeTaskJournalMarkerState::from_path(&path)
                == Some(RuntimeTaskJournalMarkerState::Committed)
            {
                self.recover_runtime_task_journal(&path, &journal, guard)
                    .await?;
                continue;
            }
            if journal.first.session_id != first_session_id
                || journal.second.session_id != second_session_id
            {
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                return Err(other_io_error(format!(
                    "pending runtime Task transaction for {}/{} must be recovered before accessing {}/{}",
                    journal.first.session_id,
                    journal.second.session_id,
                    first_session_id,
                    second_session_id
                )));
            }
            if let Err(error) = self
                .recover_runtime_task_journal(&path, &journal, guard)
                .await
            {
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                return Err(error);
            }
        }
        self.runtime_task_recovery_required
            .store(false, Ordering::Release);
        Ok(())
    }

    async fn fail_runtime_task_transaction_with_rollback(
        &self,
        _path: &Path,
        journal: &RuntimeTaskTransactionJournal,
        primary: io::Error,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        let primary_kind = primary.kind();
        let primary_message = primary.to_string();
        match self.rollback_runtime_task_journal(journal, guard).await {
            Ok(()) => match self.remove_runtime_task_journal_family(journal).await {
                Ok(()) => {
                    self.runtime_task_recovery_required
                        .store(false, Ordering::Release);
                    Err(io::Error::new(
                        primary_kind,
                        format!(
                            "runtime Task transaction failed and was rolled back: {primary_message}"
                        ),
                    ))
                }
                Err(cleanup_error) => {
                    self.runtime_task_recovery_required
                        .store(true, Ordering::Release);
                    Err(other_io_error(format!(
                        "runtime Task transaction failed ({primary_message}); rollback succeeded but journal cleanup failed ({cleanup_error}); recovery required"
                    )))
                }
            },
            Err(rollback_error) => {
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                Err(other_io_error(format!(
                    "runtime Task transaction failed ({primary_message}); {rollback_error}; recovery required"
                )))
            }
        }
    }

    async fn save_runtime_task_control_plane_if_matches(
        &self,
        original: &Session,
        updated: &Session,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<bool> {
        validate_session_id(&original.id)?;
        validate_session_id(&updated.id)?;
        if original.id != updated.id {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "single Task snapshots must preserve the session id",
            ));
        }
        if Self::runtime_task_non_task_snapshot(original)?
            != Self::runtime_task_non_task_snapshot(updated)?
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "single Task update modifies fields outside Task list/generation",
            ));
        }
        if updated.task_list.is_none() || updated.task_list_version_meta().is_none() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "single Task update requires a list and generation",
            ));
        }
        let Some(current) = self
            .load_runtime_control_plane_unchecked(&original.id)
            .await?
        else {
            return Ok(false);
        };
        self.validate_root_context_for_save(&current).await?;
        if current.authority_identity != original.authority_identity
            || current.supervisor_management != original.supervisor_management
            || !Self::runtime_task_owned_snapshot_matches(&current, original)?
        {
            return Ok(false);
        }
        let mut committed = current;
        committed.task_list = updated.task_list.clone();
        committed.set_task_list_version_meta(
            updated
                .task_list_version_meta()
                .expect("validated updated Task generation"),
        );
        self.write_existing_runtime_sidecar_durable_unchecked(
            &committed,
            RuntimeTaskDurabilityEvent::SingleUpdatedSidecarPublished,
            guard,
        )
        .await?;
        Ok(true)
    }

    async fn save_runtime_task_pair_transaction(
        &self,
        first_original: &Session,
        first_updated: &Session,
        second_original: &Session,
        second_updated: &Session,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<bool> {
        for session in [
            first_original,
            first_updated,
            second_original,
            second_updated,
        ] {
            validate_session_id(&session.id)?;
        }
        if first_original.id != first_updated.id
            || second_original.id != second_updated.id
            || first_original.id >= second_original.id
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "paired Task snapshots must preserve ids and be lexically ordered",
            ));
        }
        for (label, original, updated) in [
            ("first", first_original, first_updated),
            ("second", second_original, second_updated),
        ] {
            if Self::runtime_task_non_task_snapshot(original)?
                != Self::runtime_task_non_task_snapshot(updated)?
            {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "{label} paired Task update modifies fields outside Task list/generation"
                    ),
                ));
            }
        }
        if first_updated.task_list.is_none()
            || first_updated.task_list_version_meta().is_none()
            || first_updated.task_list_version_meta() != second_updated.task_list_version_meta()
            || serde_json::to_value(&first_updated.task_list)
                .map_err(|error| other_io_error(error.to_string()))?
                != serde_json::to_value(&second_updated.task_list)
                    .map_err(|error| other_io_error(error.to_string()))?
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "paired Task updates must publish identical Task lists/generations",
            ));
        }
        // This is the final CAS boundary. Different LockedSessionStore
        // instances have independent lexical mutexes, so both may stage from
        // the same generation before either reaches this storage transaction.
        // Re-read both Task-owned snapshots while the cross-process exclusive
        // lock is held; a loser returns a typed stale result without creating a
        // journal or touching either sidecar.
        let Some(current_first) = self
            .load_runtime_control_plane_unchecked(&first_original.id)
            .await?
        else {
            return Ok(false);
        };
        let Some(current_second) = self
            .load_runtime_control_plane_unchecked(&second_original.id)
            .await?
        else {
            return Ok(false);
        };
        self.validate_root_context_for_save(&current_first).await?;
        self.validate_root_context_for_save(&current_second).await?;
        if current_first.authority_identity != first_original.authority_identity
            || current_second.authority_identity != second_original.authority_identity
            || current_first.supervisor_management != first_original.supervisor_management
            || current_second.supervisor_management != second_original.supervisor_management
            || !Self::runtime_task_owned_snapshot_matches(&current_first, first_original)?
            || !Self::runtime_task_owned_snapshot_matches(&current_second, second_original)?
        {
            return Ok(false);
        }

        let first_version = current_first.task_list_version_meta().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "first current Task snapshot has no generation",
            )
        })?;
        let second_version = current_second.task_list_version_meta().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "second current Task snapshot has no generation",
            )
        })?;
        // The staging snapshots may predate unrelated status/round/inbox or
        // metadata writes from another store. Build the physical writes from
        // the just-revalidated durable snapshots and patch only Task-owned
        // fields, so the transaction remains narrowly targeted.
        let mut first_commit = current_first.clone();
        first_commit.task_list = first_updated.task_list.clone();
        first_commit.set_task_list_version_meta(
            first_updated
                .task_list_version_meta()
                .expect("validated updated Task generation"),
        );
        let mut second_commit = current_second.clone();
        second_commit.task_list = second_updated.task_list.clone();
        second_commit.set_task_list_version_meta(
            second_updated
                .task_list_version_meta()
                .expect("validated updated Task generation"),
        );

        let transaction_id = Uuid::new_v4().to_string();
        let journal = RuntimeTaskTransactionJournal {
            version: RUNTIME_TASK_TRANSACTION_VERSION,
            transaction_id,
            first: TaskControlPlaneUndo {
                session_id: current_first.id.clone(),
                task_list: current_first.task_list.clone(),
                task_list_version: first_version,
            },
            second: TaskControlPlaneUndo {
                session_id: current_second.id.clone(),
                task_list: current_second.task_list.clone(),
                task_list_version: second_version,
            },
        };
        let journal_path = self.write_runtime_task_journal(&journal).await?;
        self.runtime_task_recovery_required
            .store(true, Ordering::Release);

        if let Err(error) =
            self.maybe_fail_runtime_task_transaction(RuntimeTaskTransactionFault::FirstUpdatedWrite)
        {
            return self
                .fail_runtime_task_transaction_with_rollback(&journal_path, &journal, error, guard)
                .await
                .map(|()| true);
        }
        if let Err(error) = self
            .write_existing_runtime_sidecar_durable_unchecked(
                &first_commit,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                guard,
            )
            .await
        {
            return self
                .fail_runtime_task_transaction_with_rollback(&journal_path, &journal, error, guard)
                .await
                .map(|()| true);
        }

        #[cfg(test)]
        self.maybe_pause_runtime_task_transaction_after_first_write()
            .await;

        if let Err(error) = self
            .maybe_fail_runtime_task_transaction(RuntimeTaskTransactionFault::SecondUpdatedWrite)
        {
            return self
                .fail_runtime_task_transaction_with_rollback(&journal_path, &journal, error, guard)
                .await
                .map(|()| true);
        }
        if let Err(error) = self
            .write_existing_runtime_sidecar_durable_unchecked(
                &second_commit,
                RuntimeTaskDurabilityEvent::SecondUpdatedSidecarPublished,
                guard,
            )
            .await
        {
            return self
                .fail_runtime_task_transaction_with_rollback(&journal_path, &journal, error, guard)
                .await
                .map(|()| true);
        }

        match self.finalize_runtime_task_journal(&journal_path).await {
            Ok(()) => {}
            Err(RuntimeTaskJournalFinalizeError::Rollback(error)) => {
                return self
                    .fail_runtime_task_transaction_with_rollback(
                        &journal_path,
                        &journal,
                        error,
                        guard,
                    )
                    .await
                    .map(|()| true);
            }
            Err(RuntimeTaskJournalFinalizeError::RecoveryRequired(error)) => {
                // Both sidecars were synchronized before the committed marker
                // transition began. Never roll them back after a committed
                // marker may be visible: exclusive recovery will retain the
                // committed pair and durably deactivate that marker.
                self.runtime_task_recovery_required
                    .store(true, Ordering::Release);
                return Err(other_io_error(format!(
                    "runtime Task transaction committed durably but marker cleanup requires recovery: {error}"
                )));
            }
        }
        self.runtime_task_recovery_required
            .store(false, Ordering::Release);
        Ok(true)
    }

    fn runtime_task_owned_snapshot_matches(
        current: &Session,
        expected: &Session,
    ) -> io::Result<bool> {
        Ok(
            current.task_list_version_meta() == expected.task_list_version_meta()
                && serde_json::to_value(&current.task_list)
                    .map_err(|error| other_io_error(error.to_string()))?
                    == serde_json::to_value(&expected.task_list)
                        .map_err(|error| other_io_error(error.to_string()))?,
        )
    }

    fn ordinary_task_write_would_regress(
        incoming: &Session,
        durable: &Session,
    ) -> io::Result<bool> {
        if Self::runtime_task_owned_snapshot_matches(incoming, durable)? {
            return Ok(false);
        }
        let incoming_version = incoming.task_list_version_meta();
        let durable_version = durable.task_list_version_meta();
        match (incoming_version.as_deref(), durable_version.as_deref()) {
            (_, None) => Ok(false),
            (None, Some(_)) => Ok(true),
            (Some(incoming), Some(durable)) => {
                match (incoming.parse::<u64>(), durable.parse::<u64>()) {
                    (Ok(incoming), Ok(durable)) => Ok(incoming <= durable),
                    // Production Task generations are monotonic integers. An
                    // incomparable legacy/custom generation cannot prove it is
                    // newer, so preserve the durable Task snapshot fail-closed.
                    _ => Ok(true),
                }
            }
        }
    }

    /// Ordinary full/runtime saves may have queued on the shared file lock
    /// while a paired transaction advanced the durable generation. They must
    /// not silently report success after substituting a different Task
    /// snapshot: upper layers would then publish the caller's stale value into
    /// their cache. Fail before any write so the locked persistence boundary
    /// can adopt the durable Task fields and retry with one coherent snapshot.
    async fn reject_regressing_runtime_task(&self, incoming: &Session) -> io::Result<()> {
        let durable = if incoming.kind == SessionKind::Root {
            // Root writers also operate with an out-of-date local index. The
            // final Root fence has validated this canonical sidecar already.
            Self::read_runtime_sidecar_at(
                &self
                    .sessions_dir
                    .join(&incoming.id)
                    .join(RUNTIME_SIDECAR_FILE),
                &incoming.id,
            )
            .await?
            .map(Box::new)
        } else {
            self.load_runtime_control_plane_boxed_unchecked(&incoming.id)
                .await?
        };
        if let Some(durable) = durable {
            if Self::ordinary_task_write_would_regress(incoming, &durable)? {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    format!(
                        "Task control-plane changed while saving session {}",
                        incoming.id
                    ),
                ));
            }
        }
        Ok(())
    }

    fn runtime_task_non_task_snapshot(session: &Session) -> io::Result<serde_json::Value> {
        let mut snapshot = session.clone();
        snapshot.task_list = None;
        snapshot
            .metadata
            .remove(bamboo_domain::session::runtime_metadata::keys::TASK_LIST_VERSION);
        if let Some(runtime_metadata) = snapshot.runtime_metadata.as_mut() {
            runtime_metadata.task_list_version = None;
        }
        if snapshot
            .runtime_metadata
            .as_ref()
            .is_some_and(bamboo_domain::session::SessionRuntimeMetadata::is_empty)
        {
            snapshot.runtime_metadata = None;
        }
        serde_json::to_value(snapshot).map_err(|error| {
            other_io_error(format!("serialize Task transaction snapshot: {error}"))
        })
    }

    /// Task CAS/transaction replacement with a file+directory durability
    /// boundary.
    async fn write_runtime_sidecar_durable(
        &self,
        abs_dir: &Path,
        session: &Session,
        guard: &RuntimeTaskTransactionWriteGuard,
    ) -> io::Result<()> {
        self.validate_root_context_for_save(session).await?;
        let path = abs_dir.join(RUNTIME_SIDECAR_FILE);
        let snapshot = runtime_sidecar_snapshot(session);
        let bytes = serde_json::to_vec_pretty(&snapshot)
            .map_err(|error| other_io_error(error.to_string()))?;
        let guard = guard.clone();
        #[cfg(test)]
        let hook = self.task_write_hook.lock().unwrap().clone();
        tokio::task::spawn_blocking(move || {
            let _task_guard = guard;
            durable_atomic_write_blocking(&path, &bytes, |_phase| {
                #[cfg(test)]
                if let Some(hook) = hook.as_ref() {
                    hook.visit(&path, _phase)?;
                }
                Ok(())
            })
        })
        .await
        .map_err(|error| other_io_error(format!("join Task runtime publication job: {error}")))?
    }

    /// One-shot migration of legacy Child sidecars (`runtime.json`).
    ///
    /// Child loading tolerates a missing sidecar by falling back to the
    /// embedded control-plane in `session.json`. A main-only Root is
    /// indistinguishable from one that lost a newer Project or tool revision,
    /// so operational Root reads and writes reject it. Its canonical runtime
    /// must be restored; this migration cannot establish that authority.
    ///
    /// Idempotent and cheap on later boots: guarded by a marker file, and any
    /// session that already has a sidecar is skipped. Returns the number of
    /// sidecars created.
    pub async fn migrate_runtime_sidecars(&self) -> io::Result<usize> {
        let marker = self.bamboo_home_dir.join(RUNTIME_SIDECAR_MIGRATION_MARKER);
        if fs::try_exists(&marker).await.unwrap_or(false) {
            return Ok(0);
        }

        // Index/marker observations route work; each candidate owns its final
        // lifecycle -> Task -> Session boundary. No outer Task guard re-entry.
        let entries = self.list_index_entries().await;
        let mut migrated = 0usize;
        for entry in entries {
            #[cfg(test)]
            {
                let pause = self.migration_scan_pause.lock().unwrap().clone();
                if let Some(pause) = pause.filter(|pause| pause.id == entry.id) {
                    pause.reached.wait().await;
                    pause.release.wait().await;
                }
            }
            if self.migrate_runtime_candidate(&entry).await? {
                migrated += 1;
            }
        }

        // Persist the marker last, atomically, so an interrupted migration simply
        // re-runs (it is idempotent) instead of being falsely marked complete.
        let tmp = marker.with_extension(format!("tmp.{}", Uuid::new_v4()));
        fs::write(&tmp, b"runtime-sidecar-v1\n").await?;
        atomic_rename(&tmp, &marker).await?;

        if migrated > 0 {
            tracing::info!("runtime sidecar migration: created {migrated} sidecar(s)");
        }
        Ok(migrated)
    }

    async fn migrate_runtime_candidate(&self, entry: &SessionIndexEntry) -> io::Result<bool> {
        // Reject an index escape before opening any hinted target. The hint is
        // not authority for birth/lineage; compare against the locked raw main.
        validate_session_id(&entry.id)?;
        let (kind, root) = Self::copy_source_identity_from_rel(&entry.id, &entry.rel_path)?;
        if entry.kind != kind || entry.root_session_id != root {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "migration index identity mismatch",
            ));
        }
        let lifecycle = self.lock_session_lifecycle_shared().await?;
        let task = self.lock_runtime_task_sidecar_shared().await?;
        let session_guard = self.acquire_session_maintenance_lock(&entry.id).await?;
        let guards = DefaultWriterGuards::shared(lifecycle, task, session_guard);
        let directory = self.abs_path_from_rel(&entry.rel_path);
        match fs::symlink_metadata(&directory).await {
            Ok(meta) if meta.file_type().is_dir() => {}
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "migration target is not a real directory",
                ))
            }
        }
        let path = directory.join(RUNTIME_SIDECAR_FILE);
        match fs::symlink_metadata(&path).await {
            Ok(meta) if meta.file_type().is_file() => return Ok(false),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "migration sidecar is not a regular file",
                ))
            }
        }
        let main = directory.join("session.json");
        match fs::symlink_metadata(&main).await {
            Ok(meta) if meta.file_type().is_file() => {}
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "migration main is not a regular file",
                ))
            }
        }
        let raw = match fs::read(&main).await {
            Ok(raw) => raw,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
        };
        if let Err(error) = compact_main::validate_full_main(&raw) {
            tracing::warn!(session_id = %entry.id, %error, "runtime migration skipped invalid compact Main");
            return Ok(false);
        }
        let mut session: Session = match serde_json::from_slice(&raw) {
            Ok(session) => session,
            Err(error) => {
                tracing::warn!(
                    "runtime sidecar migration: skipping unreadable session {}: {}",
                    entry.id,
                    error
                );
                return Ok(false);
            }
        };
        if session.kind == SessionKind::Root && session.root_session_id.is_empty() {
            session.root_session_id = session.id.clone();
        }
        if session.id != entry.id
            || session.kind != kind
            || session.root_session_id != root
            || session.parent_session_id != entry.parent_session_id
            || session.spawn_depth != entry.spawn_depth
            || session.created_at != entry.created_at
            || Self::default_writer_rel_path(&session)? != entry.rel_path
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "migration main creation identity mismatch",
            ));
        }
        // Local typed identity validation; no Actor ensure, repair or lineage
        // enumeration. Existing Root/Supervisor proof checks retain their gate.
        bamboo_domain::ActorSession::from_session(&session).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "migration main lineage is invalid",
            )
        })?;
        supervisor::validate_identity(&session)?;
        if !matches!(
            session.authority_identity,
            SessionAuthorityIdentity::Ordinary
        ) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "cannot reconstruct missing Supervisor authority from session.json",
            ));
        }
        self.validate_root_context_for_save(&session).await?;
        self.check_actor_reconstruction(&session, &directory)
            .await?;
        let bytes = serde_json::to_vec_pretty(&runtime_sidecar_snapshot(&session))
            .map_err(|error| other_io_error(error.to_string()))?;
        self.write_default_bytes(&path, bytes, &guards).await?;
        Ok(true)
    }

    /// Read the runtime sidecar (a Session snapshot with empty `messages`), if it
    /// exists. Returns `None` when the session has no sidecar yet (e.g. legacy
    /// sessions not yet migrated). Path is resolved through the index.
    async fn read_runtime_sidecar(&self, session_id: &str) -> io::Result<Option<Session>> {
        Ok(self
            .read_runtime_sidecar_boxed(session_id)
            .await?
            .map(|session| *session))
    }

    async fn read_runtime_sidecar_boxed(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Box<Session>>> {
        let Some(path) = self.runtime_json_path(session_id).await? else {
            return Ok(None);
        };
        Self::read_runtime_sidecar_boxed_at(&path, session_id).await
    }

    /// Read + deserialize a runtime sidecar (`runtime.json`) from a known path.
    /// A missing file yields `None`; a corrupt one is ignored with a warning
    /// for Ordinary compatibility. Supervisor callers validate the canonical
    /// pair and reject missing or corrupt runtime authority. Shared by
    /// [`Self::read_runtime_sidecar`] (index-resolved path) and the index
    /// rebuild (directory-scanned path) so both overlay the sidecar identically.
    async fn read_runtime_sidecar_at(path: &Path, id: &str) -> io::Result<Option<Session>> {
        Ok(Self::read_runtime_sidecar_boxed_at(path, id)
            .await?
            .map(|session| *session))
    }

    async fn read_runtime_sidecar_boxed_at(
        path: &Path,
        id: &str,
    ) -> io::Result<Option<Box<Session>>> {
        if !path.exists() {
            return Ok(None);
        }
        let raw = fs::read_to_string(path).await?;
        match serde_json::from_str::<Box<Session>>(&raw) {
            Ok(mut side) => {
                supervisor::validate_identity(&side)?;
                // The control-plane path (`load_runtime_control_plane`) returns
                // this directly, so migrate a stale Root token_budget here too (#230).
                side.clear_stale_root_token_budget();
                Ok(Some(side))
            }
            Err(error) => {
                // Ordinary Sessions may recover from session.json. Supervisor
                // pair validation rejects this fallback before use or writes.
                tracing::warn!("ignoring corrupt runtime sidecar for {id}: {error}");
                Ok(None)
            }
        }
    }

    async fn attachments_dir(&self, session_id: &str) -> io::Result<Option<PathBuf>> {
        if let Some(rel) = self.resolve_rel_path(session_id).await {
            Ok(Some(self.abs_path_from_rel(&rel).join("attachments")))
        } else {
            Ok(None)
        }
    }

    async fn compute_has_attachments(&self, session_id: &str) -> bool {
        let Ok(Some(dir)) = self.attachments_dir(session_id).await else {
            return false;
        };
        let Ok(mut rd) = fs::read_dir(dir).await else {
            return false;
        };
        rd.next_entry().await.ok().flatten().is_some()
    }

    async fn upsert_index_from_session(
        &self,
        session: &Session,
        rel_path: String,
    ) -> io::Result<()> {
        self.upsert_index_from_session_inner(session, rel_path, false, None)
            .await
    }

    async fn repair_index_from_authoritative_session(
        &self,
        session: &Session,
        rel_path: String,
    ) -> io::Result<()> {
        self.upsert_index_from_session_inner(session, rel_path, true, None)
            .await
    }

    async fn upsert_index_from_session_inner(
        &self,
        session: &Session,
        rel_path: String,
        preserve_newer: bool,
        known_has_attachments: Option<bool>,
    ) -> io::Result<()> {
        let has_attachments = match known_has_attachments {
            Some(value) => value,
            None => self.compute_has_attachments(&session.id).await,
        };
        // Read the well-known runtime keys via the typed accessors, which prefer
        // `runtime_metadata` and fall back to the legacy `metadata` strings.
        let last_run_status = session
            .last_run_status()
            .filter(|value| !value.trim().is_empty());
        let last_run_error = session
            .last_run_error()
            .filter(|value| !value.trim().is_empty());
        let created_by_schedule_id = session
            .metadata
            .get("created_by_schedule_id")
            .cloned()
            .filter(|v| !v.trim().is_empty());
        let schedule_run_id = session
            .metadata
            .get("schedule_run_id")
            .cloned()
            .filter(|v| !v.trim().is_empty());
        let subagent_type = session.subagent_type().filter(|v| !v.trim().is_empty());
        let lifecycle = session
            .metadata
            .get("lifecycle")
            .cloned()
            .filter(|v| !v.trim().is_empty());
        let resident_name = session
            .metadata
            .get("resident_name")
            .cloned()
            .filter(|v| !v.trim().is_empty());
        let gold_config_json = session
            .metadata
            .get("gold_config")
            .cloned()
            .filter(|v| !v.trim().is_empty());
        let plan_mode = session
            .agent_runtime_state
            .as_ref()
            .and_then(|state| state.plan_mode.clone());
        let permission_mode = session
            .agent_runtime_state
            .as_ref()
            .map(|state| state.effective_permission_mode())
            .unwrap_or_default();
        let bypass_permissions = permission_mode != bamboo_domain::SessionPermissionMode::Default;
        // Placement (which machine the agent runs on) is stamped by the spawn
        // path into `metadata["placement"]` as a JSON `{kind,host}` object for
        // remote/deployed children; local sessions leave it unset and the DTO
        // layer defaults them to this backend's own host.
        let placement = session
            .metadata
            .get("placement")
            .and_then(|v| serde_json::from_str::<SessionPlacement>(v).ok());
        let workspace_path = session
            .workspace_path_meta()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        let project_id = normalized_project_id(session);
        let session_id = session.id.clone();
        let entry = SessionIndexEntry {
            id: session.id.clone(),
            kind: session.kind,
            rel_path,
            title: session.title.clone(),
            title_version: session.title_version,
            title_generated: session.title_generated,
            pinned: session.pinned,
            parent_session_id: session.parent_session_id.clone(),
            root_session_id: session.root_session_id.clone(),
            spawn_depth: session.spawn_depth,
            model: session.model.clone(),
            model_ref: session.model_ref.clone(),
            reasoning_effort: session.reasoning_effort,
            workspace_path,
            project_id,
            gold_config_json,
            created_by_schedule_id,
            schedule_run_id,
            created_at: session.created_at,
            updated_at: session.updated_at,
            last_activity_at: session.updated_at,
            message_count: session.messages.len(),
            has_attachments,
            has_pending_question: session.has_pending_question(),
            plan_mode,
            bypass_permissions,
            permission_mode,
            last_run_status,
            last_run_error,
            token_usage: session.token_usage.clone(),
            subagent_type,
            lifecycle,
            resident_name,
            placement,
        };
        self.update_index(move |index: &mut SessionsIndex| {
            if preserve_newer {
                if let Some(existing) = index.sessions.get_mut(&session_id) {
                    if existing.updated_at > entry.updated_at {
                        // A live process may already have published fresher
                        // summary/control-plane fields than the authoritative
                        // transcript snapshot being probed. Preserve those
                        // fields while repairing canonical root identity/path.
                        existing.id = entry.id.clone();
                        existing.kind = entry.kind;
                        existing.rel_path = entry.rel_path.clone();
                        existing.parent_session_id = entry.parent_session_id.clone();
                        existing.root_session_id = entry.root_session_id.clone();
                        existing.spawn_depth = entry.spawn_depth;
                        return Ok(());
                    }
                }
            }
            index.sessions.insert(session_id, entry);
            Ok(())
        })
        .await
    }

    pub async fn write_image_attachment(
        &self,
        session: &Session,
        raw_base64_or_data_url: &str,
        mime_hint: Option<&str>,
    ) -> io::Result<(String, String)> {
        self.write_image_attachment_inner(session, raw_base64_or_data_url, mime_hint, false)
            .await
    }

    /// Store immutable image content under a repeatable reference for durable
    /// message admission retries. Ordinary chat attachment naming is unchanged.
    pub async fn write_image_attachment_deduplicated(
        &self,
        session: &Session,
        raw_base64_or_data_url: &str,
        mime_hint: Option<&str>,
    ) -> io::Result<(String, String)> {
        self.write_image_attachment_inner(session, raw_base64_or_data_url, mime_hint, true)
            .await
    }

    async fn write_image_attachment_inner(
        &self,
        session: &Session,
        raw_base64_or_data_url: &str,
        mime_hint: Option<&str>,
        deduplicate: bool,
    ) -> io::Result<(String, String)> {
        let _lifecycle = self.lock_session_lifecycle_shared().await?;
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let (mime, base64_data) =
            parse_data_url_base64(raw_base64_or_data_url).unwrap_or_else(|| {
                (
                    mime_hint.unwrap_or("image/png").trim().to_string(),
                    raw_base64_or_data_url.trim().to_string(),
                )
            });

        let bytes = base64::engine::general_purpose::STANDARD
            .decode(base64_data.as_bytes())
            .map_err(|e| other_io_error(format!("invalid base64 image data: {e}")))?;

        let attachment_id = if deduplicate {
            use sha2::{Digest, Sha256};
            let mut digest = Sha256::new();
            digest.update(mime.as_bytes());
            digest.update([0]);
            digest.update(&bytes);
            digest
                .finalize()
                .iter()
                .map(|byte| format!("{byte:02x}"))
                .collect::<String>()
        } else {
            Uuid::new_v4().to_string()
        };
        let ext = mime_to_extension(mime.as_str()).unwrap_or("bin");

        let rel_path = self.ensure_session_dirs(session).await?;
        let abs_dir = self.abs_path_from_rel(&rel_path);
        let attachments_dir = abs_dir.join("attachments");
        fs::create_dir_all(&attachments_dir).await?;

        let path = attachments_dir.join(format!("{attachment_id}.{ext}"));
        let tmp = path.with_extension(format!("{ext}.tmp.{}", Uuid::new_v4()));
        fs::write(&tmp, &bytes).await?;
        atomic_rename(&tmp, &path).await?;

        Ok((
            attachment_id.clone(),
            format!("bamboo-attachment://{}/{}", session.id, attachment_id),
        ))
    }

    /// Read an attachment by id, returning bytes + inferred MIME.
    pub async fn read_attachment(
        &self,
        session_id: &str,
        attachment_id: &str,
    ) -> io::Result<Option<(Vec<u8>, String)>> {
        validate_session_id(session_id)?;
        validate_session_id(attachment_id)?;
        let Some(dir) = self.attachments_dir(session_id).await? else {
            return Ok(None);
        };
        if !dir.exists() {
            return Ok(None);
        }

        let mut rd = fs::read_dir(&dir).await?;
        while let Some(entry) = rd.next_entry().await? {
            let file_name = entry.file_name();
            let file_name = file_name.to_string_lossy();
            if !file_name.starts_with(attachment_id) {
                continue;
            }
            // Match "<id>.<ext>"
            if file_name.len() <= attachment_id.len() + 1
                || !file_name.as_bytes()[attachment_id.len()].eq(&b'.')
            {
                continue;
            }
            let ext = file_name.split('.').next_back().unwrap_or("bin");
            let mime = extension_to_mime(ext).unwrap_or("application/octet-stream");
            let bytes = fs::read(entry.path()).await?;
            return Ok(Some((bytes, mime.to_string())));
        }

        Ok(None)
    }

    /// Copy one session into a new, independent root session.
    ///
    /// The caller must serialize the source with the ordinary per-session
    /// persistence lock before invoking this method. The lifecycle write lock
    /// prevents a concurrent delete/rebuild from racing the source attachment
    /// snapshot or observing the private staging directory; the exclusive
    /// runtime/task lock also freezes cross-process writers. The fully written
    /// directory is renamed into place before the index entry is published;
    /// any pre-commit error removes every target artifact and index projection.
    /// Once the durable committed marker is published, recovery completes the
    /// successful copy instead of reverting it.
    pub async fn copy_session(&self, source_id: &str, new_id: &str) -> io::Result<Option<Session>> {
        Ok(self
            .copy_session_with_projection_guard(source_id, new_id)
            .await?
            .map(|(session, guard)| {
                drop(guard);
                session
            }))
    }

    /// Copy a session while retaining the cross-process publication boundary.
    /// The caller must drop the returned guard only after all process-local
    /// cache/workspace/feed projections derived from the returned snapshot are
    /// visible.
    pub async fn copy_session_with_projection_guard(
        &self,
        source_id: &str,
        new_id: &str,
    ) -> io::Result<Option<(Session, SessionCopyProjectionGuard)>> {
        validate_session_id(source_id)?;
        validate_session_id(new_id)?;
        if source_id == new_id {
            return Err(other_io_error("source and copied session ids must differ"));
        }

        let _lifecycle = self.lock_session_lifecycle_exclusive().await?;
        // Ordinary full/runtime saves hold the shared form of this lock. The
        // exclusive claim freezes every cross-process source writer while we
        // read session.json/runtime.json and copy referenced attachments.
        let _runtime_task = self.lock_runtime_task_transaction_exclusive().await?;
        self.recover_all_runtime_task_transactions_locked(&_runtime_task)
            .await?;
        self.recover_all_session_copy_transactions_locked().await?;
        let Some(source_rel) = self.resolve_rel_path(source_id).await else {
            return Ok(None);
        };
        let (expected_source_kind, expected_source_root) =
            Self::copy_source_identity_from_rel(source_id, &source_rel)?;
        if self.resolve_rel_path(new_id).await.is_some() {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "copied session id already exists",
            ));
        }
        if self.root_revocation(new_id).await?.is_some() {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "copied session ID was deleted; use a new ID or trusted Root recreation",
            ));
        }

        let source_dir = self.abs_path_from_rel(&source_rel);
        let source = self
            .load_session_from_dir_strict(
                &source_dir,
                source_id,
                expected_source_kind,
                &expected_source_root,
            )
            .await?
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::NotFound,
                    "indexed source session.json is missing",
                )
            })?;
        let target_rel = Self::root_rel_path(new_id);
        let target_dir = self.abs_path_from_rel(&target_rel);
        if fs::try_exists(&target_dir).await? {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "copied session directory already exists",
            ));
        }
        let transaction_id = Uuid::new_v4().to_string();
        let journal = SessionCopyTransactionJournal {
            version: SESSION_COPY_TRANSACTION_VERSION,
            transaction_id,
            source_id: source_id.to_string(),
            target_id: new_id.to_string(),
        };
        let staging_dir = self.session_copy_staging_dir(&journal);
        let mut copied = copied_session_snapshot(&source, new_id);
        rewrite_attachment_session_urls(&mut copied, source_id, new_id);
        let main_bytes = compact_main::serialize_main(&copied)?;
        let journal_path = self.write_session_copy_journal(&journal).await?;
        let has_attachments = match self
            .write_copied_session(&source_dir, &staging_dir, &target_dir, &copied, &main_bytes)
            .await
        {
            Ok(has_attachments) => has_attachments,
            Err(error) => {
                return self
                    .fail_session_copy_with_rollback(&journal_path, &journal, error)
                    .await
                    .map(|()| None)
            }
        };
        let (search_revision_path, search_revision) =
            match self.publish_search_revision(&target_dir).await {
                Ok(revision) => revision,
                Err(error) => {
                    return self
                        .fail_session_copy_with_rollback(&journal_path, &journal, error)
                        .await
                        .map(|()| None)
                }
            };
        let committing = journal_path.with_extension("committing");
        if let Err(error) = atomic_rename(&journal_path, &committing).await {
            return self
                .fail_session_copy_with_rollback(&journal_path, &journal, error)
                .await
                .map(|()| None);
        }
        if let Err(error) = sync_parent_directory_entry(&committing).await {
            return self
                .fail_session_copy_with_rollback(&committing, &journal, error)
                .await
                .map(|()| None);
        }
        let committed = journal_path.with_extension("committed");
        if let Err(error) = atomic_rename(&committing, &committed).await {
            return self
                .fail_session_copy_with_rollback(&committing, &journal, error)
                .await
                .map(|()| None);
        }
        if let Err(error) = sync_parent_directory_entry(&committed).await {
            // A rename is not a durable commit boundary until its containing
            // directory is synchronized. Do not acknowledge a copy whose
            // recovery decision could revert to `.committing` after power loss.
            return self
                .fail_session_copy_with_rollback(&committed, &journal, error)
                .await
                .map(|()| None);
        }
        // Only a durable committed marker may precede public index visibility.
        // A crash from here is completed by startup recovery; while this call
        // remains alive, any publication error is synchronously rolled back.
        if let Err(error) = self
            .upsert_index_from_session_inner(&copied, target_rel, false, Some(has_attachments))
            .await
        {
            return self
                .fail_session_copy_with_rollback(&committed, &journal, error)
                .await
                .map(|()| None);
        }
        self.search_index_queue
            .enqueue_upsert(&copied, search_revision_path, search_revision);
        // A retained committed marker is safe: every target-removing lifecycle
        // operation recovers committed copies before it mutates the tree. This
        // marker cleanup is therefore retryable maintenance after the durable
        // commit decision, not a reason to report a committed copy as failed.
        if let Err(error) = durable_deactivate_recovery_marker(&committed).await {
            tracing::warn!(session_id = new_id, %error, "copied session committed; journal cleanup deferred to lifecycle recovery");
        }
        Ok(Some((
            copied,
            SessionCopyProjectionGuard {
                _lifecycle,
                _runtime_task,
            },
        )))
    }

    async fn write_copied_session(
        &self,
        source_dir: &Path,
        staging_dir: &Path,
        target_dir: &Path,
        copied: &Session,
        main_bytes: &[u8],
    ) -> io::Result<bool> {
        fs::create_dir(staging_dir).await?;
        fs::create_dir(staging_dir.join("children")).await?;
        let source_attachments = source_dir.join("attachments");
        let staging_attachments = staging_dir.join("attachments");
        fs::create_dir(&staging_attachments).await?;
        let mut has_attachments = false;
        if fs::try_exists(&source_attachments).await? {
            let mut entries = fs::read_dir(&source_attachments).await?;
            while let Some(entry) = entries.next_entry().await? {
                if !entry.file_type().await?.is_file() {
                    continue;
                }
                durable_copy_file(&entry.path(), &staging_attachments.join(entry.file_name()))
                    .await?;
                has_attachments = true;
            }
        }
        // Persist copied file names after each file's contents have reached
        // stable storage. The later staging-directory sync only persists the
        // `attachments/` directory entry, not entries inside that directory.
        sync_directory(&staging_attachments).await?;

        let runtime_snapshot = runtime_sidecar_snapshot(copied);
        let runtime_bytes = serde_json::to_vec_pretty(&runtime_snapshot)
            .map_err(|error| other_io_error(error.to_string()))?;
        durable_atomic_write(&staging_dir.join(RUNTIME_SIDECAR_FILE), &runtime_bytes).await?;
        durable_atomic_write(&staging_dir.join("session.json"), main_bytes).await?;
        Self::stage_actor_tree_revision(staging_dir, copied).await?;
        Self::write_staged_root_tool_proof(staging_dir, copied).await?;
        Self::write_staged_supervisor_proof(staging_dir, copied).await?;
        // Flush the staging directory after its children/attachments are all
        // complete, before its name is published under `sessions/`.
        sync_parent_directory_entry(&staging_dir.join("session.json")).await?;
        atomic_rename(staging_dir, target_dir).await?;
        // This rename crosses from `$BAMBOO_HOME` into `sessions/`: both
        // directory entries must be synchronized before publishing the target.
        sync_parent_directory_entry(staging_dir).await?;
        sync_parent_directory_entry(target_dir).await?;
        Ok(has_attachments)
    }

    async fn fail_session_copy_with_rollback(
        &self,
        marker_path: &Path,
        journal: &SessionCopyTransactionJournal,
        primary: io::Error,
    ) -> io::Result<()> {
        let primary_kind = primary.kind();
        let primary_message = primary.to_string();
        // A durable `.committed` marker tells startup to finish the copy. If a
        // live caller has not acknowledged success and chooses rollback, first
        // durably move that decision back to a rollback state. Otherwise a
        // partial cleanup could leave a committed marker pointing at a removed
        // target and make every subsequent startup fail closed forever.
        if SessionCopyJournalMarkerState::from_path(marker_path)
            == Some(SessionCopyJournalMarkerState::Committed)
        {
            let rollback_marker = marker_path.with_extension("committing");
            if let Err(error) = async {
                atomic_rename(marker_path, &rollback_marker).await?;
                sync_parent_directory_entry(&rollback_marker).await
            }
            .await
            {
                return Err(other_io_error(format!(
                    "session copy failed ({primary_message}); could not persist rollback decision ({error}); recovery required"
                )));
            }
        }
        match self.rollback_session_copy_transaction(journal).await {
            Ok(()) => match self.remove_session_copy_journal_family(journal).await {
                Ok(()) => Err(io::Error::new(
                    primary_kind,
                    format!("session copy failed and was rolled back: {primary_message}"),
                )),
                Err(cleanup_error) => Err(other_io_error(format!(
                    "session copy failed ({primary_message}); rollback succeeded but journal cleanup failed ({cleanup_error}); recovery required"
                ))),
            },
            Err(rollback_error) => Err(other_io_error(format!(
                "session copy failed ({primary_message}); rollback failed ({rollback_error}); recovery required"
            ))),
        }
    }

    pub async fn clear_session(&self, session_id: &str) -> io::Result<bool> {
        validate_session_id(session_id)?;
        let lifecycle = self.lock_session_lifecycle_exclusive().await?;
        let runtime_task = self.lock_runtime_task_transaction_exclusive().await?;
        self.recover_all_runtime_task_transactions_locked(&runtime_task)
            .await?;
        self.recover_all_session_copy_transactions_locked().await?;
        let session_write = self.acquire_session_maintenance_lock(session_id).await?;
        let guards = DefaultWriterGuards::exclusive(lifecycle, runtime_task, session_write);

        let Some(entry) = self.get_index_entry(session_id).await else {
            return Ok(false);
        };
        let rel_path = entry.rel_path.clone();
        let abs_dir = self.abs_path_from_rel(&rel_path);
        self.check_default_actor_clear(&abs_dir).await?;
        let Some(mut session) = self
            .load_session_from_dir_strict(&abs_dir, session_id, entry.kind, &entry.root_session_id)
            .await?
        else {
            return Ok(false);
        };

        self.validate_root_context_for_save(&session).await?;

        // Keep only the first System message if present; drop all other messages.
        let system_msg = session
            .messages
            .iter()
            .find(|m| matches!(m.role, Role::System))
            .cloned();
        session.messages.clear();
        if let Some(system) = system_msg {
            session.messages.push(system);
        }

        // Clearing history invalidates derived context state.
        session.token_usage = None;
        session.conversation_summary = None;
        session.updated_at = Utc::now();

        // One started job owns cleanup and the resulting canonical files.
        let (revision_path, revision) = self
            .clear_default_session_files(&abs_dir, &session, &guards)
            .await?;
        self.upsert_index_from_session_inner(&session, rel_path, false, Some(false))
            .await?;
        self.search_index_queue
            .enqueue_upsert(&session, revision_path, revision);
        Ok(true)
    }

    pub async fn cleanup(&self, mode: CleanupMode, keep_pinned: bool) -> io::Result<CleanupResult> {
        let lifecycle = self.lock_session_lifecycle_exclusive().await?;
        let runtime_task = self.lock_runtime_task_transaction_exclusive().await?;
        let guards = Arc::new(SessionDeletionGuards {
            runtime_task,
            _lifecycle: lifecycle,
        });
        self.recover_all_runtime_task_transactions_locked(&guards.runtime_task)
            .await?;
        self.recover_all_session_copy_transactions_locked().await?;

        // All decisions are index-only.
        let entries = {
            self.index
                .read()
                .await
                .sessions
                .values()
                .cloned()
                .collect::<Vec<_>>()
        };

        let pinned_child_roots: HashSet<String> = if keep_pinned {
            entries
                .iter()
                .filter(|e| e.kind == SessionKind::Child && e.pinned)
                .filter_map(|e| e.parent_session_id.clone())
                .collect()
        } else {
            HashSet::new()
        };

        // Helper to decide whether an entry is protected.
        let is_protected = |e: &SessionIndexEntry| -> bool {
            if !keep_pinned {
                return false;
            }
            if e.pinned {
                return true;
            }
            // A root with pinned child cannot be deleted.
            if e.kind == SessionKind::Root && pinned_child_roots.contains(&e.id) {
                return true;
            }
            false
        };

        // Determine deletions as a set of session ids (roots and/or children).
        let mut delete_child_ids = HashSet::<String>::new();
        let mut delete_root_ids = HashSet::<String>::new();

        match mode {
            CleanupMode::Children => {
                for e in entries.iter().filter(|e| e.kind == SessionKind::Child) {
                    if is_protected(e) {
                        continue;
                    }
                    delete_child_ids.insert(e.id.clone());
                }
            }
            CleanupMode::All | CleanupMode::Empty => {
                // First decide which roots can be deleted.
                for root in entries.iter().filter(|e| e.kind == SessionKind::Root) {
                    if is_protected(root) {
                        continue;
                    }
                    if mode == CleanupMode::Empty && root.message_count > 1 {
                        continue;
                    }
                    delete_root_ids.insert(root.id.clone());
                }

                // For roots we keep, we may still delete some children (e.g., unpinned, or empty).
                for child in entries.iter().filter(|e| e.kind == SessionKind::Child) {
                    if delete_root_ids.contains(&child.root_session_id) {
                        continue; // will be deleted with root.
                    }
                    if is_protected(child) {
                        continue;
                    }
                    if mode == CleanupMode::Empty && child.message_count > 1 {
                        continue;
                    }
                    delete_child_ids.insert(child.id.clone());
                }
            }
        }

        // Pre-compute full deleted id set for a truthful response payload.
        let mut deleted_ids = HashSet::<String>::new();
        for root_id in delete_root_ids.iter() {
            for e in entries.iter().filter(|e| e.root_session_id == *root_id) {
                deleted_ids.insert(e.id.clone());
            }
        }
        for child_id in delete_child_ids.iter() {
            deleted_ids.insert(child_id.clone());
        }

        // Apply deletions (roots first; they delete children implicitly).
        for root_id in delete_root_ids.iter() {
            let _ = self
                .delete_session_recursive_locked(root_id, true, &guards)
                .await?;
        }
        for child_id in delete_child_ids.iter() {
            let _ = self
                .delete_session_recursive_locked(child_id, true, &guards)
                .await?;
        }
        let mut deleted_session_ids: Vec<String> = deleted_ids.into_iter().collect();
        deleted_session_ids.sort();
        Ok(CleanupResult {
            deleted_count: deleted_session_ids.len(),
            deleted_session_ids,
        })
    }

    /// Development-only: hard reset all sessions and the index.
    ///
    /// This is the supported "greenfield" history/index mechanism. It deletes:
    /// - `bamboo_home_dir/sessions/`
    /// - `bamboo_home_dir/sessions.json` (rewritten to empty index)
    ///
    /// Root revocations remain canonical so surviving processes cannot restore
    /// their deleted snapshots after this reset.
    pub async fn dev_reset(&self) -> io::Result<()> {
        let _lifecycle = self.lock_session_lifecycle_exclusive().await?;
        let _runtime_task = self.lock_runtime_task_transaction_exclusive().await?;
        self.recover_all_runtime_task_transactions_locked(&_runtime_task)
            .await?;
        self.recover_all_session_copy_transactions_locked().await?;

        let deleted_search_sources = self
            .index
            .read()
            .await
            .sessions
            .values()
            .map(|entry| {
                (
                    entry.id.clone(),
                    self.abs_path_from_rel(&entry.rel_path)
                        .join(SEARCH_INDEX_REVISION_FILE),
                )
            })
            .collect::<Vec<_>>();

        // Revoke canonical Roots before removing the tree, including Roots
        // omitted by this process's stale index. Preserve the revocations
        // outside sessions/: stale writers may survive this development reset.
        let mut roots = fs::read_dir(&self.sessions_dir).await?;
        while let Some(root) = roots.next_entry().await? {
            if root.file_type().await?.is_dir() {
                if let Some(id) = root.file_name().to_str() {
                    self.revoke_root_lifetime(id).await?;
                }
            }
        }
        match fs::remove_dir_all(&self.sessions_dir).await {
            Ok(()) => sync_parent_directory_entry(&self.sessions_dir).await?,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        fs::create_dir_all(&self.sessions_dir).await?;
        sync_parent_directory_entry(&self.sessions_dir).await?;

        // Reset through the same cross-process rebase/publish boundary as every
        // other index mutation; dev reset must not race a stale direct writer.
        self.update_index(|index| {
            *index = SessionsIndex::empty();
            Ok(())
        })
        .await?;
        for (session_id, revision_path) in deleted_search_sources {
            self.search_index_queue
                .enqueue_delete(&session_id, revision_path);
        }
        Ok(())
    }

    /// Delete a session. If the session is a root, deletes its entire directory (and all child sessions).
    /// If the session is a child, deletes only that child directory.
    ///
    /// `force=true` ignores pinned protection; callers must enforce confirmations at the API/UI layer.
    pub async fn delete_session_recursive(
        &self,
        session_id: &str,
        force: bool,
    ) -> io::Result<bool> {
        let lifecycle = self.lock_session_lifecycle_exclusive().await?;
        let runtime_task = self.lock_runtime_task_transaction_exclusive().await?;
        let guards = Arc::new(SessionDeletionGuards {
            runtime_task,
            _lifecycle: lifecycle,
        });
        self.recover_all_runtime_task_transactions_locked(&guards.runtime_task)
            .await?;
        self.recover_all_session_copy_transactions_locked().await?;
        self.delete_session_recursive_locked(session_id, force, &guards)
            .await
    }

    async fn remove_child_directory(
        &self,
        directory: &Path,
        guards: &Arc<SessionDeletionGuards>,
        tree: &Arc<ActorTreeWriteGuard>,
    ) -> io::Result<()> {
        let directory = directory.to_path_buf();
        let guards = Arc::clone(guards);
        let tree = Arc::clone(tree);
        #[cfg(test)]
        let hook = self.child_delete_hook.lock().unwrap().clone();
        tokio::task::spawn_blocking(move || {
            // Tokio filesystem jobs outlive a cancelled waiter or runtime.
            // Retain the acquired guards until this physical removal ends.
            let _guards = guards;
            let _tree = tree;
            #[cfg(test)]
            let _finished = hook.as_ref().map(|hook| hook.enter());
            std::fs::remove_dir_all(directory)
        })
        .await
        .map_err(|_| other_io_error("background task failed"))?
    }

    async fn delete_session_recursive_locked(
        &self,
        session_id: &str,
        force: bool,
        guards: &Arc<SessionDeletionGuards>,
    ) -> io::Result<bool> {
        validate_session_id(session_id)?;
        let entry = self.get_index_entry(session_id).await;
        let root_birth = self.canonical_root_birth(session_id).await?;
        let revoked_directory = root_birth.is_none()
            && self.root_revocation(session_id).await?.is_some()
            && fs::try_exists(self.sessions_dir.join(session_id)).await?;
        if root_birth.is_some()
            || revoked_directory
            || entry
                .as_ref()
                .is_some_and(|entry| entry.kind == SessionKind::Root)
        {
            if !force
                && (entry.as_ref().is_some_and(|entry| entry.pinned)
                    || self
                        .load_authoritative_root_session(session_id)
                        .await?
                        .is_some_and(|root| root.pinned))
            {
                return Err(other_io_error(
                    "refusing to delete pinned session without force",
                ));
            }
            if !self.revoke_root_lifetime(session_id).await? {
                return Err(other_io_error(
                    "cannot revoke Root without canonical birth evidence",
                ));
            }
            let directory = self.sessions_dir.join(session_id);
            match fs::remove_dir_all(&directory).await {
                Ok(()) => sync_parent_directory_entry(&directory).await?,
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
            let removed = self
                .update_index(|index| {
                    let removed = index
                        .sessions
                        .values()
                        .filter(|entry| {
                            entry.id == session_id || entry.root_session_id == session_id
                        })
                        .map(|entry| (entry.id.clone(), entry.rel_path.clone()))
                        .collect::<Vec<_>>();
                    for (id, _) in &removed {
                        index.sessions.remove(id);
                    }
                    Ok(removed)
                })
                .await?;
            for (id, rel) in removed {
                self.search_index_queue.enqueue_delete(
                    &id,
                    self.abs_path_from_rel(&rel)
                        .join(SEARCH_INDEX_REVISION_FILE),
                );
            }
            return Ok(true);
        }
        let Some(entry) = entry else {
            return Ok(false);
        };

        if !force && entry.pinned {
            return Err(other_io_error(
                "refusing to delete pinned session without force",
            ));
        }

        match entry.kind {
            SessionKind::Child => {
                let tree = Arc::new(
                    self.acquire_actor_tree_write_guard(&entry.root_session_id)
                        .await?,
                );
                if let Some(root) = self
                    .actor_tree_root_for_child_write(&entry.root_session_id)
                    .await?
                {
                    self.bump_actor_tree_revision(&root).await?;
                }
                self.cancel_descendant_activations_before_child_delete(
                    &entry.root_session_id,
                    session_id,
                    guards,
                    &tree,
                )
                .await?;
                let abs_dir = self.abs_path_from_rel(&entry.rel_path);
                let _ = self.remove_child_directory(&abs_dir, guards, &tree).await;
                self.update_index(|index| {
                    index.sessions.remove(session_id);
                    Ok(())
                })
                .await?;
                self.search_index_queue
                    .enqueue_delete(session_id, abs_dir.join(SEARCH_INDEX_REVISION_FILE));
                Ok(true)
            }
            SessionKind::Root => unreachable!("Root deletion handled from canonical placement"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CleanupMode {
    All,
    Empty,
    Children,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CleanupResult {
    pub deleted_count: usize,
    pub deleted_session_ids: Vec<String>,
}

/// Atomically write `bytes` to `path`: write a uniquely-named temp file in the
/// same directory, fsync it to durable storage, then atomically rename over the
/// target. A crash (OOM, panic, power loss) mid-write can therefore never leave
/// `path` truncated or half-written — a reader sees either the old content or the
/// complete new content, never a torn write. The temp is cleaned up on a write
/// failure. Shared by the persistence layers (vs. a plain `fs::write` overwrite).
/// #35.
///
/// Residuals (tracked in #166): the rename + parent directory are not fsync'd, so
/// after a power loss the file may revert to the OLD complete content (still never
/// torn), and a crash BETWEEN temp-create and rename leaks an orphan `*.tmp.*`
/// (disk litter, not corruption — no sweep yet). Windows replacement is a true
/// `MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH)`, so it has no remove-first gap.
/// Task CAS/transaction paths use [`durable_atomic_write`] below, which also
/// synchronizes the published directory entry.
pub(crate) async fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> {
    use tokio::io::AsyncWriteExt;

    let tmp = path.with_extension(format!("tmp.{}", Uuid::new_v4()));
    let write_result = async {
        let mut file = fs::File::create(&tmp).await?;
        file.write_all(bytes).await?;
        // fsync so the bytes are durable before the rename publishes them.
        file.sync_all().await
    }
    .await;
    if let Err(e) = write_result {
        let _ = fs::remove_file(&tmp).await;
        return Err(e);
    }
    atomic_rename(&tmp, path).await
}

async fn atomic_rename(from: &Path, to: &Path) -> io::Result<()> {
    #[cfg(not(windows))]
    {
        fs::rename(from, to).await
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        use windows_sys::Win32::Storage::FileSystem::{
            MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
        };

        let source: Vec<u16> = from.as_os_str().encode_wide().chain(Some(0)).collect();
        let destination: Vec<u16> = to.as_os_str().encode_wide().chain(Some(0)).collect();
        let result = unsafe {
            MoveFileExW(
                source.as_ptr(),
                destination.as_ptr(),
                MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
            )
        };
        if result == 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

/// Flush the directory entry containing `path` after a create/rename/remove.
/// Unix exposes directory handles through `std`; Windows does not, so Windows
/// transaction renames use `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` above as
/// the strongest portable completion boundary available here.
async fn sync_directory(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        let path = path.to_path_buf();
        tokio::task::spawn_blocking(move || std::fs::File::open(path)?.sync_all())
            .await
            .map_err(|error| other_io_error(format!("join directory sync task: {error}")))?
    }
    #[cfg(windows)]
    {
        let _ = path;
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
        Ok(())
    }
}

async fn sync_parent_directory_entry(path: &Path) -> io::Result<()> {
    let parent = path
        .parent()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
    sync_directory(parent).await
}

async fn durable_copy_file(source: &Path, target: &Path) -> io::Result<u64> {
    let copied = fs::copy(source, target).await?;
    fs::File::open(target).await?.sync_all().await?;
    Ok(copied)
}

/// Transaction-only durable replacement. Unlike ordinary sidecar writes, the
/// temp contents and the published directory entry are both synchronized
/// before this returns. Windows uses a true replace-existing primitive, never
/// the target-loss-prone remove-then-rename fallback.
pub(crate) async fn durable_atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> {
    use tokio::io::AsyncWriteExt;

    let tmp = path.with_extension(format!("durable.tmp.{}", Uuid::new_v4()));
    let write_result = async {
        let mut file = fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&tmp)
            .await?;
        file.write_all(bytes).await?;
        file.sync_all().await
    }
    .await;
    if let Err(error) = write_result {
        let _ = fs::remove_file(&tmp).await;
        return Err(error);
    }
    if let Err(error) = atomic_rename(&tmp, path).await {
        let _ = fs::remove_file(&tmp).await;
        return Err(error);
    }
    sync_parent_directory_entry(path).await
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DurableWritePhase {
    BeforeReplace,
    AfterReplace,
    #[cfg(test)]
    BeforeErrorCleanup,
}

/// Owned authority and Task writes run the complete replacement in one blocking job.
/// Its caller owns the lock holder across temp creation, sync, publication,
/// directory sync and error cleanup; no filesystem subtask can outlive it.
fn durable_atomic_write_blocking(
    path: &Path,
    bytes: &[u8],
    mut publication_hook: impl FnMut(DurableWritePhase) -> io::Result<()>,
) -> io::Result<()> {
    use std::io::Write;

    let tmp = path.with_extension(format!("durable.tmp.{}", Uuid::new_v4()));
    let result = (|| {
        let mut file = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&tmp)?;
        file.write_all(bytes)?;
        file.sync_all()?;
        drop(file);
        publication_hook(DurableWritePhase::BeforeReplace)?;
        #[cfg(not(windows))]
        std::fs::rename(&tmp, path)?;
        #[cfg(windows)]
        {
            use std::os::windows::ffi::OsStrExt;
            use windows_sys::Win32::Storage::FileSystem::{
                MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
            };
            let source: Vec<u16> = tmp.as_os_str().encode_wide().chain(Some(0)).collect();
            let destination: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
            if unsafe {
                MoveFileExW(
                    source.as_ptr(),
                    destination.as_ptr(),
                    MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
                )
            } == 0
            {
                return Err(io::Error::last_os_error());
            }
        }
        publication_hook(DurableWritePhase::AfterReplace)?;
        #[cfg(unix)]
        std::fs::File::open(
            path.parent()
                .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?,
        )?
        .sync_all()?;
        Ok(())
    })();
    if result.is_err() {
        #[cfg(test)]
        let _ = publication_hook(DurableWritePhase::BeforeErrorCleanup);
        let _ = std::fs::remove_file(&tmp);
    }
    result
}

/// Durably remove an active recovery marker without relying on directory
/// unlink persistence. The marker is first renamed to an extension the scanner
/// never treats as active; a resurrected cleanup tombstone is therefore inert.
async fn durable_deactivate_recovery_marker(path: &Path) -> io::Result<()> {
    let tombstone = path.with_extension(format!("removed.{}", Uuid::new_v4()));
    atomic_rename(path, &tombstone).await?;
    sync_parent_directory_entry(&tombstone).await?;

    // Once the rename above is durable, cleanup cannot affect recovery
    // correctness. A power-loss-resurrected tombstone remains non-scannable.
    if fs::remove_file(&tombstone).await.is_ok() {
        let _ = sync_parent_directory_entry(&tombstone).await;
    }
    Ok(())
}

fn parse_data_url_base64(url: &str) -> Option<(String, String)> {
    // data:<mime>;base64,<data...>
    let trimmed = url.trim();
    if !trimmed.starts_with("data:") {
        return None;
    }
    let trimmed = trimmed.strip_prefix("data:")?;
    let (header, data) = trimmed.split_once(',')?;
    if !header.contains(";base64") {
        return None;
    }
    let mime = header.split(';').next()?.trim().to_string();
    Some((mime, data.trim().to_string()))
}

fn mime_to_extension(mime: &str) -> Option<&'static str> {
    match mime.trim().to_ascii_lowercase().as_str() {
        "image/png" => Some("png"),
        "image/jpeg" => Some("jpg"),
        "image/webp" => Some("webp"),
        "image/gif" => Some("gif"),
        "image/bmp" => Some("bmp"),
        _ => None,
    }
}

fn extension_to_mime(ext: &str) -> Option<&'static str> {
    match ext.trim().to_ascii_lowercase().as_str() {
        "png" => Some("image/png"),
        "jpg" | "jpeg" => Some("image/jpeg"),
        "webp" => Some("image/webp"),
        "gif" => Some("image/gif"),
        "bmp" => Some("image/bmp"),
        _ => None,
    }
}

impl SessionStoreV2 {
    pub(crate) async fn load_session_unlocked(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Session>> {
        validate_session_id(session_id)?;
        let Some(path) = self.session_json_path(session_id).await? else {
            self.ensure_no_unindexed_root(session_id).await?;
            return Ok(None);
        };
        if !path.exists() {
            self.ensure_no_unindexed_root(session_id).await?;
            return Ok(None);
        }
        let raw = fs::read_to_string(path).await?;
        compact_main::validate_full_main(raw.as_bytes())?;
        let session: Session = serde_json::from_str(&raw)
            .map_err(|e| other_io_error(format!("invalid session.json: {e}")))?;
        if !self.session_lifetime_is_live(&session).await? {
            return Ok(None);
        }
        let sidecar = self.read_runtime_sidecar(session_id).await?;
        supervisor::validate_overlay(&session, sidecar.as_ref())?;
        self.validate_root_tool_authority_overlay(session_id, &session, sidecar.as_ref())
            .await?;
        let mut session = overlay_runtime_sidecar(session, sidecar);
        // Drop a stale pre-#180 Root token_budget cache so it re-resolves (#230).
        session.clear_stale_root_token_budget();
        Ok(Some(session))
    }
    async fn save_runtime_state_with_owner(
        &self,
        session: &Session,
        owner: Option<&bamboo_domain::storage::RootActorRuntimeWrite>,
        publish: Option<bamboo_domain::storage::RootActorRuntimePublisher>,
    ) -> io::Result<()> {
        self.save_runtime_state_with_owner_and_inherited(session, owner, publish, None)
            .await
            .map(|_| ())
    }

    async fn reconcile_inherited_runtime_snapshot(
        &self,
        session: &Session,
        inherited: &bamboo_domain::InheritedChildWait,
        runtime_only: bool,
    ) -> io::Result<Session> {
        inherited.validate_session(session)?;
        let latest = if runtime_only {
            self.load_runtime_control_plane_unchecked(&session.id)
                .await?
        } else {
            self.load_session_unlocked(&session.id).await?
        }
        .ok_or_else(|| {
            io::Error::other(bamboo_domain::SessionAuthorityConflict(
                "inherited child wait session disappeared".into(),
            ))
        })?;
        let mut reconciled = session.clone();
        crate::session_merge::reconcile_inherited_child_wait(&mut reconciled, &latest, inherited)?;
        Ok(reconciled)
    }

    async fn save_runtime_state_with_owner_and_inherited(
        &self,
        session: &Session,
        owner: Option<&bamboo_domain::storage::RootActorRuntimeWrite>,
        publish: Option<bamboo_domain::storage::RootActorRuntimePublisher>,
        inherited: Option<&bamboo_domain::InheritedChildWait>,
    ) -> io::Result<Option<Session>> {
        // Fast path: write ONLY the small runtime sidecar (no messages), leaving
        // session.json — which carries the full conversation history — untouched.
        // Legacy sessions retain O(1) I/O in conversation length. Initialized
        // Actor protection compares actual durable context, including main birth.
        validate_session_id(&session.id)?;
        let mut rel = self.resolve_rel_path(&session.id).await;
        if rel.is_none() && session.kind == SessionKind::Root {
            // The index is only a hint. Another Store may have created this
            // Root since our index loaded. Keep the existing Root on the
            // runtime path so a context update cannot overwrite its history.
            // Either canonical file is enough to select this path, never to
            // authorize it: the final guard requires the complete valid pair.
            let directory = self.sessions_dir.join(&session.id);
            for file in ["session.json", RUNTIME_SIDECAR_FILE] {
                match fs::symlink_metadata(directory.join(file)).await {
                    Ok(_) => {
                        rel = Some(Self::root_rel_path(&session.id));
                        break;
                    }
                    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                    Err(error) => return Err(error),
                }
            }
        }
        let Some(rel) = rel else {
            // Session was never fully persisted yet — fall back to a full save so
            // session.json and the index get created. Deliberately acquire no
            // shared Task guard before this call: `save_session` owns that
            // boundary, avoiding a same-instance shared-lock re-entry.
            if owner.is_some() || inherited.is_some() {
                return Err(root_actor_runtime::conflict(
                    "Root runtime source is missing",
                ));
            }
            return self.save_session(session).await.map(|_| None);
        };
        let total_started = Instant::now();
        let lifecycle = self.lock_default_writer_lifecycle().await?;
        let runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let session_write = self
            .acquire_session_write_lock(&session.id, SaveKind::Runtime)
            .await?;
        let guards = DefaultWriterGuards::shared_with_root_actor(
            lifecycle,
            runtime_task,
            session_write,
            owner.map(|owner| {
                root_actor_runtime::RootActorWriteProof::new(
                    self.sessions_dir.join(&session.id),
                    owner.clone(),
                )
            }),
        );
        self.save_runtime_state_after_lock(
            session,
            &rel,
            total_started,
            &guards,
            publish,
            inherited,
        )
        .await
    }

    /// Reuse the runtime publication protocol after the caller owns the same
    /// lifecycle, Task and physical Session guards as the ordinary writer.
    async fn save_runtime_state_after_lock(
        &self,
        session: &Session,
        rel: &str,
        total_started: Instant,
        guards: &Arc<DefaultWriterGuards>,
        publish: Option<bamboo_domain::RootActorRuntimePublisher>,
        inherited: Option<&bamboo_domain::InheritedChildWait>,
    ) -> io::Result<Option<Session>> {
        if session
            .metadata
            .contains_key(bamboo_domain::SCOPED_LOOP_UNCERTAIN_KEY)
        {
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "scoped Loop checkpoint outcome is uncertain; strict canonical reload required",
            ));
        }

        let reconciled = match inherited {
            Some(inherited) => Some(
                self.reconcile_inherited_runtime_snapshot(session, inherited, true)
                    .await?,
            ),
            None => None,
        };
        let session = reconciled.as_ref().unwrap_or(session);
        self.check_default_or_root_actor_context(
            session,
            &self.abs_path_from_rel(rel),
            false,
            guards,
        )
        .await?;
        self.validate_authority_for_save(session).await?;
        self.validate_root_context_for_save(session).await?;
        self.validate_child_project_for_write(session, false, Some(rel))
            .await?;
        self.reject_regressing_runtime_task(session).await?;
        if session.kind == SessionKind::Root && self.get_index_entry(&session.id).await.is_none() {
            let index_bytes = fs::read(&self.index_path).await?;
            let global_index: SessionsIndex = serde_json::from_slice(&index_bytes)
                .map_err(|error| other_io_error(format!("invalid sessions index: {error}")))?;
            let globally_indexed = global_index.sessions.get(&session.id).is_some_and(|entry| {
                entry.kind == SessionKind::Root
                    && entry.root_session_id == session.id
                    && entry.rel_path == Self::root_rel_path(&session.id)
            });
            if !globally_indexed {
                // A cold, indexless Root may be damaged. Check its complete pair
                // before publishing even a runtime checkpoint. The established
                // indexed path remains bounded independently of transcript size.
                self.load_authoritative_root_session(&session.id)
                    .await
                    .map_err(|error| {
                        io::Error::new(
                            io::ErrorKind::WouldBlock,
                            bamboo_domain::SessionAuthorityConflict(format!(
                                "Root canonical index recovery unavailable: {error}"
                            )),
                        )
                    })?
                    .ok_or_else(|| {
                        io::Error::new(
                            io::ErrorKind::WouldBlock,
                            bamboo_domain::SessionAuthorityConflict(
                                "Root canonical index recovery is missing".into(),
                            ),
                        )
                    })?;
            }
        }
        let abs_dir = self.abs_path_from_rel(rel);
        let mut stages = SaveStageDurations::default();
        let serialization_started = Instant::now();
        let runtime_snapshot = runtime_sidecar_snapshot(session);
        let runtime_bytes = serde_json::to_vec_pretty(&runtime_snapshot)
            .map_err(|error| other_io_error(error.to_string()))?;
        stages.serialization = serialization_started.elapsed();
        let serialized_bytes = runtime_bytes.len();
        let root_id = if session.kind == SessionKind::Root {
            session.id.as_str()
        } else {
            session.root_session_id.as_str()
        };
        let tree = self.acquire_actor_tree_write_guard(root_id).await?;
        guards.hold_tree(tree);
        let tree_projection_changed = read_actor_tree_session_projection(&abs_dir, session)
            .await
            .as_ref()
            != Some(&actor_tree_session_projection(session));
        if tree_projection_changed {
            let root = if session.kind == SessionKind::Root {
                Some(session.clone())
            } else {
                self.actor_tree_root_for_child_write(root_id).await?
            };
            if let Some(root) = root.as_ref() {
                self.bump_actor_tree_revision(root).await?;
            }
        }
        let filesystem_started = Instant::now();
        self.write_default_bytes(&abs_dir.join(RUNTIME_SIDECAR_FILE), runtime_bytes, guards)
            .await?;
        stages.filesystem_commit = filesystem_started.elapsed();

        // Workspace and Project ownership are part of the list/index API
        // contract. Runtime updates must therefore be reflected without waiting
        // for a later full session save. Avoid rewriting the global index when
        // neither normalized value changed.
        let workspace_path = session
            .workspace_path_meta()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        let project_id = normalized_project_id(session);
        let runtime_index_changed = self.get_index_entry(&session.id).await.is_none_or(|entry| {
            entry.workspace_path != workspace_path || entry.project_id != project_id
        });
        if runtime_index_changed {
            let index_started = Instant::now();
            let index_updated = self
                .update_index(|index| {
                    if let Some(entry) = index.sessions.get_mut(&session.id) {
                        entry.workspace_path = workspace_path;
                        entry.project_id = project_id;
                        return Ok(true);
                    }
                    Ok(false)
                })
                .await?;
            if !index_updated && session.kind == SessionKind::Root {
                // Exceptional recovery of a globally missing index entry must
                // preserve the real history count, not the caller's snapshot.
                // This index recovery reads main too. Legacy runtime saves
                // without Actor authority retain the transcript-independent path.
                let authoritative = self
                    .load_authoritative_root_session(&session.id)
                    .await
                    .map_err(|error| {
                        io::Error::new(
                            io::ErrorKind::WouldBlock,
                            bamboo_domain::SessionAuthorityConflict(format!(
                                "Root canonical index recovery unavailable: {error}"
                            )),
                        )
                    })?
                    .ok_or_else(|| {
                        other_io_error("runtime Root disappeared during index repair")
                    })?;
                self.repair_index_from_authoritative_session(&authoritative, rel.to_string())
                    .await?;
            }
            stages.index_publication = index_started.elapsed();
        }
        let index_entry_count = self.index.read().await.sessions.len();
        let total = total_started.elapsed();
        self.persistence_metrics.record_save(
            SaveKind::Runtime,
            total,
            stages,
            serialized_bytes,
            session.messages.len(),
            index_entry_count,
        );
        tracing::debug!(
            target: "bamboo.session_persistence",
            session_id = %session.id,
            save_type = "runtime",
            phase = "durable_commit",
            serialized_bytes,
            message_count = session.messages.len(),
            index_entry_count,
            total_ms = total.as_millis() as u64,
            "session runtime-state commit completed"
        );
        if let Some(publish) = publish {
            self.publish_root_actor_runtime(guards, publish).await?;
        }
        Ok(reconciled)
    }

    async fn save_session_after_lock(
        &self,
        session: &Session,
        total_started: Instant,
        guards: &Arc<DefaultWriterGuards>,
        answer_permit: Option<&ParentQuestion>,
    ) -> io::Result<()> {
        self.save_session_after_lock_with_title_intent(
            session,
            total_started,
            guards,
            answer_permit,
            false,
        )
        .await
    }

    async fn save_session_after_lock_with_title_intent(
        &self,
        session: &Session,
        total_started: Instant,
        guards: &Arc<DefaultWriterGuards>,
        answer_permit: Option<&ParentQuestion>,
        manual_title: bool,
    ) -> io::Result<()> {
        if session
            .metadata
            .contains_key(bamboo_domain::SCOPED_LOOP_UNCERTAIN_KEY)
        {
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "scoped Loop checkpoint outcome is uncertain; strict canonical reload required",
            ));
        }

        let intended_rel = Self::default_writer_rel_path(session)?;
        self.check_default_or_root_actor_context(
            session,
            &self.abs_path_from_rel(&intended_rel),
            true,
            guards,
        )
        .await?;
        self.validate_authority_for_save(session).await?;
        self.validate_root_context_for_full_save(session).await?;
        self.validate_child_project_for_write(session, true, None)
            .await?;
        self.reject_regressing_runtime_task(session).await?;
        // The per-instance LockedSessionStore mutex cannot close another
        // AppState's load→save window. Check the authoritative transcript while
        // holding V2's cross-process session write lock, before either file is
        // changed, so a stale checkpoint cannot erase a recorded decision.
        // Read only Main: the sidecar is not transcript authority, and a full
        // save must still be able to repair an interrupted creation whose Main
        // is missing.
        let current_main = self.abs_path_from_rel(&intended_rel).join("session.json");
        let previous_main = match fs::read_to_string(&current_main).await {
            Ok(raw) => {
                compact_main::validate_full_main(raw.as_bytes())?;
                let durable: Session = serde_json::from_str(&raw)
                    .map_err(|error| other_io_error(format!("invalid session.json: {error}")))?;
                reject_regressing_direct_parent_terminals(session, &durable)?;
                self.reject_rewriting_broker_receipts(
                    session,
                    &durable,
                    current_main.parent().expect("session.json has a parent"),
                    answer_permit,
                )
                .await?;
                Some(durable)
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                self.reject_broker_receipts_without_main(
                    current_main.parent().expect("session.json has a parent"),
                )
                .await?;
                None
            }
            Err(error) => return Err(error),
        };

        let mut stages = SaveStageDurations::default();
        let serialization_started = Instant::now();
        let session_bytes = compact_main::serialize_main(session)?;
        let runtime_bytes = serde_json::to_vec_pretty(&runtime_sidecar_snapshot(session))
            .map_err(|error| other_io_error(error.to_string()))?;
        stages.serialization = serialization_started.elapsed();
        let serialized_bytes = runtime_bytes.len().saturating_add(session_bytes.len());
        let directory_started = Instant::now();
        let rel_path = self.ensure_default_writer_dirs(session, guards).await?;
        let abs_dir = self.abs_path_from_rel(&rel_path);
        let path = abs_dir.join("session.json");
        stages.directory_preparation = directory_started.elapsed();

        let previous_projection = match &previous_main {
            Some(main) => read_actor_tree_session_projection(&abs_dir, main).await,
            None => None,
        };
        let root_id = if session.kind == SessionKind::Root {
            session.id.as_str()
        } else {
            session.root_session_id.as_str()
        };
        let tree = self.acquire_actor_tree_write_guard(root_id).await?;
        guards.hold_tree(tree);
        let title_observations = if manual_title {
            self.prepare_title_observations(session).await?
        } else {
            Vec::new()
        };
        if previous_projection.as_ref() != Some(&actor_tree_session_projection(session)) {
            let root = if session.kind == SessionKind::Root {
                Some(session.clone())
            } else {
                self.actor_tree_root_for_child_write(root_id).await?
            };
            if let Some(root) = root.as_ref() {
                self.bump_actor_tree_revision(root).await?;
            }
        }

        // Refresh the runtime sidecar BEFORE session.json. If the process
        // crashes between the two writes, the sidecar then carries a
        // control-plane that is at least as fresh as session.json, and the
        // load-time overlay (sidecar wins for non-message fields) stays correct.
        // Writing session.json first could leave a stale sidecar that silently
        // reverts the just-saved control-plane on the next load.
        // Both buffers were preflighted before this publisher prepared directories.

        #[cfg(any(test, feature = "test-utils"))]
        self.maybe_pause_full_save_before_filesystem_commit(&session.id)
            .await;

        let filesystem_started = Instant::now();
        let root_proof_prepared = self
            .prepare_root_tool_proof_for_full_save(&abs_dir, session, guards)
            .await?;
        if root_proof_prepared {
            self.maybe_fail_root_tool_proof(root_context::RootToolProofFault::Prepared)?;
        }
        let supervisor_proof_prepared = self
            .prepare_supervisor_proof_for_full_save(&abs_dir, session, guards)
            .await?;
        if supervisor_proof_prepared {
            self.maybe_fail_supervisor_proof(supervisor_proof::SupervisorProofFault::Prepared)?;
        }
        self.write_default_bytes(&abs_dir.join(RUNTIME_SIDECAR_FILE), runtime_bytes, guards)
            .await?;
        if root_proof_prepared {
            self.maybe_fail_root_tool_proof(root_context::RootToolProofFault::Runtime)?;
        }
        if supervisor_proof_prepared {
            self.maybe_fail_supervisor_proof(supervisor_proof::SupervisorProofFault::Runtime)?;
        }
        self.write_default_bytes(&path, session_bytes, guards)
            .await?;
        if root_proof_prepared {
            self.maybe_fail_root_tool_proof(root_context::RootToolProofFault::Main)?;
        }
        self.commit_root_tool_proof_after_full_save(&abs_dir, session, root_proof_prepared, guards)
            .await?;
        if root_proof_prepared {
            self.maybe_fail_root_tool_proof(root_context::RootToolProofFault::Committed)?;
        }
        self.commit_supervisor_proof_after_full_save(
            &abs_dir,
            session,
            supervisor_proof_prepared,
            guards,
        )
        .await?;
        if supervisor_proof_prepared {
            self.maybe_fail_supervisor_proof(supervisor_proof::SupervisorProofFault::Committed)?;
        }
        // Observations must never lead canonical metadata: an ahead row
        // could conceal a later Project A→B→A revision. A failed refresh
        // remains stale/fail-closed; the manual no-op path validates it too.
        for (path, bytes) in title_observations {
            self.write_default_bytes(&path, bytes, guards).await?;
        }
        let (revision_path, revision) = self
            .publish_default_search_revision(&abs_dir, guards)
            .await?;
        stages.filesystem_commit = filesystem_started.elapsed();

        let index_started = Instant::now();
        self.upsert_index_from_session(session, rel_path).await?;
        stages.index_publication = index_started.elapsed();

        let enqueue_started = Instant::now();
        let search_generation =
            self.search_index_queue
                .enqueue_upsert(session, revision_path, revision);
        stages.search_enqueue = enqueue_started.elapsed();
        let index_entry_count = self.index.read().await.sessions.len();
        let total = total_started.elapsed();
        self.persistence_metrics.record_save(
            SaveKind::Full,
            total,
            stages,
            serialized_bytes,
            session.messages.len(),
            index_entry_count,
        );
        tracing::debug!(
            target: "bamboo.session_persistence",
            session_id = %session.id,
            save_type = "full",
            phase = "durable_commit",
            serialized_bytes,
            message_count = session.messages.len(),
            index_entry_count,
            search_generation,
            total_ms = total.as_millis() as u64,
            "session durable commit completed; search indexing deferred"
        );
        Ok(())
    }
}

#[async_trait::async_trait]
impl Storage for SessionStoreV2 {
    async fn save_manual_title(&self, session: &Session) -> io::Result<()> {
        let total_started = Instant::now();
        let lifecycle = self.lock_default_writer_lifecycle().await?;
        let runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let session_write = self
            .acquire_session_write_lock(&session.id, SaveKind::Full)
            .await?;
        let guards = DefaultWriterGuards::shared(lifecycle, runtime_task, session_write);
        self.save_session_after_lock_with_title_intent(session, total_started, &guards, None, true)
            .await
    }

    async fn validate_title_observations(&self, expected: &Session) -> io::Result<()> {
        self.validate_unchanged_title(expected).await
    }

    fn supports_child_actor_runtime_write(&self) -> bool {
        true
    }

    fn bind_child_actor_inbox(
        &self,
        owner: &bamboo_domain::ChildActorRuntimeWrite,
        inbox: Arc<dyn bamboo_domain::SessionInboxPort>,
    ) -> io::Result<Arc<dyn bamboo_domain::SessionInboxPort>> {
        Ok(Arc::new(self.bound_child_inbox(owner, &inbox)?))
    }

    async fn save_child_actor_runtime(
        &self,
        request: bamboo_domain::ChildActorRuntimeSave<'_>,
    ) -> io::Result<()> {
        self.save_child_actor_runtime_impl(request).await
    }

    async fn publish_child_actor_runtime_event(
        &self,
        owner: &bamboo_domain::ChildActorRuntimeWrite,
        publish: bamboo_domain::RootActorRuntimeEventPublisher,
    ) -> io::Result<()> {
        self.publish_child_actor_runtime_event_impl(owner, publish)
            .await
    }

    fn bind_root_actor_inbox(
        &self,
        owner: &bamboo_domain::RootActorRuntimeWrite,
        inbox: Arc<dyn bamboo_domain::SessionInboxPort>,
    ) -> io::Result<Arc<dyn bamboo_domain::SessionInboxPort>> {
        let inbox = self.bound_root_inbox(owner, &inbox)?;
        Ok(Arc::new(inbox))
    }

    async fn save_root_actor_input(
        &self,
        owner: &bamboo_domain::RootActorRuntimeWrite,
        session: &Session,
        inbox: Arc<dyn bamboo_domain::SessionInboxPort>,
        claim: &bamboo_domain::SessionInboxOwnedClaim,
        publish: bamboo_domain::RootActorRuntimePublisher,
    ) -> io::Result<()> {
        self.save_root_actor_input_impl(owner, &mut session.clone(), inbox, claim, publish, None)
            .await
    }

    async fn load_scoped_loop_session(
        &self,
        binding: &bamboo_domain::ScopedLoopControlBinding,
        activation: Arc<dyn bamboo_domain::SessionActivationPort>,
    ) -> io::Result<Option<Session>> {
        self.load_scoped_loop_session_impl(binding, activation)
            .await
    }

    fn supports_scoped_loop_transport_retirement(&self) -> bool {
        true
    }

    async fn retire_scoped_loop_transport(
        &self,
        request: bamboo_domain::storage::ScopedLoopTransportRetirement<'_>,
    ) -> io::Result<()> {
        self.retire_scoped_loop_transport_impl(request).await
    }

    async fn checkpoint_scoped_loop(
        &self,
        request: bamboo_domain::ScopedLoopControlCheckpoint<'_>,
    ) -> io::Result<()> {
        self.checkpoint_scoped_loop_impl(request).await
    }

    fn supports_root_actor_runtime_write(&self) -> bool {
        true
    }

    async fn publish_root_actor_runtime_event(
        &self,
        owner: &bamboo_domain::RootActorRuntimeWrite,
        publish: bamboo_domain::storage::RootActorRuntimeEventPublisher,
    ) -> io::Result<()> {
        self.publish_root_actor_runtime_event_impl(owner, publish)
            .await
    }

    async fn save_root_actor_runtime(
        &self,
        owner: &bamboo_domain::storage::RootActorRuntimeWrite,
        session: &Session,
        runtime_only: bool,
        publish: bamboo_domain::storage::RootActorRuntimePublisher,
    ) -> io::Result<()> {
        self.save_root_actor_runtime_impl(owner, session, runtime_only, publish)
            .await
    }

    async fn root_mode_operation(
        &self,
        request: &RootModeOperationRequest,
    ) -> io::Result<RootModeOperationDecision> {
        validate_session_id(&request.session_id)?;
        if !bamboo_domain::root_mode_operation_id_matches_epoch(
            &request.operation_id,
            request.expected_epoch,
        ) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Root mode operation_id must be <expected_epoch>:<canonical UUID>",
            ));
        }
        let total_started = Instant::now();
        // Deletion and trusted same-ID recreation hold the exclusive form.
        // Keep one Root birth stable from the authoritative load through the
        // completed operation proof, before taking runtime-task and writer locks.
        let lifecycle = self.lock_session_lifecycle_shared().await?;
        let runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let session_write = self
            .acquire_session_write_lock(&request.session_id, SaveKind::Full)
            .await?;
        let mut guards = DefaultWriterGuards::shared(lifecycle, runtime_task, session_write);
        let Some(mut session) = self.load_session_unlocked(&request.session_id).await? else {
            return Ok(RootModeOperationDecision::NotFound);
        };
        if session.kind != SessionKind::Root || session.parent_session_id.is_some() {
            return Ok(RootModeOperationDecision::NotRoot);
        }
        if session.root_mode_birth_token() != request.birth_token {
            return Ok(RootModeOperationDecision::BirthMismatch);
        }
        if let Some(receipt) = session.root_mode_operation(&request.operation_id) {
            if receipt.expected_epoch != request.expected_epoch
                || receipt.requested_enabled != request.requested_enabled
            {
                return Ok(RootModeOperationDecision::OperationConflict);
            }
            return Ok(RootModeOperationDecision::Terminal(receipt.clone()));
        }
        if request.expected_epoch > session.root_mode_transition_epoch {
            return Ok(RootModeOperationDecision::FutureEpoch);
        }
        if request.expected_epoch < session.root_mode_transition_epoch {
            return Ok(RootModeOperationDecision::FencedBySuccessor {
                operation_id: request.operation_id.clone(),
                expected_epoch: request.expected_epoch,
                current_epoch: session.root_mode_transition_epoch,
                current_enabled: session.root_orchestration_only_enabled(),
                current_tool_revision: session.root_tool_authority_revision,
            });
        }

        let original = session.clone();
        let outcome = match request.action {
            RootModeOperationAction::Recover => RootModeOperationOutcome::Fenced,
            RootModeOperationAction::Select => {
                let mut candidate = session.clone();
                let compatible =
                    match candidate.set_root_orchestration_only(request.requested_enabled) {
                        Ok(()) => true,
                        Err(RootToolAuthorityError::LegacyPlanActive)
                        | Err(RootToolAuthorityError::WorkflowSelected) => false,
                        Err(error) => return Err(other_io_error(error.to_string())),
                    } && (!request.requested_enabled || {
                        let pending = candidate
                            .metadata
                            .contains_key(bamboo_skills::WORKFLOW_SELECTION_METADATA_KEY);
                        let active = candidate
                            .metadata
                            .get(bamboo_skills::ACTIVE_WORKFLOW_METADATA_KEY)
                            .is_some_and(|raw| {
                                serde_json::from_str::<bamboo_skills::ActiveWorkflow>(raw)
                                    .map(|workflow| {
                                        workflow.status
                                            != bamboo_skills::WorkflowActivationStatus::Deactivated
                                    })
                                    .unwrap_or(true)
                            });
                        !pending && !active
                    });
                if compatible {
                    session = candidate;
                    RootModeOperationOutcome::Committed
                } else {
                    RootModeOperationOutcome::RejectedIncompatible
                }
            }
        };
        let receipt = RootModeOperationReceipt {
            operation_id: request.operation_id.clone(),
            expected_epoch: request.expected_epoch,
            resulting_epoch: 0,
            requested_enabled: request.requested_enabled,
            enabled_at_completion: false,
            tool_authority_revision: 0,
            outcome,
        };
        session
            .record_root_mode_operation(receipt)
            .map_err(|error| other_io_error(error.to_string()))?;
        // A pending ledger reset may coalesce across a quick mode round trip,
        // while the native transcript still invalidates on each selection.
        if session.authority_identity.is_ordinary()
            && (session.model_context_state != original.model_context_state
                || session.provider_transcript != original.provider_transcript)
        {
            let directory = self.sessions_dir.join(&session.id);
            let candidate = session.clone();
            let proof = Self::default_writer_job(&guards, move || {
                root_context::RootModeContextWrite::capture(directory, &original, &candidate)
            })
            .await?;
            Arc::get_mut(&mut guards)
                .expect("Root mode writer owns its acquired guards")
                .root_mode_context = Some(proof);
        }
        self.save_session_after_lock(&session, total_started, &guards, None)
            .await?;
        Ok(RootModeOperationDecision::Terminal(
            session
                .root_mode_operation(&request.operation_id)
                .expect("just-recorded terminal Root mode operation")
                .clone(),
        ))
    }

    async fn recreate_root_session(
        &self,
        session_id: &str,
        initial_model: &str,
    ) -> io::Result<Session> {
        self.recreate_ordinary_root(session_id, initial_model).await
    }

    async fn get_or_create_default_supervisor(
        &self,
        initial_model: &str,
    ) -> io::Result<SupervisorBootstrapReceipt> {
        self.bootstrap_default_supervisor(initial_model).await
    }

    async fn with_supervisor_orchestration_authority(
        &self,
        supervisor: &bamboo_domain::SupervisorReference,
        expected_revision: u64,
        operation: Box<dyn FnOnce() -> io::Result<()> + Send>,
    ) -> io::Result<()> {
        self.supervisor_orchestration_job(supervisor, expected_revision, operation)
            .await
    }

    async fn load_root_authority(&self, session_id: &str) -> io::Result<Option<Session>> {
        let _lifecycle = self.lock_session_lifecycle_shared().await?;
        let _task = self.lock_runtime_task_sidecar_shared().await?;
        let _session = self.acquire_session_maintenance_lock(session_id).await?;
        self.load_root_authority_unchecked(session_id).await
    }

    async fn inspect_supervisor_scope(
        &self,
        supervisor: &bamboo_domain::SupervisorReference,
    ) -> io::Result<bamboo_domain::SupervisorScopeObservation> {
        self.management_scope(supervisor).await
    }

    async fn mutate_supervisor_management(
        &self,
        request: &bamboo_domain::SupervisorManagementRequest,
    ) -> io::Result<bamboo_domain::SupervisorManagementReceipt> {
        self.management_mutate(request).await
    }

    async fn inspect_supervisor_link(
        &self,
        supervisor: &bamboo_domain::SupervisorReference,
        target_session_id: &str,
    ) -> io::Result<bamboo_domain::SupervisorLinkObservation> {
        self.management_link(supervisor, target_session_id).await
    }

    async fn load_supervisor_managed_session(
        &self,
        supervisor: &bamboo_domain::SupervisorReference,
        target_session_id: &str,
    ) -> io::Result<Option<Session>> {
        self.management_history(supervisor, target_session_id).await
    }

    async fn save_session(&self, session: &Session) -> io::Result<()> {
        let total_started = Instant::now();
        let lifecycle = self.lock_default_writer_lifecycle().await?;
        let runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let session_write = self
            .acquire_session_write_lock(&session.id, SaveKind::Full)
            .await?;
        let guards = DefaultWriterGuards::shared(lifecycle, runtime_task, session_write);
        self.save_session_after_lock(session, total_started, &guards, None)
            .await
    }

    async fn save_inherited_child_wait_finalized(
        &self,
        session: &mut Session,
        inherited: &bamboo_domain::session::runtime_state::WaitingForChildrenState,
        root_writer: Option<(
            bamboo_domain::RootActorRuntimeWrite,
            bamboo_domain::RootActorRuntimePublisher,
        )>,
    ) -> io::Result<()> {
        let started = Instant::now();
        validate_session_id(&session.id)?;
        let lifecycle = self.lock_default_writer_lifecycle().await?;
        let task = self.lock_runtime_task_sidecar_shared().await?;
        let session_write = self
            .acquire_session_write_lock(&session.id, SaveKind::Full)
            .await?;
        let proof = root_writer.as_ref().map(|(owner, _)| {
            root_actor_runtime::RootActorWriteProof::new(
                self.sessions_dir.join(&session.id),
                owner.clone(),
            )
        });
        let guards =
            DefaultWriterGuards::shared_with_root_actor(lifecycle, task, session_write, proof);
        let latest = self
            .load_session_unlocked(&session.id)
            .await?
            .filter(|latest| latest.created_at == session.created_at)
            .ok_or_else(|| {
                io::Error::other(bamboo_domain::SessionAuthorityConflict(
                    "inherited child wait session disappeared or changed birth".into(),
                ))
            })?;
        let mut reconciled = session.clone();
        if reconciled
            .agent_runtime_state
            .as_ref()
            .and_then(|state| state.waiting_for_children.as_ref())
            == Some(inherited)
        {
            crate::session_merge::adopt_finalized_child_wait(&mut reconciled, &latest, true);
        }
        self.save_session_after_lock(&reconciled, started, &guards, None)
            .await?;
        if let Some((_, publish)) = root_writer {
            self.publish_root_actor_runtime(&guards, publish).await?;
        }
        *session = reconciled;
        Ok(())
    }

    async fn save_runtime_with_inherited_child_wait(
        &self,
        session: &mut Session,
        inherited: &bamboo_domain::InheritedChildWait,
        runtime_only: bool,
        root_writer: Option<(
            bamboo_domain::RootActorRuntimeWrite,
            bamboo_domain::RootActorRuntimePublisher,
        )>,
        input: Option<(
            Arc<dyn bamboo_domain::SessionInboxPort>,
            bamboo_domain::SessionInboxOwnedClaim,
        )>,
    ) -> io::Result<()> {
        inherited.validate_session(session)?;
        if let Some((inbox, claim)) = input {
            if runtime_only {
                return Err(io::Error::other("Root input requires a full checkpoint"));
            }
            let (owner, publish) = root_writer
                .ok_or_else(|| io::Error::other("Root input checkpoint requires a bound writer"))?;
            return self
                .save_root_actor_input_impl(
                    &owner,
                    session,
                    inbox,
                    &claim,
                    publish,
                    Some(inherited),
                )
                .await;
        }
        if runtime_only {
            let (owner, publish) = match root_writer.as_ref() {
                Some((owner, publish)) => (Some(owner), Some(publish.clone())),
                None => (None, None),
            };
            let reconciled = self
                .save_runtime_state_with_owner_and_inherited(
                    session,
                    owner,
                    publish,
                    Some(inherited),
                )
                .await?;
            *session = reconciled.expect("inherited runtime writer reconciled its snapshot");
            return Ok(());
        }
        let started = Instant::now();
        validate_session_id(&session.id)?;
        let lifecycle = self.lock_default_writer_lifecycle().await?;
        let task = self.lock_runtime_task_sidecar_shared().await?;
        let session_write = self
            .acquire_session_write_lock(&session.id, SaveKind::Full)
            .await?;
        let proof = root_writer.as_ref().map(|(owner, _)| {
            root_actor_runtime::RootActorWriteProof::new(
                self.sessions_dir.join(&session.id),
                owner.clone(),
            )
        });
        let guards =
            DefaultWriterGuards::shared_with_root_actor(lifecycle, task, session_write, proof);
        let reconciled = self
            .reconcile_inherited_runtime_snapshot(session, inherited, false)
            .await?;
        self.save_session_after_lock(&reconciled, started, &guards, None)
            .await?;
        if let Some((_, publish)) = root_writer {
            self.publish_root_actor_runtime(&guards, publish).await?;
        }
        *session = reconciled;
        Ok(())
    }

    async fn load_session(&self, session_id: &str) -> io::Result<Option<Session>> {
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        self.load_session_unlocked(session_id).await
    }

    async fn load_execution_admission_snapshot(
        &self,
        session_id: &str,
    ) -> io::Result<Option<Session>> {
        validate_session_id(session_id)?;
        let _lifecycle = self.lock_session_lifecycle_shared().await?;
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        let _session = self.acquire_session_maintenance_lock(session_id).await?;
        self.load_execution_admission_unchecked(session_id).await
    }

    async fn delete_session(&self, session_id: &str) -> io::Result<bool> {
        // Historical API deletes sessions. In V2, treat this as recursive and forced.
        self.delete_session_recursive(session_id, true).await
    }

    async fn save_runtime_state(&self, session: &Session) -> io::Result<()> {
        self.save_runtime_state_with_owner(session, None, None)
            .await
    }

    async fn load_runtime_control_plane(&self, session_id: &str) -> io::Result<Option<Session>> {
        let _runtime_task = self.lock_runtime_task_sidecar_shared().await?;
        self.load_runtime_control_plane_unchecked(session_id).await
    }

    async fn recover_task_control_plane_transaction(
        &self,
        first_session_id: &str,
        second_session_id: &str,
    ) -> io::Result<()> {
        let _guard = self.lock_runtime_task_transaction_exclusive().await?;
        self.recover_runtime_task_transaction_for_pair_locked(
            first_session_id,
            second_session_id,
            &_guard,
        )
        .await
    }

    async fn save_task_control_plane_if_matches(
        &self,
        original: &Session,
        updated: &Session,
    ) -> io::Result<bool> {
        let _guard = self.lock_runtime_task_transaction_exclusive().await?;
        self.recover_all_runtime_task_transactions_locked(&_guard)
            .await?;
        self.save_runtime_task_control_plane_if_matches(original, updated, &_guard)
            .await
    }

    async fn save_task_control_planes_atomically(
        &self,
        first_original: &Session,
        first_updated: &Session,
        second_original: &Session,
        second_updated: &Session,
    ) -> io::Result<bool> {
        let _guard = self.lock_runtime_task_transaction_exclusive().await?;
        self.recover_runtime_task_transaction_for_pair_locked(
            &first_original.id,
            &second_original.id,
            &_guard,
        )
        .await?;
        self.save_runtime_task_pair_transaction(
            first_original,
            first_updated,
            second_original,
            second_updated,
            &_guard,
        )
        .await
    }

    async fn load_child_wait_session(
        &self,
        parent: &Session,
        child_id: &str,
        full: bool,
    ) -> io::Result<Option<Session>> {
        let _task = self.lock_runtime_task_sidecar_shared().await?;
        SessionStoreV2::load_child_wait_session(self, parent, child_id, full).await
    }

    fn supports_atomic_child_wait_control_plane(&self) -> bool {
        true
    }

    async fn register_child_wait_control_plane(
        &self,
        expected: &Session,
        batch: &[(String, Option<String>)],
        policy: bamboo_domain::ChildWaitPolicy,
        check_terminal: bool,
        publish: bamboo_domain::RootActorRuntimePublisher,
    ) -> io::Result<(Session, usize)> {
        self.register_child_wait(expected, batch, policy, check_terminal, publish)
            .await
    }

    async fn compare_exchange_child_wait_control_plane(
        &self,
        expected: &Session,
        updated: &mut Session,
        runtime_only: bool,
        publish: bamboo_domain::RootActorRuntimePublisher,
    ) -> io::Result<bool> {
        self.compare_exchange_child_wait(expected, updated, runtime_only, publish)
            .await
    }

    async fn list_child_run_statuses(
        &self,
        parent_session_id: &str,
    ) -> io::Result<Vec<(String, Option<String>)>> {
        let index = self.index.read().await;
        Ok(index
            .sessions
            .values()
            .filter(|entry| {
                entry.kind == SessionKind::Child
                    && entry.parent_session_id.as_deref() == Some(parent_session_id)
            })
            .map(|entry| (entry.id.clone(), entry.last_run_status.clone()))
            .collect())
    }

    async fn list_sessions_by_run_status(
        &self,
        status: &str,
    ) -> io::Result<Vec<(String, Option<String>)>> {
        let index = self.index.read().await;
        Ok(index
            .sessions
            .values()
            .filter(|entry| entry.last_run_status.as_deref() == Some(status))
            .map(|entry| (entry.id.clone(), entry.parent_session_id.clone()))
            .collect())
    }

    async fn append_token_usage_record(&self, session_id: &str, json_line: &str) -> io::Result<()> {
        use tokio::io::AsyncWriteExt;

        validate_session_id(session_id)?;
        // Resolve the session's own directory. If it isn't indexed yet (no
        // initial save has happened), skip silently — this is an analysis
        // sidecar, never authoritative state.
        let Some(rel) = self.resolve_rel_path(session_id).await else {
            return Ok(());
        };
        let path = self.abs_path_from_rel(&rel).join(TOKEN_USAGE_FILE);

        // Exactly one line per record, regardless of how the caller framed it.
        let mut line = json_line.trim_end_matches('\n').to_string();
        line.push('\n');

        let mut file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
            .await?;
        file.write_all(line.as_bytes()).await?;
        // `flush` is LOAD-BEARING, not cosmetic (issues #378/#486):
        // `tokio::fs::File::write_all` only copies the bytes into the File's
        // internal buffer and schedules the actual OS write on the blocking
        // thread pool — it does NOT wait for it. Dropping the File does not
        // wait either (the write still happens "eventually" on the pool, and
        // any error is silently discarded). So without this flush a caller
        // that appends and then promptly reads the file back — exactly what
        // `append_token_usage_record_writes_jsonl_in_session_dir` does — can
        // observe the file BEFORE a still-in-flight append lands, which on a
        // loaded CI runner (saturated blocking pool) manifested as the
        // one-off "1 line instead of 2 / lost second append" failure.
        // `flush().await` drives the pending background write to completion
        // (and surfaces its error) before we return.
        file.flush().await?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl AttachmentReader for SessionStoreV2 {
    async fn read_attachment(
        &self,
        session_id: &str,
        attachment_id: &str,
    ) -> io::Result<Option<(Vec<u8>, String)>> {
        SessionStoreV2::read_attachment(self, session_id, attachment_id).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bamboo_domain::{
        ImageOcrResult, ImageUrlRef, Message, MessagePart, SessionInboxError, SessionInboxPort,
        SessionMessageEnvelope, TaskItem, TaskItemStatus,
    };
    use std::io;
    use std::sync::Arc;
    use tempfile::TempDir;

    async fn create_temp_storage() -> io::Result<(SessionStoreV2, TempDir)> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let storage = SessionStoreV2::new(bamboo_home).await?;
        Ok((storage, temp_dir))
    }

    #[tokio::test]
    async fn stale_second_store_cannot_erase_clarification_terminal() -> io::Result<()> {
        use bamboo_domain::{FunctionCall, PendingQuestionSource, ToolCall};

        let (first, home) = create_temp_storage().await?;
        let mut parent = Session::new("clarification-terminal-parent", "model");
        let mut child =
            Session::new_child_of("clarification-terminal-child", &parent, "model", "Child");
        child.add_message(Message::assistant(
            "",
            Some(vec![ToolCall {
                id: "clarification-call".into(),
                tool_type: "function".into(),
                function: FunctionCall {
                    name: "AskUserQuestion".into(),
                    arguments: "{}".into(),
                },
            }]),
        ));
        child.add_message(Message::tool_result_with_status(
            "clarification-call",
            "Clarification needed: Which option?",
            true,
        ));
        child.set_pending_question_with_source(
            "clarification-call".into(),
            "AskUserQuestion".into(),
            "Which option?".into(),
            vec!["A".into(), "B".into()],
            true,
            PendingQuestionSource::DirectParent,
        );
        child.metadata.insert(
            "runtime.suspend_reason".into(),
            "awaiting_clarification".into(),
        );
        let question = ParentQuestion::issue_at(&parent, &child, Utc::now()).unwrap();
        parent.add_message(question.envelope().to_provider_message().unwrap());
        first.save_session(&parent).await?;

        let second = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let stale = second.load_session(&parent.id).await?.unwrap();
        let resolution = ParentQuestionResolution::answered(
            &question,
            question.issued_at + chrono::Duration::milliseconds(1),
            "A",
        )
        .unwrap();
        let terminal = resolution.terminal_envelope().unwrap();
        assert_eq!(
            ParentQuestionResolution::from_terminal(&question.envelope(), &terminal),
            Some(resolution)
        );
        parent.add_message(terminal.to_provider_message().unwrap());
        first.save_session(&parent).await?;

        let error = second.save_session(&stale).await.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
        assert!(error
            .get_ref()
            .is_some_and(|cause| cause.is::<DirectParentTerminalConflict>()));
        let retained = first.load_session(&parent.id).await?.unwrap();
        assert_eq!(
            serde_json::to_value(retained.messages).unwrap(),
            serde_json::to_value(parent.messages).unwrap()
        );
        Ok(())
    }

    pub(super) fn transaction_task_list(root_id: &str, title: &str) -> TaskList {
        let now = Utc::now();
        TaskList {
            session_id: root_id.to_string(),
            title: title.to_string(),
            items: vec![TaskItem {
                id: "task-1".to_string(),
                description: format!("{title} work"),
                status: TaskItemStatus::InProgress,
                ..TaskItem::default()
            }],
            created_at: now,
            updated_at: now,
        }
    }

    pub(super) async fn seed_runtime_task_transaction_pair(
        storage: &SessionStoreV2,
    ) -> io::Result<(Session, Session, Session, Session)> {
        let root_id = "tx-root";
        let child_id = "tx-child";

        let mut root = Session::new(root_id, "model");
        root.add_message(Message::user("root transcript secret"));
        root.metadata.insert(
            "unrelated.root".to_string(),
            "root metadata secret".to_string(),
        );
        root.set_task_list(transaction_task_list(root_id, "original root"));
        root.set_task_list_version_meta("1");
        storage.save_session(&root).await?;

        let mut child = Session::new_child_of(child_id, &root, "model", "child");
        child.add_message(Message::user("child transcript secret"));
        child.metadata.insert(
            "unrelated.child".to_string(),
            "child metadata secret".to_string(),
        );
        child.set_task_list(transaction_task_list(root_id, "original child"));
        child.set_task_list_version_meta("1");
        storage.save_session(&child).await?;

        let child_original = storage
            .load_runtime_control_plane(child_id)
            .await?
            .expect("child control plane");
        let root_original = storage
            .load_runtime_control_plane(root_id)
            .await?
            .expect("root control plane");
        let evaluated = transaction_task_list(root_id, "evaluated");
        let mut child_updated = child_original.clone();
        child_updated.task_list = Some(evaluated.clone());
        child_updated.set_task_list_version_meta("2");
        let mut root_updated = root_original.clone();
        root_updated.task_list = Some(evaluated);
        root_updated.set_task_list_version_meta("2");

        // child < root lexically, matching the Storage transaction contract.
        Ok((child_original, child_updated, root_original, root_updated))
    }

    async fn assert_original_runtime_task_pair(storage: &SessionStoreV2) -> io::Result<()> {
        let child = storage
            .load_session("tx-child")
            .await?
            .expect("child remains");
        let root = storage
            .load_session("tx-root")
            .await?
            .expect("root remains");
        for (session, title, transcript, metadata_key, metadata_value) in [
            (
                &child,
                "original child",
                "child transcript secret",
                "unrelated.child",
                "child metadata secret",
            ),
            (
                &root,
                "original root",
                "root transcript secret",
                "unrelated.root",
                "root metadata secret",
            ),
        ] {
            assert_eq!(session.task_list_version_meta().as_deref(), Some("1"));
            assert_eq!(
                session.task_list.as_ref().map(|list| list.title.as_str()),
                Some(title)
            );
            assert_eq!(session.messages.len(), 1);
            assert_eq!(session.messages[0].content, transcript);
            assert_eq!(
                session.metadata.get(metadata_key).map(String::as_str),
                Some(metadata_value)
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn paired_task_success_records_durable_publish_order() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        assert!(storage.take_runtime_task_durability_events().is_empty());

        assert!(
            storage
                .save_task_control_planes_atomically(
                    &child_original,
                    &child_updated,
                    &root_original,
                    &root_updated,
                )
                .await?
        );
        assert_eq!(
            storage.take_runtime_task_durability_events(),
            vec![
                RuntimeTaskDurabilityEvent::JournalPublished,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                RuntimeTaskDurabilityEvent::SecondUpdatedSidecarPublished,
                RuntimeTaskDurabilityEvent::JournalDeactivated,
            ]
        );
        Ok(())
    }

    #[tokio::test]
    async fn paired_task_second_write_failure_rolls_back_both_originals() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        assert!(storage.take_runtime_task_durability_events().is_empty());
        storage
            .inject_runtime_task_transaction_fault(RuntimeTaskTransactionFault::SecondUpdatedWrite);

        let error = storage
            .save_task_control_planes_atomically(
                &child_original,
                &child_updated,
                &root_original,
                &root_updated,
            )
            .await
            .expect_err("second write must fail");
        assert!(error.to_string().contains("rolled back"), "{error}");
        assert_original_runtime_task_pair(&storage).await?;
        assert!(storage.runtime_task_journal_paths().await?.is_empty());
        assert_eq!(
            storage.take_runtime_task_durability_events(),
            vec![
                RuntimeTaskDurabilityEvent::JournalPublished,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                RuntimeTaskDurabilityEvent::FirstRollbackSidecarPublished,
                RuntimeTaskDurabilityEvent::SecondRollbackSidecarPublished,
                RuntimeTaskDurabilityEvent::JournalDeactivated,
            ]
        );
        Ok(())
    }

    #[tokio::test]
    async fn paired_task_commit_marker_removal_failure_rolls_back_before_error() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        storage.inject_runtime_task_transaction_fault(RuntimeTaskTransactionFault::JournalRemove);

        let error = storage
            .save_task_control_planes_atomically(
                &child_original,
                &child_updated,
                &root_original,
                &root_updated,
            )
            .await
            .expect_err("journal removal failure cannot publish success");
        assert!(error.to_string().contains("rolled back"), "{error}");
        assert_original_runtime_task_pair(&storage).await?;
        assert!(storage.runtime_task_journal_paths().await?.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn paired_task_rollback_failure_retains_journal_and_fails_closed_until_recovery(
    ) -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        storage
            .inject_runtime_task_transaction_fault(RuntimeTaskTransactionFault::SecondUpdatedWrite);
        storage
            .inject_runtime_task_transaction_fault(RuntimeTaskTransactionFault::FirstRollbackWrite);

        let error = storage
            .save_task_control_planes_atomically(
                &child_original,
                &child_updated,
                &root_original,
                &root_updated,
            )
            .await
            .expect_err("rollback failure must surface");
        assert!(error.to_string().contains("recovery required"), "{error}");
        assert_eq!(storage.runtime_task_journal_paths().await?.len(), 1);
        assert!(
            storage.load_session("tx-child").await.is_err(),
            "ordinary access must fail closed while an undo journal remains"
        );

        storage
            .recover_task_control_plane_transaction("tx-child", "tx-root")
            .await?;
        assert_original_runtime_task_pair(&storage).await?;
        assert!(storage.runtime_task_journal_paths().await?.is_empty());
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn independent_store_sidecar_access_and_constructor_wait_for_live_pair_commit(
    ) -> io::Result<()> {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let home = temp.path().to_path_buf();
        let first_store = Arc::new(SessionStoreV2::new(home.clone()).await?);
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&first_store).await?;
        // This store starts with its own recovery flag clear. Correctness must
        // therefore come from the shared file lock + durable journal check.
        let second_store = Arc::new(SessionStoreV2::new(home.clone()).await?);

        let (first_write_reached, release_first_write) =
            first_store.pause_runtime_task_transaction_after_first_write();
        let commit_store = first_store.clone();
        let commit_child_original = child_original.clone();
        let commit_child_updated = child_updated.clone();
        let commit_root_original = root_original.clone();
        let commit_root_updated = root_updated.clone();
        let commit = tokio::spawn(async move {
            commit_store
                .save_task_control_planes_atomically(
                    &commit_child_original,
                    &commit_child_updated,
                    &commit_root_original,
                    &commit_root_updated,
                )
                .await
        });
        first_write_reached.wait().await;
        assert_eq!(first_store.runtime_task_journal_paths().await?.len(), 1);

        let load_store = second_store.clone();
        let mut full_load = tokio::spawn(async move { load_store.load_session("tx-child").await });
        let control_store = second_store.clone();
        let mut control_load =
            tokio::spawn(async move { control_store.load_runtime_control_plane("tx-root").await });
        let save_store = second_store.clone();
        // Queue an actually stale v1 writer. Once the shared lock is granted it
        // must fail before writing rather than silently substitute the durable
        // v2 Task fields while reporting the caller's v1 snapshot as saved.
        let mut save_snapshot = child_original.clone();
        save_snapshot
            .metadata
            .insert("independent.writer".to_string(), "preserved".to_string());
        let mut runtime_save =
            tokio::spawn(async move { save_store.save_runtime_state(&save_snapshot).await });
        let full_save_store = second_store.clone();
        let mut full_save_snapshot = root_original.clone();
        full_save_snapshot.metadata.insert(
            "independent.full-writer".to_string(),
            "preserved".to_string(),
        );
        let mut full_save =
            tokio::spawn(async move { full_save_store.save_session(&full_save_snapshot).await });
        let constructor_home = home.clone();
        let mut constructor =
            tokio::spawn(async move { SessionStoreV2::new(constructor_home).await });

        let blocked_for = std::time::Duration::from_millis(100);
        assert!(
            tokio::time::timeout(blocked_for, &mut full_load)
                .await
                .is_err(),
            "full load must not observe the first published sidecar"
        );
        assert!(
            tokio::time::timeout(blocked_for, &mut control_load)
                .await
                .is_err(),
            "control-plane load must not observe the first published sidecar"
        );
        assert!(
            tokio::time::timeout(blocked_for, &mut runtime_save)
                .await
                .is_err(),
            "runtime save must not overwrite a half-published transaction"
        );
        assert!(
            tokio::time::timeout(blocked_for, &mut full_save)
                .await
                .is_err(),
            "full save must not overwrite a half-published transaction"
        );
        assert!(
            tokio::time::timeout(blocked_for, &mut constructor)
                .await
                .is_err(),
            "a second constructor must not recover another store's live journal"
        );

        release_first_write.wait().await;
        assert!(commit.await.map_err(io::Error::other)??);

        let full = full_load
            .await
            .map_err(io::Error::other)??
            .expect("child remains");
        let control = control_load
            .await
            .map_err(io::Error::other)??
            .expect("root remains");
        let runtime_error = runtime_save
            .await
            .map_err(io::Error::other)?
            .expect_err("stale runtime save must report a Task conflict");
        assert_eq!(runtime_error.kind(), io::ErrorKind::WouldBlock);
        let full_save_error = full_save
            .await
            .map_err(io::Error::other)?
            .expect_err("stale full save must report a Task conflict");
        assert_eq!(full_save_error.kind(), io::ErrorKind::WouldBlock);
        let constructed = constructor.await.map_err(io::Error::other)??;
        for session in [&full, &control] {
            assert_eq!(session.task_list_version_meta().as_deref(), Some("2"));
            assert_eq!(
                session.task_list.as_ref().map(|list| list.title.as_str()),
                Some("evaluated")
            );
        }
        for storage in [second_store.as_ref(), &constructed] {
            let child = storage.load_session("tx-child").await?.expect("child");
            let root = storage.load_session("tx-root").await?.expect("root");
            for session in [&child, &root] {
                assert_eq!(session.task_list_version_meta().as_deref(), Some("2"));
                assert_eq!(
                    session.task_list.as_ref().map(|list| list.title.as_str()),
                    Some("evaluated")
                );
            }
            assert!(!child.metadata.contains_key("independent.writer"));
            assert!(!root.metadata.contains_key("independent.full-writer"));
        }
        assert!(first_store.runtime_task_journal_paths().await?.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn paired_task_commit_rebases_on_current_non_task_control_plane() -> io::Result<()> {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let home = temp.path().to_path_buf();
        let first_store = SessionStoreV2::new(home.clone()).await?;
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&first_store).await?;
        let second_store = SessionStoreV2::new(home).await?;

        let mut current_child = second_store
            .load_runtime_control_plane("tx-child")
            .await?
            .expect("child");
        current_child.metadata.insert(
            "concurrent.child.status".to_string(),
            "must survive".to_string(),
        );
        second_store.save_runtime_state(&current_child).await?;
        let mut current_root = second_store
            .load_runtime_control_plane("tx-root")
            .await?
            .expect("root");
        current_root.metadata.insert(
            "concurrent.root.round".to_string(),
            "must survive".to_string(),
        );
        second_store.save_runtime_state(&current_root).await?;

        assert!(
            first_store
                .save_task_control_planes_atomically(
                    &child_original,
                    &child_updated,
                    &root_original,
                    &root_updated,
                )
                .await?,
            "Task-owned originals still match, so the narrow CAS should commit"
        );
        let child = first_store.load_session("tx-child").await?.expect("child");
        let root = first_store.load_session("tx-root").await?.expect("root");
        for session in [&child, &root] {
            assert_eq!(session.task_list_version_meta().as_deref(), Some("2"));
            assert_eq!(
                session.task_list.as_ref().map(|list| list.title.as_str()),
                Some("evaluated")
            );
        }
        assert_eq!(
            child
                .metadata
                .get("concurrent.child.status")
                .map(String::as_str),
            Some("must survive")
        );
        assert_eq!(
            root.metadata
                .get("concurrent.root.round")
                .map(String::as_str),
            Some("must survive")
        );
        Ok(())
    }

    #[tokio::test]
    async fn paired_task_cas_accepts_legacy_only_generation_metadata() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let root_id = "legacy-task-root";
        let child_id = "legacy-task-child";
        let generation_key =
            bamboo_domain::session::runtime_metadata::keys::TASK_LIST_VERSION.to_string();
        let mut root = Session::new(root_id, "model");
        root.task_list = Some(transaction_task_list(root_id, "legacy root"));
        root.metadata
            .insert(generation_key.clone(), "1".to_string());
        assert!(root.runtime_metadata.is_none());
        storage.save_session(&root).await?;
        let mut child = Session::new_child(child_id, root_id, "model", "child");
        child.task_list = Some(transaction_task_list(root_id, "legacy child"));
        child.metadata.insert(generation_key, "1".to_string());
        assert!(child.runtime_metadata.is_none());
        storage.save_session(&child).await?;

        let child_original = storage
            .load_runtime_control_plane(child_id)
            .await?
            .expect("child");
        let root_original = storage
            .load_runtime_control_plane(root_id)
            .await?
            .expect("root");
        assert!(child_original.runtime_metadata.is_none());
        assert!(root_original.runtime_metadata.is_none());
        let evaluated = transaction_task_list(root_id, "legacy evaluated");
        let mut child_updated = child_original.clone();
        child_updated.task_list = Some(evaluated.clone());
        child_updated.set_task_list_version_meta("2");
        let mut root_updated = root_original.clone();
        root_updated.task_list = Some(evaluated);
        root_updated.set_task_list_version_meta("2");

        assert!(
            storage
                .save_task_control_planes_atomically(
                    &child_original,
                    &child_updated,
                    &root_original,
                    &root_updated,
                )
                .await?,
            "typed setter normalization must not look like a non-Task mutation"
        );
        for id in [child_id, root_id] {
            let session = storage.load_session(id).await?.expect("session");
            assert_eq!(session.task_list_version_meta().as_deref(), Some("2"));
            assert_eq!(
                session.task_list.as_ref().map(|list| list.title.as_str()),
                Some("legacy evaluated")
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn ordinary_task_save_accepts_newer_generation_and_rejects_same_generation_divergence(
    ) -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let mut initial = Session::new("ordinary-task-rebase", "model");
        initial.set_task_list(transaction_task_list(&initial.id, "generation one"));
        initial.set_task_list_version_meta("1");
        storage.save_session(&initial).await?;

        let mut newer = initial.clone();
        newer.set_task_list(transaction_task_list(&newer.id, "generation two"));
        newer.set_task_list_version_meta("2");
        storage.save_runtime_state(&newer).await?;
        let durable_newer = storage
            .load_session(&newer.id)
            .await?
            .expect("newer session");
        assert_eq!(
            durable_newer
                .task_list
                .as_ref()
                .map(|list| list.title.as_str()),
            Some("generation two"),
            "a legitimate monotonic Taskwrite must not be rebased away"
        );

        let mut divergent = durable_newer.clone();
        divergent.set_task_list(transaction_task_list(
            &divergent.id,
            "same generation divergent",
        ));
        divergent.set_task_list_version_meta("2");
        divergent
            .metadata
            .insert("ordinary.non-task".to_string(), "must persist".to_string());
        let conflict = storage
            .save_runtime_state(&divergent)
            .await
            .expect_err("same-generation divergence must fail before writing");
        assert_eq!(conflict.kind(), io::ErrorKind::WouldBlock);
        assert_eq!(
            divergent.task_list.as_ref().map(|list| list.title.as_str()),
            Some("same generation divergent"),
            "save must not mutate the caller-owned snapshot"
        );
        let durable = storage
            .load_session(&divergent.id)
            .await?
            .expect("durable session");
        assert_eq!(durable.task_list_version_meta().as_deref(), Some("2"));
        assert_eq!(
            durable.task_list.as_ref().map(|list| list.title.as_str()),
            Some("generation two"),
            "same-generation divergent content must preserve durable truth"
        );
        assert!(!durable.metadata.contains_key("ordinary.non-task"));
        Ok(())
    }

    async fn assert_corrupt_index_orphan_task_journal_recovers(
        marker_state: RuntimeTaskJournalMarkerState,
    ) -> io::Result<()> {
        assert!(matches!(
            marker_state,
            RuntimeTaskJournalMarkerState::Prepared | RuntimeTaskJournalMarkerState::Committing
        ));
        let (storage, temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, _root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        let transaction_id = Uuid::new_v4().to_string();
        let journal = RuntimeTaskTransactionJournal {
            version: RUNTIME_TASK_TRANSACTION_VERSION,
            transaction_id,
            first: TaskControlPlaneUndo {
                session_id: child_original.id.clone(),
                task_list: child_original.task_list.clone(),
                task_list_version: child_original
                    .task_list_version_meta()
                    .expect("child generation"),
            },
            second: TaskControlPlaneUndo {
                session_id: root_original.id.clone(),
                task_list: root_original.task_list.clone(),
                task_list_version: root_original
                    .task_list_version_meta()
                    .expect("root generation"),
            },
        };
        let mut journal_path = storage.write_runtime_task_journal(&journal).await?;
        let journal_json = fs::read_to_string(&journal_path).await?;
        assert!(!journal_json.contains("transcript secret"));
        assert!(!journal_json.contains("metadata secret"));
        assert!(!journal_json.contains("unrelated.child"));
        assert!(!journal_json.contains("unrelated.root"));
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(storage.runtime_task_transaction_dir())
                .await?
                .permissions()
                .mode();
            assert_eq!(mode & 0o077, 0, "journal directory must be private");
        }

        // Simulate process death after the first rename: leave the durable undo
        // journal and only the lexically first target at generation 2.
        storage
            .write_existing_runtime_sidecar_durable_unchecked(
                &child_updated,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                &storage.lock_runtime_task_transaction_exclusive().await?,
            )
            .await?;
        if marker_state == RuntimeTaskJournalMarkerState::Committing {
            let committing = journal_path.with_extension("committing");
            atomic_rename(&journal_path, &committing).await?;
            sync_parent_directory_entry(&committing).await?;
            journal_path = committing;
        }
        assert!(journal_path.exists());
        let child_sidecar = storage
            .runtime_json_path("tx-child")
            .await?
            .expect("child runtime sidecar path");
        let root_sidecar = storage
            .runtime_json_path("tx-root")
            .await?
            .expect("root runtime sidecar path");
        assert!(child_sidecar.exists());
        assert!(root_sidecar.exists());

        // Exercise the constructor ordering hazard: corrupt-index handling
        // publishes an empty rebuild marker before orphan Task recovery. Undo
        // must therefore locate these intact authoritative session directories
        // without consulting that temporarily empty index.
        fs::write(storage.index_path(), b"{ corrupt sessions index").await?;
        drop(storage);

        let reopened = SessionStoreV2::new(temp.path().to_path_buf()).await?;
        assert_eq!(
            reopened.take_runtime_task_durability_events(),
            vec![
                RuntimeTaskDurabilityEvent::FirstRollbackSidecarPublished,
                RuntimeTaskDurabilityEvent::SecondRollbackSidecarPublished,
                RuntimeTaskDurabilityEvent::JournalDeactivated,
            ]
        );
        assert_original_runtime_task_pair(&reopened).await?;
        assert!(reopened.runtime_task_journal_paths().await?.is_empty());
        assert!(temp.path().join("sessions.json.bak").exists());
        let rebuilt_raw = fs::read_to_string(reopened.index_path()).await?;
        let rebuilt: SessionsIndex = serde_json::from_str(&rebuilt_raw)
            .map_err(|error| other_io_error(format!("parse rebuilt sessions index: {error}")))?;
        assert_eq!(rebuilt.version, SESSIONS_INDEX_VERSION);
        assert!(!rebuilt.rebuild_in_progress);
        assert_eq!(rebuilt.sessions.len(), 2);
        assert_eq!(
            rebuilt
                .sessions
                .get("tx-root")
                .map(|entry| entry.rel_path.as_str()),
            Some("sessions/tx-root")
        );
        assert_eq!(
            rebuilt
                .sessions
                .get("tx-child")
                .map(|entry| entry.rel_path.as_str()),
            Some("sessions/tx-root/children/tx-child")
        );
        Ok(())
    }

    #[tokio::test]
    async fn reopening_store_recovers_orphan_task_journal_without_transcript_or_metadata_copy(
    ) -> io::Result<()> {
        for marker_state in [
            RuntimeTaskJournalMarkerState::Prepared,
            RuntimeTaskJournalMarkerState::Committing,
        ] {
            assert_corrupt_index_orphan_task_journal_recovers(marker_state).await?;
        }
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn rebuild_keeps_retry_marker_when_pair_transaction_crashes_mid_scan() -> io::Result<()> {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let home = temp.path().to_path_buf();
        let rebuild_store = Arc::new(SessionStoreV2::new(home.clone()).await?);
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&rebuild_store).await?;
        // Independent in-memory locks model the second Bamboo process that can
        // start a Task pair commit after constructor recovery releases its
        // exclusive cross-process guard.
        let commit_store = Arc::new(SessionStoreV2::new(home.clone()).await?);

        rebuild_store
            .update_index(|index| {
                *index = SessionsIndex::empty();
                index.version = 0;
                index.rebuild_in_progress = true;
                Ok(())
            })
            .await?;

        // Freeze the first per-entry lifecycle probe. Pair commits do not own
        // lifecycle, so the independent store can publish its journal and
        // first sidecar while rebuild is demonstrably mid-scan.
        let lifecycle = rebuild_store.lock_session_lifecycle_exclusive().await?;
        let rebuilding = Arc::clone(&rebuild_store);
        let rebuild = tokio::spawn(async move { rebuilding.rebuild_index_from_disk().await });
        tokio::task::yield_now().await;

        let (first_write_reached, _release_first_write) =
            commit_store.pause_runtime_task_transaction_after_first_write();
        let committing = Arc::clone(&commit_store);
        let commit = tokio::spawn(async move {
            committing
                .save_task_control_planes_atomically(
                    &child_original,
                    &child_updated,
                    &root_original,
                    &root_updated,
                )
                .await
        });
        first_write_reached.wait().await;
        assert_eq!(commit_store.runtime_task_journal_paths().await?.len(), 1);
        assert_eq!(
            commit_store.take_runtime_task_durability_events(),
            vec![
                RuntimeTaskDurabilityEvent::JournalPublished,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
            ]
        );

        // Cancellation models process death: the exclusive file guard drops,
        // while the prepared undo journal and first durable sidecar remain.
        commit.abort();
        assert!(
            commit
                .await
                .expect_err("commit task must be cancelled")
                .is_cancelled(),
            "cancelled commit must release the cross-process Task guard"
        );
        drop(lifecycle);

        let rebuild_error = rebuild
            .await
            .map_err(io::Error::other)?
            .expect_err("a pending journal must prevent rebuild finalization");
        assert!(
            rebuild_error.to_string().contains("recovery is required"),
            "{rebuild_error}"
        );
        let retryable: SessionsIndex =
            serde_json::from_slice(&fs::read(&home.join("sessions.json")).await?)
                .map_err(io::Error::other)?;
        assert_eq!(retryable.version, 0);
        assert!(retryable.rebuild_in_progress);
        assert!(retryable.sessions.is_empty());
        assert_eq!(commit_store.runtime_task_journal_paths().await?.len(), 1);

        drop(commit_store);
        drop(rebuild_store);
        let reopened = SessionStoreV2::new(home).await?;
        assert_eq!(
            reopened.take_runtime_task_durability_events(),
            vec![
                RuntimeTaskDurabilityEvent::FirstRollbackSidecarPublished,
                RuntimeTaskDurabilityEvent::SecondRollbackSidecarPublished,
                RuntimeTaskDurabilityEvent::JournalDeactivated,
            ]
        );
        assert_original_runtime_task_pair(&reopened).await?;
        assert!(reopened.runtime_task_journal_paths().await?.is_empty());
        let rebuilt: SessionsIndex =
            serde_json::from_slice(&fs::read(reopened.index_path()).await?)
                .map_err(io::Error::other)?;
        assert_eq!(rebuilt.version, SESSIONS_INDEX_VERSION);
        assert!(!rebuilt.rebuild_in_progress);
        assert_eq!(rebuilt.sessions.len(), 2);
        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn orphan_recovery_rejects_symlinked_child_without_writing_outside_sessions(
    ) -> io::Result<()> {
        use std::os::unix::fs::symlink;

        let (storage, temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, _root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        let journal = RuntimeTaskTransactionJournal {
            version: RUNTIME_TASK_TRANSACTION_VERSION,
            transaction_id: Uuid::new_v4().to_string(),
            first: TaskControlPlaneUndo {
                session_id: child_original.id.clone(),
                task_list: child_original.task_list.clone(),
                task_list_version: child_original
                    .task_list_version_meta()
                    .expect("child generation"),
            },
            second: TaskControlPlaneUndo {
                session_id: root_original.id.clone(),
                task_list: root_original.task_list.clone(),
                task_list_version: root_original
                    .task_list_version_meta()
                    .expect("root generation"),
            },
        };
        let journal_path = storage.write_runtime_task_journal(&journal).await?;
        storage
            .write_existing_runtime_sidecar_durable_unchecked(
                &child_updated,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                &storage.lock_runtime_task_transaction_exclusive().await?,
            )
            .await?;

        let child_dir = temp.path().join("sessions/tx-root/children/tx-child");
        let outside_dir = temp.path().join("outside-session-tree");
        fs::rename(&child_dir, &outside_dir).await?;
        symlink(&outside_dir, &child_dir).map_err(io::Error::other)?;
        let outside_runtime = outside_dir.join(RUNTIME_SIDECAR_FILE);
        let outside_before = fs::read(&outside_runtime).await?;
        fs::write(storage.index_path(), b"{ corrupt sessions index").await?;
        drop(storage);

        let error = SessionStoreV2::new(temp.path().to_path_buf())
            .await
            .expect_err("symlinked journal target must fail closed");
        assert!(
            error.to_string().contains("not a real directory"),
            "{error}"
        );
        assert_eq!(
            fs::read(&outside_runtime).await?,
            outside_before,
            "recovery must not rewrite runtime.json outside sessions/"
        );
        assert!(fs::symlink_metadata(&child_dir)
            .await?
            .file_type()
            .is_symlink());
        assert!(journal_path.exists(), "failed recovery must retain undo");
        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn orphan_recovery_rejects_symlinked_sessions_root_without_writing_outside_home(
    ) -> io::Result<()> {
        use std::os::unix::fs::symlink;

        let (storage, temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, _root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        let journal = RuntimeTaskTransactionJournal {
            version: RUNTIME_TASK_TRANSACTION_VERSION,
            transaction_id: Uuid::new_v4().to_string(),
            first: TaskControlPlaneUndo {
                session_id: child_original.id.clone(),
                task_list: child_original.task_list.clone(),
                task_list_version: child_original
                    .task_list_version_meta()
                    .expect("child generation"),
            },
            second: TaskControlPlaneUndo {
                session_id: root_original.id.clone(),
                task_list: root_original.task_list.clone(),
                task_list_version: root_original
                    .task_list_version_meta()
                    .expect("root generation"),
            },
        };
        let journal_path = storage.write_runtime_task_journal(&journal).await?;
        storage
            .write_existing_runtime_sidecar_durable_unchecked(
                &child_updated,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                &storage.lock_runtime_task_transaction_exclusive().await?,
            )
            .await?;

        let sessions_dir = temp.path().join("sessions");
        let outside_home = TempDir::new().map_err(io::Error::other)?;
        let outside_dir = outside_home.path().join("sessions");
        fs::rename(&sessions_dir, &outside_dir).await?;
        symlink(&outside_dir, &sessions_dir).map_err(io::Error::other)?;
        let outside_runtime = outside_dir.join("tx-root/children/tx-child/runtime.json");
        let outside_before = fs::read(&outside_runtime).await?;
        fs::write(storage.index_path(), b"{ corrupt sessions index").await?;
        drop(storage);

        let error = SessionStoreV2::new(temp.path().to_path_buf())
            .await
            .expect_err("symlinked sessions root must fail closed");
        assert!(
            error.to_string().contains("not a real directory"),
            "{error}"
        );
        assert_eq!(
            fs::read(&outside_runtime).await?,
            outside_before,
            "recovery must not rewrite runtime.json outside Bamboo home"
        );
        assert!(fs::symlink_metadata(&sessions_dir)
            .await?
            .file_type()
            .is_symlink());
        assert!(journal_path.exists(), "failed recovery must retain undo");
        Ok(())
    }

    #[tokio::test]
    async fn reopening_store_keeps_durable_pair_when_committed_marker_survives() -> io::Result<()> {
        let (storage, temp) = create_temp_storage().await?;
        let (child_original, child_updated, root_original, root_updated) =
            seed_runtime_task_transaction_pair(&storage).await?;
        let journal = RuntimeTaskTransactionJournal {
            version: RUNTIME_TASK_TRANSACTION_VERSION,
            transaction_id: Uuid::new_v4().to_string(),
            first: TaskControlPlaneUndo {
                session_id: child_original.id.clone(),
                task_list: child_original.task_list.clone(),
                task_list_version: child_original
                    .task_list_version_meta()
                    .expect("child generation"),
            },
            second: TaskControlPlaneUndo {
                session_id: root_original.id.clone(),
                task_list: root_original.task_list.clone(),
                task_list_version: root_original
                    .task_list_version_meta()
                    .expect("root generation"),
            },
        };
        let prepared = storage.write_runtime_task_journal(&journal).await?;
        storage
            .write_existing_runtime_sidecar_durable_unchecked(
                &child_updated,
                RuntimeTaskDurabilityEvent::FirstUpdatedSidecarPublished,
                &storage.lock_runtime_task_transaction_exclusive().await?,
            )
            .await?;
        storage
            .write_existing_runtime_sidecar_durable_unchecked(
                &root_updated,
                RuntimeTaskDurabilityEvent::SecondUpdatedSidecarPublished,
                &storage.lock_runtime_task_transaction_exclusive().await?,
            )
            .await?;
        let committing = prepared.with_extension("committing");
        atomic_rename(&prepared, &committing).await?;
        sync_parent_directory_entry(&committing).await?;
        let committed = prepared.with_extension("committed");
        atomic_rename(&committing, &committed).await?;
        sync_parent_directory_entry(&committed).await?;
        drop(storage);

        let reopened = SessionStoreV2::new(temp.path().to_path_buf()).await?;
        assert_eq!(
            reopened.take_runtime_task_durability_events(),
            vec![RuntimeTaskDurabilityEvent::JournalDeactivated],
            "committed recovery must clean the marker without publishing either undo"
        );
        assert!(reopened.runtime_task_journal_paths().await?.is_empty());
        let child = reopened
            .load_session("tx-child")
            .await?
            .expect("child remains");
        let root = reopened
            .load_session("tx-root")
            .await?
            .expect("root remains");
        for (session, transcript, metadata_key, metadata_value) in [
            (
                &child,
                "child transcript secret",
                "unrelated.child",
                "child metadata secret",
            ),
            (
                &root,
                "root transcript secret",
                "unrelated.root",
                "root metadata secret",
            ),
        ] {
            assert_eq!(session.task_list_version_meta().as_deref(), Some("2"));
            assert_eq!(
                session.task_list.as_ref().map(|list| list.title.as_str()),
                Some("evaluated")
            );
            assert_eq!(session.messages[0].content, transcript);
            assert_eq!(
                session.metadata.get(metadata_key).map(String::as_str),
                Some(metadata_value)
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_new_creates_sessions_directory() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let sessions_dir = bamboo_home.join("sessions");

        assert!(!sessions_dir.exists());
        let _storage = SessionStoreV2::new(bamboo_home).await?;
        assert!(sessions_dir.exists());

        Ok(())
    }

    #[tokio::test]
    async fn first_save_recreates_removed_home_before_opening_task_lock() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().join("removed-bamboo-home");
        let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
        fs::remove_dir_all(&bamboo_home).await?;

        let session = Session::new("first-save-after-home-removal", "model");
        storage.save_session(&session).await?;

        assert!(
            bamboo_home
                .join(RUNTIME_TASK_TRANSACTION_LOCK_FILE)
                .exists(),
            "the Task transaction lock parent must be recreated on first use"
        );
        assert!(storage.load_session(&session.id).await?.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn clean_sidecar_reads_do_not_create_or_rechmod_journal_directory() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let session = Session::new("clean-journal-probe", "model");
        storage.save_session(&session).await?;
        let journal_dir = storage.runtime_task_transaction_dir();
        fs::remove_dir(&journal_dir).await?;

        assert!(storage.load_session(&session.id).await?.is_some());
        assert!(
            !journal_dir.exists(),
            "ordinary clean reads must treat a missing journal directory as empty"
        );

        fs::create_dir(&journal_dir).await?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&journal_dir, std::fs::Permissions::from_mode(0o750)).await?;
            assert!(storage
                .load_runtime_control_plane(&session.id)
                .await?
                .is_some());
            let mode = fs::metadata(&journal_dir).await?.permissions().mode();
            assert_eq!(
                mode & 0o777,
                0o750,
                "ordinary clean reads must not repeat constructor/write chmod"
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn root_token_budget_cleared_on_load_child_preserved() -> io::Result<()> {
        // #230: a Root persisted with a token_budget (pre-#180 stale cache) loads
        // with token_budget == None so it re-resolves; a Child's assigned
        // sub-budget survives the reload.
        let (storage, _dir) = create_temp_storage().await?;

        let mut root = Session::new("root-1", "m");
        root.token_budget = Some(bamboo_domain::TokenBudget::for_model(1000));
        storage.save_session(&root).await?;
        let loaded = storage.load_session("root-1").await?.expect("root present");
        assert!(
            loaded.token_budget.is_none(),
            "stale Root token_budget must be cleared on load"
        );

        let parent = Session::new("root-1", "m");
        let mut child = Session::new_child_of("child-1", &parent, "m", "c");
        child.token_budget = Some(bamboo_domain::TokenBudget::for_model(500));
        storage.save_session(&child).await?;
        let loaded_child = storage
            .load_session("child-1")
            .await?
            .expect("child present");
        assert!(
            loaded_child.token_budget.is_some(),
            "Child assigned sub-budget must be preserved on load"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_new_creates_index_file() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let index_path = bamboo_home.join("sessions.json");

        assert!(!index_path.exists());
        let _storage = SessionStoreV2::new(bamboo_home).await?;
        assert!(index_path.exists());

        Ok(())
    }

    #[tokio::test]
    async fn title_lifecycle_is_indexed_and_legacy_rows_fail_safe() -> io::Result<()> {
        let (storage, _dir) = create_temp_storage().await?;
        let session = Session::new("pending-title", "m");
        storage.save_session(&session).await?;

        let entry = storage
            .get_index_entry(&session.id)
            .await
            .expect("saved session is indexed");
        assert!(!entry.title_generated);

        let mut legacy = serde_json::to_value(&entry).unwrap();
        legacy.as_object_mut().unwrap().remove("title_generated");
        let decoded: SessionIndexEntry = serde_json::from_value(legacy).unwrap();
        assert!(decoded.title_generated);

        Ok(())
    }

    // ── Runtime sidecar (③) ───────────────────────────────────────────────

    use bamboo_domain::AgentRuntimeState;

    fn session_with_history(id: &str, messages: usize, run_id: &str) -> Session {
        let mut s = Session::new(id.to_string(), "test-model".to_string());
        for i in 0..messages {
            s.add_message(Message::user(format!("msg-{i}")));
        }
        s.agent_runtime_state = Some(AgentRuntimeState::new(run_id));
        s
    }

    async fn read_session_json_raw(storage: &SessionStoreV2, id: &str) -> String {
        let path = storage.session_json_path(id).await.unwrap().unwrap();
        tokio::fs::read_to_string(path).await.unwrap()
    }

    #[tokio::test]
    async fn append_token_usage_record_writes_jsonl_in_session_dir() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        let s = session_with_history("tu-1", 1, "run-A");
        storage.save_session(&s).await?;

        storage
            .append_token_usage_record("tu-1", r#"{"round":1,"cache_read_input_tokens":0}"#)
            .await?;
        // A trailing newline in the caller's line must not produce a blank line.
        storage
            .append_token_usage_record("tu-1", "{\"round\":2,\"cache_read_input_tokens\":9000}\n")
            .await?;

        let rel = storage.resolve_rel_path("tu-1").await.unwrap();
        let path = storage.abs_path_from_rel(&rel).join(TOKEN_USAGE_FILE);
        assert!(
            path.exists(),
            "token-usage.jsonl should sit in the session dir"
        );

        let contents = tokio::fs::read_to_string(&path).await?;
        let lines: Vec<&str> = contents.lines().collect();
        // Storage is a unique per-test TempDir and every path resolves off the
        // instance `bamboo_home_dir` (not a process-global), so nothing outside
        // this test can write here — exactly two sequential appends ⇒ two lines.
        // If CI ever trips this again (#378), dump the file so the failure is
        // diagnosable (extra line + its source, or a lost append) instead of an
        // opaque count mismatch. Do NOT relax this to "records present": that
        // would mask a real double-write / lost-write regression.
        assert_eq!(
            lines.len(),
            2,
            "one line per appended record; actual token-usage.jsonl = {contents:?}"
        );
        assert!(lines[0].contains("\"round\":1"));
        assert!(lines[1].contains("\"round\":2"));
        // Each line is valid standalone JSON.
        for line in lines {
            serde_json::from_str::<serde_json::Value>(line).expect("each line is valid JSON");
        }
        Ok(())
    }

    #[tokio::test]
    async fn append_token_usage_record_is_noop_for_unindexed_session() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        // No save_session → not indexed yet. Must not error, must not create a file.
        storage
            .append_token_usage_record("never-saved", r#"{"round":1}"#)
            .await?;
        assert!(storage.resolve_rel_path("never-saved").await.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn save_session_writes_runtime_sidecar() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        let mut s = session_with_history("sc-1", 2, "run-A");
        let assistant = Message::assistant("discovery", None);
        let anchor = assistant.id.clone();
        s.add_message(assistant);
        let item = bamboo_domain::ProviderTranscriptItem::try_from_payload(
            bamboo_domain::ProviderFamily::OpenAi,
            bamboo_domain::ProviderProtocol::OpenAiResponsesV1,
            bamboo_domain::ProviderTranscriptOrigin::Provider,
            bamboo_domain::ProviderTranscriptAuthor::Model,
            serde_json::json!({
                "type":"tool_search_call","id":"tsc_search_sidecar","execution":"client","call_id":"search_sidecar",
                "status":"completed","arguments":{"query":"weather"}
            }),
        )
        .unwrap();
        s.append_provider_transcript_group(&anchor, None, vec![item])
            .unwrap();
        storage.save_session(&s).await?;

        let sidecar_path = storage.runtime_json_path("sc-1").await?.unwrap();
        assert!(
            sidecar_path.exists(),
            "save_session must write runtime.json"
        );

        // Sidecar must NOT carry the message history.
        let side = storage.read_runtime_sidecar("sc-1").await?.unwrap();
        assert!(side.messages.is_empty(), "sidecar messages must be cleared");
        assert!(side.provider_transcript.is_empty());
        assert_eq!(side.agent_runtime_state.as_ref().unwrap().run_id, "run-A");
        let loaded = storage.load_session("sc-1").await?.unwrap();
        assert_eq!(loaded.provider_transcript.groups().len(), 1);
        Ok(())
    }

    #[tokio::test]
    async fn model_context_ledger_round_trips_through_session_persistence() -> io::Result<()> {
        use bamboo_domain::{
            deterministic_model_context_event_id, model_context_block_sha256,
            render_model_context_snapshot, ContextBlock, ContextBlockBaseline,
            ContextBlockPriority, ContextBlockStability, ContextBlockType, ModelContextEvent,
            ModelContextEventKind, ModelContextState,
        };

        let (storage, _t) = create_temp_storage().await?;
        let mut session = session_with_history("ledger-persistence", 2, "run-ledger");
        let block = ContextBlock::new(
            ContextBlockType::TaskSnapshot,
            ContextBlockPriority::High,
            ContextBlockStability::RoundDynamic,
            "Task",
            "durable context bytes",
        );
        let digest = model_context_block_sha256(&block);
        let id = deterministic_model_context_event_id(
            &session.id,
            3,
            ContextBlockType::TaskSnapshot,
            1,
            &digest,
        );
        let rendered_text = render_model_context_snapshot(&id, 3, 0, &block, 1, None);
        let state = ModelContextState {
            prefix_epoch: 3,
            next_sequence: 1,
            baselines: std::collections::BTreeMap::from([(
                ContextBlockType::TaskSnapshot,
                ContextBlockBaseline {
                    revision: 1,
                    content_sha256: digest.clone(),
                },
            )]),
            events: vec![ModelContextEvent {
                id,
                epoch: 3,
                sequence: 0,
                anchor_message_id: None,
                block_type: ContextBlockType::TaskSnapshot,
                revision: 1,
                supersedes_revision: None,
                kind: ModelContextEventKind::Snapshot,
                content_sha256: digest,
                rendered_text,
            }],
            cache_scope_sha256: Some("scope-hash".to_string()),
            transcript_item_sha256: vec!["item-hash".to_string()],
            ..ModelContextState::default()
        };
        session.model_context_state = Some(state.clone());

        storage.save_session(&session).await?;

        let sidecar = storage
            .read_runtime_sidecar(&session.id)
            .await?
            .expect("runtime sidecar");
        assert_eq!(sidecar.model_context_state.as_ref(), Some(&state));
        assert!(sidecar.messages.is_empty());

        let loaded = storage
            .load_session(&session.id)
            .await?
            .expect("persisted session");
        assert_eq!(loaded.model_context_state.as_ref(), Some(&state));
        assert_eq!(loaded.messages.len(), session.messages.len());
        assert!(loaded
            .messages
            .iter()
            .zip(&session.messages)
            .all(|(loaded, original)| {
                loaded.id == original.id
                    && loaded.role == original.role
                    && loaded.content == original.content
            }));
        Ok(())
    }

    #[tokio::test]
    async fn save_runtime_state_does_not_rewrite_session_json_messages() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;

        // Full save: 3 messages + run-A.
        let s = session_with_history("sc-2", 3, "run-A");
        storage.save_session(&s).await?;
        let raw_before = read_session_json_raw(&storage, "sc-2").await;
        assert!(raw_before.contains("msg-2"));

        // Runtime-only save: bump control-plane to run-B AND (deviously) add a
        // 4th in-memory message. The sidecar must persist run-B but IGNORE the
        // message, and session.json must be left byte-identical.
        let mut s2 = s.clone();
        s2.agent_runtime_state = Some(AgentRuntimeState::new("run-B"));
        s2.add_message(Message::user("msg-3-should-not-persist"));
        storage.save_runtime_state(&s2).await?;

        let raw_after = read_session_json_raw(&storage, "sc-2").await;
        assert_eq!(
            raw_before, raw_after,
            "save_runtime_state must not touch session.json"
        );

        // Load overlays the sidecar: run-B control-plane + original 3 messages.
        let loaded = storage.load_session("sc-2").await?.unwrap();
        assert_eq!(loaded.agent_runtime_state.as_ref().unwrap().run_id, "run-B");
        assert_eq!(
            loaded.messages.len(),
            3,
            "runtime-only save must not add a message"
        );
        Ok(())
    }

    #[tokio::test]
    async fn save_runtime_state_falls_back_to_full_save_when_unpersisted() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        // Session was never saved: no index entry, no dir. save_runtime_state
        // must fall back to a full save so session.json + index get created.
        let s = session_with_history("sc-3", 1, "run-A");
        storage.save_runtime_state(&s).await?;

        let loaded = storage.load_session("sc-3").await?;
        assert!(
            loaded.is_some(),
            "fallback full save must create the session"
        );
        assert_eq!(loaded.unwrap().messages.len(), 1);
        Ok(())
    }

    #[tokio::test]
    async fn paused_full_save_does_not_block_unrelated_full_save() -> io::Result<()> {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let storage = Arc::new(SessionStoreV2::new(temp.path().to_path_buf()).await?);
        let paused = session_with_history("convoy-full-a", 2, "run-a");
        let unrelated = session_with_history("convoy-full-b", 2, "run-b");
        let (reached, release) =
            storage.pause_full_save_before_filesystem_commit_for_test(&paused.id);

        let paused_store = storage.clone();
        let paused_save = tokio::spawn(async move { paused_store.save_session(&paused).await });
        reached.wait().await;

        let unrelated_store = storage.clone();
        let unrelated_save =
            tokio::spawn(async move { unrelated_store.save_session(&unrelated).await });
        tokio::time::timeout(Duration::from_secs(2), unrelated_save)
            .await
            .expect("unrelated full save must not wait for paused session")
            .expect("unrelated full-save task")?;

        release.wait().await;
        paused_save.await.expect("paused full-save task")?;
        assert!(storage.session_write_locks.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn paused_full_save_does_not_block_unrelated_runtime_save() -> io::Result<()> {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let storage = Arc::new(SessionStoreV2::new(temp.path().to_path_buf()).await?);
        let paused = session_with_history("convoy-runtime-a", 2, "run-a");
        let mut unrelated = session_with_history("convoy-runtime-b", 2, "run-b");
        storage.save_session(&unrelated).await?;
        unrelated.agent_runtime_state = Some(AgentRuntimeState::new("run-b-next"));
        let (reached, release) =
            storage.pause_full_save_before_filesystem_commit_for_test(&paused.id);

        let paused_store = storage.clone();
        let paused_save = tokio::spawn(async move { paused_store.save_session(&paused).await });
        reached.wait().await;

        let unrelated_store = storage.clone();
        let unrelated_save =
            tokio::spawn(async move { unrelated_store.save_runtime_state(&unrelated).await });
        tokio::time::timeout(Duration::from_secs(2), unrelated_save)
            .await
            .expect("unrelated runtime save must not wait for paused session")
            .expect("unrelated runtime-save task")?;

        release.wait().await;
        paused_save.await.expect("paused full-save task")?;
        assert!(storage.session_write_locks.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn paused_full_save_serializes_same_session_runtime_save() -> io::Result<()> {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let storage = Arc::new(SessionStoreV2::new(temp.path().to_path_buf()).await?);
        let paused = session_with_history("same-session-order", 2, "run-a");
        storage.save_session(&paused).await?;
        let mut runtime = paused.clone();
        runtime.agent_runtime_state = Some(AgentRuntimeState::new("run-after-full"));
        let (reached, release) =
            storage.pause_full_save_before_filesystem_commit_for_test(&paused.id);

        let paused_store = storage.clone();
        let paused_save = tokio::spawn(async move { paused_store.save_session(&paused).await });
        reached.wait().await;

        let runtime_store = storage.clone();
        let mut runtime_save =
            tokio::spawn(async move { runtime_store.save_runtime_state(&runtime).await });
        assert!(
            tokio::time::timeout(Duration::from_millis(100), &mut runtime_save)
                .await
                .is_err(),
            "same-session runtime save must wait for the paused full save"
        );

        release.wait().await;
        paused_save.await.expect("paused full-save task")?;
        runtime_save.await.expect("runtime-save task")?;
        let loaded = storage
            .load_session("same-session-order")
            .await?
            .expect("session remains readable");
        assert_eq!(
            loaded
                .agent_runtime_state
                .as_ref()
                .map(|state| state.run_id.as_str()),
            Some("run-after-full")
        );
        assert!(storage.session_write_locks.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn peer_delivery_waits_for_ancestor_without_holding_reverse_lexical_child(
    ) -> io::Result<()> {
        use std::future::Future;
        let (store, _temp) = create_temp_storage().await?;
        let root = Session::new("z-root", "model");
        let child = Session::new_child_of("a-child", &root, "model", "child");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        let source = bamboo_domain::ActorSession::from_session(&child).unwrap();
        let target = bamboo_domain::ActorSession::from_session(&root).unwrap();
        // ParentQuestion acquires the ancestor Session before its child.
        let ancestor = store.acquire_session_maintenance_lock(&root.id).await?;
        let root_lock = store
            .session_write_locks
            .get(&root.id)
            .unwrap()
            .value()
            .clone();
        let owners = Arc::strong_count(&root_lock);
        let mut peer = Box::pin(store.lock_peer_delivery(&source, &target, None));
        tokio::time::timeout(
            Duration::from_secs(10),
            std::future::poll_fn(|cx| {
                assert!(peer.as_mut().poll(cx).is_pending());
                // The owned Mutex waiter retains an Arc as soon as it queues.
                if Arc::strong_count(&root_lock) > owners {
                    std::task::Poll::Ready(())
                } else {
                    std::task::Poll::Pending
                }
            }),
        )
        .await
        .expect("peer must reach the held ancestor lock");
        // Once peer is waiting for the ancestor, the answer writer must still
        // acquire the child. Child-first ordering would deadlock this step.
        let descendant = tokio::time::timeout(
            Duration::from_secs(10),
            store.acquire_session_maintenance_lock(&child.id),
        )
        .await
        .expect("peer must not hold child while waiting for ancestor")?;
        drop(descendant);
        drop(ancestor);
        drop(root_lock);
        drop(
            tokio::time::timeout(Duration::from_secs(10), peer)
                .await
                .expect("peer must proceed after the answer writer releases")?,
        );
        Ok(())
    }

    #[tokio::test]
    async fn cancelled_last_waiter_reclaims_session_write_locks() -> io::Result<()> {
        let temp = TempDir::new()?;
        let store = SessionStoreV2::new(temp.path().to_path_buf()).await?;
        for index in 0..512 {
            let id = format!("cancelled-child-{index}");
            let held = store.acquire_session_maintenance_lock(&id).await?;
            let mut waiter = Box::pin(store.acquire_session_write_lock(&id, SaveKind::Runtime));
            assert!(
                std::future::poll_fn(|cx| std::task::Poll::Ready(
                    std::future::Future::poll(waiter.as_mut(), cx).is_pending()
                ))
                .await
            );
            drop(held);
            drop(waiter);
        }
        assert!(store.session_write_locks.is_empty());
        assert_eq!(
            store
                .persistence_metrics
                .waiting_saves
                .load(Ordering::Relaxed),
            0
        );
        Ok(())
    }

    #[tokio::test]
    async fn independent_stores_serialize_same_session_without_blocking_other_ids() -> io::Result<()>
    {
        let temp = TempDir::new().map_err(io::Error::other)?;
        let first = Arc::new(SessionStoreV2::new(temp.path().to_path_buf()).await?);
        let shared = session_with_history("cross-store-shared", 2, "run-a");
        first.save_session(&shared).await?;
        let second = Arc::new(SessionStoreV2::new(temp.path().to_path_buf()).await?);

        let unrelated = session_with_history("cross-store-unrelated", 2, "run-b");
        let mut runtime = shared.clone();
        runtime.agent_runtime_state = Some(AgentRuntimeState::new("run-after-cross-store-full"));
        let (reached, release) =
            first.pause_full_save_before_filesystem_commit_for_test(&shared.id);

        let first_save_store = first.clone();
        let paused = shared.clone();
        let first_save = tokio::spawn(async move { first_save_store.save_session(&paused).await });
        reached.wait().await;

        let unrelated_store = second.clone();
        let unrelated_save =
            tokio::spawn(async move { unrelated_store.save_session(&unrelated).await });
        tokio::time::timeout(Duration::from_secs(2), unrelated_save)
            .await
            .expect("another store must persist an unrelated id independently")
            .expect("unrelated cross-store save task")?;

        let cancelled_store = second.clone();
        let cancelled_runtime = runtime.clone();
        let cancelled =
            tokio::spawn(
                async move { cancelled_store.save_runtime_state(&cancelled_runtime).await },
            );
        tokio::time::sleep(Duration::from_millis(50)).await;
        cancelled.abort();
        assert!(cancelled.await.is_err(), "contended save must be cancelled");
        assert_eq!(second.persistence_metrics().waiting_saves, 0);
        assert!(
            second.session_write_locks.is_empty(),
            "cancellation while the file lock is contended must reclaim the local lock entry"
        );

        let runtime_store = second.clone();
        let mut runtime_save =
            tokio::spawn(async move { runtime_store.save_runtime_state(&runtime).await });
        assert!(
            tokio::time::timeout(Duration::from_millis(100), &mut runtime_save)
                .await
                .is_err(),
            "the cross-process session lock must serialize the same id"
        );

        release.wait().await;
        first_save.await.expect("cross-store full-save task")?;
        runtime_save.await.expect("cross-store runtime-save task")?;
        let loaded = second
            .load_session("cross-store-shared")
            .await?
            .expect("shared session remains readable");
        assert_eq!(
            loaded
                .agent_runtime_state
                .as_ref()
                .map(|state| state.run_id.as_str()),
            Some("run-after-cross-store-full")
        );
        assert!(first.session_write_locks.is_empty());
        assert!(second.session_write_locks.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn deferred_search_index_coalesces_to_latest_session_and_delete() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        let mut session = session_with_history("search-generation", 1, "run-a");
        session.title = "old queued title".to_string();
        storage.save_session(&session).await?;
        let stale_session = session.clone();
        let revision_path = storage
            .sessions_root_dir()
            .join(&session.id)
            .join(SEARCH_INDEX_REVISION_FILE);
        let stale_revision = fs::read_to_string(&revision_path).await?;
        session.title = "newest queued title".to_string();
        session.updated_at = Utc::now() + chrono::Duration::milliseconds(1);
        storage.save_session(&session).await?;
        storage.flush_search_index().await;

        let published_revision = storage
            .search_source_revision(&session.id)
            .await?
            .expect("saved Session publishes a search revision");
        let page = storage
            .search_index()
            .search_messages_in_session(&session.id, "msg", usize::MAX, &[], 10)
            .await?;
        assert_eq!(
            page.indexed_source_revision.as_deref(),
            Some(published_revision.as_str())
        );
        assert_eq!(page.indexed_updated_at, Some(session.updated_at));

        storage
            .search_index()
            .upsert_session_if_current(&stale_session, &revision_path, &stale_revision)
            .await?;

        let newest = storage.search_index().search("newest", 10).await?;
        assert!(newest
            .iter()
            .any(|entry| entry.session_id == "search-generation"));
        let stale = storage.search_index().search("old queued", 10).await?;
        assert!(stale
            .iter()
            .all(|entry| entry.session_id != "search-generation"));

        let current_revision = fs::read_to_string(&revision_path).await?;
        assert!(
            storage
                .delete_session_recursive("search-generation", true)
                .await?
        );
        storage.flush_search_index().await;
        storage
            .search_index()
            .upsert_session_if_current(&session, &revision_path, &current_revision)
            .await?;
        let deleted = storage.search_index().search("newest", 10).await?;
        assert!(deleted
            .iter()
            .all(|entry| entry.session_id != "search-generation"));

        session = storage
            .recreate_root_session(&session.id, &session.model)
            .await?;
        session.title = "recreated searchable title".to_string();
        session.updated_at = Utc::now() + chrono::Duration::milliseconds(2);
        storage.save_session(&session).await?;
        storage.flush_search_index().await;
        storage
            .search_index()
            .delete_session_if_source_missing(&session.id, &revision_path)
            .await?;
        let recreated = storage.search_index().search("recreated", 10).await?;
        assert!(recreated
            .iter()
            .any(|entry| entry.session_id == "search-generation"));
        Ok(())
    }

    #[tokio::test]
    async fn search_rebuild_repairs_unchanged_snapshots_without_replacing_message_ids(
    ) -> io::Result<()> {
        let (storage, temp) = create_temp_storage().await?;
        let mut session = session_with_history("search-repair", 2, "run-a");
        session.title = "repairable beacon".into();
        session.messages[0].content = "repairable quartz".into();
        storage.save_session(&session).await?;
        storage.flush_search_index().await;
        let conn = rusqlite::Connection::open(storage.search_index().db_path()).unwrap();
        let identities = |conn: &rusqlite::Connection| {
            conn.prepare(
                "SELECT message_id, search_rowid FROM session_messages_search ORDER BY message_id",
            )
            .unwrap()
            .query_map([], |row| {
                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
            })
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap()
        };
        let before = identities(&conn);
        conn.execute_batch(
            "DELETE FROM sessions_search_fts;
            UPDATE session_messages_search_fts SET content='stale payload';",
        )
        .unwrap();
        drop(storage);

        // Reopen the store and run the same rebuild used by server startup.
        let reopened = SessionStoreV2::new(temp.path().to_path_buf()).await?;
        reopened.rebuild_search_index().await?;
        assert_eq!(identities(&conn), before);
        assert_eq!(reopened.search_index().search("beacon", 10).await?.len(), 1);
        assert_eq!(reopened.search_index().search("quartz", 10).await?.len(), 1);
        assert!(reopened
            .search_index()
            .search("stale", 10)
            .await?
            .is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn persistence_metrics_report_bounded_create_latency_percentiles() -> io::Result<()> {
        let (storage, _temp) = create_temp_storage().await?;
        for millis in [10, 20, 30, 40, 50] {
            storage.record_session_create_latency(Duration::from_millis(millis));
        }
        let metrics = storage.persistence_metrics();
        assert_eq!(metrics.create_latency.count, 5);
        assert_eq!(metrics.create_latency.p50_ms, 30);
        assert_eq!(metrics.create_latency.p95_ms, 50);
        assert_eq!(metrics.create_latency.max_ms, 50);
        Ok(())
    }

    #[tokio::test]
    async fn corrupt_child_sidecar_is_ignored_and_session_still_loads() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        let parent = Session::new("sc-parent", "test-model");
        storage.save_session(&parent).await?;
        let mut s = Session::new_child("sc-4", &parent.id, "test-model", "child");
        s.add_message(Message::user("msg-0"));
        s.add_message(Message::user("msg-1"));
        s.agent_runtime_state = Some(AgentRuntimeState::new("run-A"));
        storage.save_session(&s).await?;

        // Corrupt the sidecar.
        let sidecar_path = storage.runtime_json_path("sc-4").await?.unwrap();
        tokio::fs::write(&sidecar_path, b"{ not valid json").await?;

        // A Child still loads from session.json; its corrupt sidecar is ignored.
        let loaded = storage.load_session("sc-4").await?.unwrap();
        assert_eq!(loaded.messages.len(), 2);
        assert_eq!(loaded.agent_runtime_state.as_ref().unwrap().run_id, "run-A");
        Ok(())
    }

    #[tokio::test]
    async fn corrupt_index_is_backed_up_and_rebuilt_from_disk() -> io::Result<()> {
        // #342: a corrupt sessions.json must NOT be boot-fatal. On construction
        // the store backs it up to sessions.json.bak, rebuilds the index by
        // scanning the on-disk session tree, and every intact session.json (root
        // AND child) becomes reachable again.
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();

        // Persist a root and a child under it, then drop the store.
        {
            let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
            let root = Session::new("root-1", "m");
            storage.save_session(&root).await?;
            let child = Session::new_child_of("child-1", &root, "m", "c");
            storage.save_session(&child).await?;
        }

        // Corrupt the global index (truncated / invalid JSON).
        let index_path = bamboo_home.join("sessions.json");
        tokio::fs::write(&index_path, b"{ not valid json").await?;

        // (a) Re-opening on the same dir must SUCCEED, not hard-error.
        let recovered = SessionStoreV2::new(bamboo_home.clone()).await?;

        // (b) Both sessions are indexed again, with the correct rel_paths, so
        // they actually resolve + load from disk.
        assert_eq!(
            recovered.resolve_rel_path("root-1").await.as_deref(),
            Some("sessions/root-1"),
            "root must be recovered with its on-disk rel_path"
        );
        assert_eq!(
            recovered.resolve_rel_path("child-1").await.as_deref(),
            Some("sessions/root-1/children/child-1"),
            "child must be recovered with its on-disk rel_path"
        );
        assert!(
            recovered.get_index_entry("root-1").await.is_some(),
            "root index entry must exist after rebuild"
        );
        assert!(
            recovered.load_session("root-1").await?.is_some(),
            "recovered root must load from disk"
        );
        let loaded_child = recovered
            .load_session("child-1")
            .await?
            .expect("recovered child must load from disk");
        assert_eq!(loaded_child.parent_session_id.as_deref(), Some("root-1"));
        assert_eq!(loaded_child.root_session_id, "root-1");

        // (c) The corrupt index was preserved as sessions.json.bak, and a fresh
        // valid sessions.json was re-materialized.
        assert!(
            bamboo_home.join("sessions.json.bak").exists(),
            "corrupt sessions.json must be backed up to sessions.json.bak"
        );
        assert!(
            index_path.exists(),
            "a fresh sessions.json must be written after rebuild"
        );

        Ok(())
    }

    #[tokio::test]
    async fn v2_index_migrates_workspace_paths_from_root_and_child_sessions() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();

        {
            let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
            let mut root = Session::new("workspace-root", "m");
            root.set_workspace_path_meta("  /workspaces/root  ");
            storage.save_session(&root).await?;

            let mut child = Session::new_child_of("workspace-child", &root, "m", "child");
            child.set_workspace_path_meta("/workspaces/child");
            storage.save_session(&child).await?;

            let legacy_without_workspace = Session::new("workspace-missing", "m");
            storage.save_session(&legacy_without_workspace).await?;

            // A malformed sibling must not prevent recovery of intact sessions.
            let broken_dir = bamboo_home.join("sessions/broken");
            tokio::fs::create_dir_all(&broken_dir).await?;
            tokio::fs::write(broken_dir.join("session.json"), b"{ invalid json").await?;
        }

        let index_path = bamboo_home.join("sessions.json");
        let mut legacy: serde_json::Value =
            serde_json::from_slice(&tokio::fs::read(&index_path).await?)
                .map_err(|error| other_io_error(error.to_string()))?;
        legacy["version"] = serde_json::json!(2);
        for entry in legacy["sessions"]
            .as_object_mut()
            .expect("sessions object")
            .values_mut()
        {
            entry
                .as_object_mut()
                .expect("entry")
                .remove("workspace_path");
        }
        tokio::fs::write(
            &index_path,
            serde_json::to_vec_pretty(&legacy)
                .map_err(|error| other_io_error(error.to_string()))?,
        )
        .await?;

        let migrated = SessionStoreV2::new(bamboo_home.clone()).await?;
        assert_eq!(
            migrated
                .get_index_entry("workspace-root")
                .await
                .and_then(|entry| entry.workspace_path),
            Some("/workspaces/root".to_string())
        );
        assert_eq!(
            migrated
                .get_index_entry("workspace-child")
                .await
                .and_then(|entry| entry.workspace_path),
            Some("/workspaces/child".to_string())
        );
        assert!(migrated.get_index_entry("broken").await.is_none());
        assert_eq!(
            migrated
                .get_index_entry("workspace-missing")
                .await
                .and_then(|entry| entry.workspace_path),
            None
        );

        let persisted: SessionsIndex = serde_json::from_slice(&tokio::fs::read(index_path).await?)
            .map_err(|error| other_io_error(error.to_string()))?;
        assert_eq!(persisted.version, SESSIONS_INDEX_VERSION);
        Ok(())
    }

    #[tokio::test]
    async fn v3_index_migrates_project_ids_from_root_and_child_sessions() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();

        {
            let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
            let mut root = Session::new("project-root", "m");
            root.set_project_id_meta("01JROOTPROJECT00000000000000");
            storage.save_session(&root).await?;

            let mut child = Session::new_child_of("project-child", &root, "m", "child");
            child.metadata.insert(
                "project_id".to_string(),
                "01JCHILDPROJECT000000000000".to_string(),
            );
            storage.save_session(&child).await?;

            let unassigned = Session::new("project-unassigned", "m");
            storage.save_session(&unassigned).await?;
        }

        let index_path = bamboo_home.join("sessions.json");
        let mut legacy: serde_json::Value =
            serde_json::from_slice(&tokio::fs::read(&index_path).await?)
                .map_err(|error| other_io_error(error.to_string()))?;
        legacy["version"] = serde_json::json!(3);
        for entry in legacy["sessions"]
            .as_object_mut()
            .expect("sessions object")
            .values_mut()
        {
            entry.as_object_mut().expect("entry").remove("project_id");
        }
        tokio::fs::write(
            &index_path,
            serde_json::to_vec_pretty(&legacy)
                .map_err(|error| other_io_error(error.to_string()))?,
        )
        .await?;

        let migrated = SessionStoreV2::new(bamboo_home.clone()).await?;
        assert_eq!(
            migrated
                .get_index_entry("project-root")
                .await
                .and_then(|entry| entry.project_id),
            Some("01JROOTPROJECT00000000000000".to_string())
        );
        assert_eq!(
            migrated
                .get_index_entry("project-child")
                .await
                .and_then(|entry| entry.project_id),
            Some("01JCHILDPROJECT000000000000".to_string())
        );
        assert_eq!(
            migrated
                .get_index_entry("project-unassigned")
                .await
                .and_then(|entry| entry.project_id),
            None
        );

        let persisted: SessionsIndex = serde_json::from_slice(&tokio::fs::read(index_path).await?)
            .map_err(|error| other_io_error(error.to_string()))?;
        assert_eq!(persisted.version, SESSIONS_INDEX_VERSION);
        Ok(())
    }

    #[tokio::test]
    async fn workspace_path_updates_index_on_full_and_runtime_only_saves() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let mut session = Session::new("workspace-update", "m");
        session.set_workspace_path_meta("  /workspaces/first  ");
        storage.save_session(&session).await?;
        assert_eq!(
            storage
                .get_index_entry(&session.id)
                .await
                .and_then(|entry| entry.workspace_path),
            Some("/workspaces/first".to_string())
        );

        session.set_workspace_path_meta(" /workspaces/latest ");
        storage.save_runtime_state(&session).await?;
        assert_eq!(
            storage
                .get_index_entry(&session.id)
                .await
                .and_then(|entry| entry.workspace_path),
            Some("/workspaces/latest".to_string())
        );
        Ok(())
    }

    #[tokio::test]
    async fn project_id_updates_index_on_full_and_runtime_only_saves() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let mut session = Session::new("project-update", "m");
        session.set_project_id_meta(" 01JPROJECTFIRST000000000000 ");
        storage.save_session(&session).await?;
        assert_eq!(
            storage
                .get_index_entry(&session.id)
                .await
                .and_then(|entry| entry.project_id),
            Some("01JPROJECTFIRST000000000000".to_string())
        );

        session.set_project_id_meta(" 01JPROJECTLATEST00000000000 ");
        session.metadata_version += 1;
        storage.save_runtime_state(&session).await?;
        assert_eq!(
            storage
                .get_index_entry(&session.id)
                .await
                .and_then(|entry| entry.project_id),
            Some("01JPROJECTLATEST00000000000".to_string())
        );
        Ok(())
    }

    #[tokio::test]
    async fn malformed_legacy_project_id_isolated_from_session_index() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let mut malformed = Session::new("project-malformed", "m");
        malformed
            .metadata
            .insert("project_id".to_string(), "../unsafe".to_string());
        storage.save_session(&malformed).await?;

        let healthy = Session::new("project-healthy", "m");
        storage.save_session(&healthy).await?;

        assert_eq!(
            storage
                .get_index_entry(&malformed.id)
                .await
                .and_then(|entry| entry.project_id),
            None
        );
        assert!(storage.get_index_entry(&healthy.id).await.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn rebuild_overlays_runtime_sidecar_control_plane() -> io::Result<()> {
        // #342 review: rebuild must overlay runtime.json (the freshest
        // control-plane) on top of session.json, exactly like load_session.
        // A runtime-only save updates ONLY the sidecar, so a session that
        // completed that way must be recovered as "completed", not the stale
        // "running" still baked into session.json.
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();

        {
            let storage = SessionStoreV2::new(bamboo_home.clone()).await?;

            // Full save: session.json + sidecar both carry "running".
            let mut root = Session::new("rb-overlay", "m");
            root.metadata
                .insert("last_run_status".into(), "running".into());
            storage.save_session(&root).await?;

            // Runtime-only save: bump ONLY the sidecar to "completed".
            // session.json is left byte-identical (still "running").
            let mut updated = root.clone();
            updated
                .metadata
                .insert("last_run_status".into(), "completed".into());
            storage.save_runtime_state(&updated).await?;

            // Sanity: session.json on disk still carries the stale status.
            let raw = read_session_json_raw(&storage, "rb-overlay").await;
            assert!(
                raw.contains("running"),
                "session.json must still carry the pre-sidecar status"
            );
        }

        // Corrupt the index, then reopen → triggers rebuild-from-disk.
        tokio::fs::write(bamboo_home.join("sessions.json"), b"{ not valid json").await?;
        let recovered = SessionStoreV2::new(bamboo_home.clone()).await?;

        // The rebuilt index entry must reflect the SIDECAR's fresh "completed",
        // NOT session.json's stale "running". Without the overlay fix the rebuild
        // reads session.json only and this is "running", so the test fails.
        let entry = recovered
            .get_index_entry("rb-overlay")
            .await
            .expect("root recovered into rebuilt index");
        assert_eq!(
            entry.last_run_status.as_deref(),
            Some("completed"),
            "rebuild must overlay runtime.json control-plane, not the stale session.json"
        );
        Ok(())
    }

    #[tokio::test]
    async fn missing_index_starts_empty_and_does_not_back_up() -> io::Result<()> {
        // A *missing* sessions.json keeps the fresh-empty-index behavior: no
        // rebuild is triggered and no sessions.json.bak is produced.
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();

        let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
        assert!(storage.list_index_entries().await.is_empty());
        assert!(
            !bamboo_home.join("sessions.json.bak").exists(),
            "a missing index must not produce a .bak backup"
        );
        Ok(())
    }

    #[tokio::test]
    async fn fresh_constructor_waits_for_index_claim_then_reloads_published_index() -> io::Result<()>
    {
        // Prepare valid index bytes containing one entry without pre-populating
        // the fresh target directory used by the race below.
        let seed_dir = TempDir::new().map_err(io::Error::other)?;
        let seed_store = SessionStoreV2::new(seed_dir.path().to_path_buf()).await?;
        let seeded = Session::new("init-race-survivor", "test-model");
        seed_store.save_session(&seeded).await?;
        let seeded_index = fs::read(seed_dir.path().join("sessions.json")).await?;

        let target_dir = TempDir::new().map_err(io::Error::other)?;
        let target_home = target_dir.path().to_path_buf();
        let claim = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(target_home.join(SESSION_INDEX_LOCK_FILE))?;
        FileExt::lock_exclusive(&claim)?;

        let contender_home = target_home.clone();
        let mut contender = tokio::spawn(async move { SessionStoreV2::new(contender_home).await });
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(100), &mut contender)
                .await
                .is_err(),
            "fresh initialization must inspect and publish only after acquiring the index claim"
        );

        // Simulate the process currently owning the claim publishing an index
        // between the contender's start and its eventual inspection.
        fs::write(target_home.join("sessions.json"), seeded_index).await?;
        FileExt::unlock(&claim)?;

        let storage = tokio::time::timeout(std::time::Duration::from_secs(2), contender)
            .await
            .map_err(io::Error::other)?
            .map_err(io::Error::other)??;
        assert!(storage
            .get_index_entry("init-race-survivor")
            .await
            .is_some());
        let persisted: SessionsIndex =
            serde_json::from_slice(&fs::read(target_home.join("sessions.json")).await?)
                .map_err(io::Error::other)?;
        assert!(persisted.sessions.contains_key("init-race-survivor"));
        Ok(())
    }

    // ── ⑤ Runtime sidecar migration ──────────────────────────────────────

    #[tokio::test]
    async fn migration_backfills_sidecars_for_legacy_children() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let storage = SessionStoreV2::new(bamboo_home.clone()).await?;

        // Child migration remains compatible. A main-only Root is ambiguous
        // and cannot establish a current Project revision through migration.
        let parent = Session::new("migration-root", "model");
        storage.save_session(&parent).await?;
        let mut a = Session::new_child("mig-a", &parent.id, "model", "child");
        a.messages = session_with_history("history-a", 3, "run-A").messages;
        a.agent_runtime_state = Some(AgentRuntimeState::new("run-A"));
        let mut b = Session::new_child("mig-b", &parent.id, "model", "child");
        b.messages = session_with_history("history-b", 1, "run-B").messages;
        b.agent_runtime_state = Some(AgentRuntimeState::new("run-B"));
        storage.save_session(&a).await?;
        storage.save_session(&b).await?;
        for id in ["mig-a", "mig-b"] {
            let sidecar = storage.runtime_json_path(id).await?.unwrap();
            tokio::fs::remove_file(&sidecar).await?;
            assert!(!sidecar.exists());
        }

        let migrated = storage.migrate_runtime_sidecars().await?;
        assert_eq!(migrated, 2, "both legacy sessions get a sidecar");

        // Sidecars now exist and carry the control-plane (no messages).
        for (id, run) in [("mig-a", "run-A"), ("mig-b", "run-B")] {
            let side = storage.read_runtime_sidecar(id).await?.unwrap();
            assert!(side.messages.is_empty());
            assert_eq!(side.agent_runtime_state.as_ref().unwrap().run_id, run);
        }
        // Full load still returns the messages from session.json.
        assert_eq!(
            storage.load_session("mig-a").await?.unwrap().messages.len(),
            3
        );

        // Marker written; a second run is a no-op.
        let marker = bamboo_home.join(RUNTIME_SIDECAR_MIGRATION_MARKER);
        assert!(marker.exists());
        assert_eq!(storage.migrate_runtime_sidecars().await?, 0);
        Ok(())
    }

    #[tokio::test]
    async fn migration_is_idempotent_and_skips_existing_sidecars() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        // Fresh save already writes a sidecar — migration must not double-count it.
        storage
            .save_session(&session_with_history("mig-c", 2, "run-C"))
            .await?;
        let first = storage.migrate_runtime_sidecars().await?;
        assert_eq!(first, 0, "session saved in new format needs no migration");
        // And a re-run remains a no-op.
        assert_eq!(storage.migrate_runtime_sidecars().await?, 0);
        Ok(())
    }

    #[tokio::test]
    async fn migration_drops_legacy_denormalized_children_from_sidecar() -> io::Result<()> {
        // A legacy session.json whose embedded runtime state still carries the
        // old denormalized children id vectors. After migration the sidecar must
        // not contain them (they are now derived from the index).
        let (storage, _t) = create_temp_storage().await?;
        let parent = Session::new("migration-root", "model");
        storage.save_session(&parent).await?;
        let mut s = Session::new_child("mig-legacy", &parent.id, "model", "child");
        s.messages = session_with_history("history-legacy", 1, "run-L").messages;
        s.agent_runtime_state = Some(AgentRuntimeState::new("run-L"));
        storage.save_session(&s).await?;

        // Hand-write a legacy session.json containing children.active_ids and
        // remove the sidecar, simulating pre-split on-disk data.
        let dir = storage.abs_path_from_rel(&storage.resolve_rel_path("mig-legacy").await.unwrap());
        s.agent_runtime_state = Some(AgentRuntimeState::new("run-L"));
        let mut value = serde_json::to_value(&s).unwrap();
        value["agent_runtime_state"]["children"]["active_ids"] = serde_json::json!(["ghost-child"]);
        tokio::fs::write(
            dir.join("session.json"),
            serde_json::to_vec_pretty(&value).unwrap(),
        )
        .await?;
        tokio::fs::remove_file(storage.runtime_json_path("mig-legacy").await?.unwrap()).await?;

        assert_eq!(storage.migrate_runtime_sidecars().await?, 1);

        let raw_sidecar =
            tokio::fs::read_to_string(storage.runtime_json_path("mig-legacy").await?.unwrap())
                .await?;
        assert!(
            !raw_sidecar.contains("ghost-child") && !raw_sidecar.contains("active_ids"),
            "legacy denormalized children must not survive migration: {raw_sidecar}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn list_child_run_statuses_filters_by_parent_and_reports_status() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;

        // Parent root + two children with distinct statuses, plus an unrelated
        // child under a different parent that must NOT appear.
        let parent = Session::new("p-root".to_string(), "m".to_string());
        storage.save_session(&parent).await?;
        let other = Session::new("p-other".to_string(), "m".to_string());
        storage.save_session(&other).await?;

        let mut c1 = Session::new_child("ch-done", "p-root", "m", "c1");
        c1.metadata
            .insert("last_run_status".to_string(), "completed".to_string());
        storage.save_session(&c1).await?;

        let c2 = Session::new_child("ch-pending", "p-root", "m", "c2");
        storage.save_session(&c2).await?;

        let foreign = Session::new_child("ch-foreign", "p-other", "m", "x");
        storage.save_session(&foreign).await?;

        let mut got = storage.list_child_run_statuses("p-root").await?;
        got.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(got.len(), 2, "only p-root's children: {got:?}");
        assert_eq!(got[0].0, "ch-done");
        assert_eq!(got[0].1.as_deref(), Some("completed"));
        assert_eq!(got[1].0, "ch-pending");
        // pending child has no terminal status mirrored yet.
        assert!(got[1].1.as_deref() != Some("completed"));
        Ok(())
    }

    #[tokio::test]
    async fn list_sessions_by_run_status_matches_index_and_reports_parent() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;

        let mut root = Session::new("r-susp".to_string(), "m".to_string());
        root.metadata
            .insert("last_run_status".to_string(), "suspended".to_string());
        storage.save_session(&root).await?;

        let mut child = Session::new_child("ch-run", "r-susp", "m", "c");
        child
            .metadata
            .insert("last_run_status".to_string(), "running".to_string());
        storage.save_session(&child).await?;

        let mut done = Session::new("r-done".to_string(), "m".to_string());
        done.metadata
            .insert("last_run_status".to_string(), "completed".to_string());
        storage.save_session(&done).await?;

        let suspended = storage.list_sessions_by_run_status("suspended").await?;
        assert_eq!(suspended, vec![("r-susp".to_string(), None)]);

        let running = storage.list_sessions_by_run_status("running").await?;
        assert_eq!(
            running,
            vec![("ch-run".to_string(), Some("r-susp".to_string()))]
        );

        assert!(storage
            .list_sessions_by_run_status("timeout")
            .await?
            .is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn load_runtime_control_plane_reads_sidecar_without_messages() -> io::Result<()> {
        let (storage, _t) = create_temp_storage().await?;
        let s = session_with_history("sc-5", 5, "run-A");
        storage.save_session(&s).await?;

        let cp = storage.load_runtime_control_plane("sc-5").await?.unwrap();
        assert!(
            cp.messages.is_empty(),
            "control-plane load must skip the message history"
        );
        assert_eq!(cp.agent_runtime_state.as_ref().unwrap().run_id, "run-A");
        Ok(())
    }

    #[tokio::test]
    async fn test_save_and_load_session() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let session = Session::new("session-1", "test-model");

        storage.save_session(&session).await?;
        let loaded = storage.load_session(&session.id).await?;

        assert!(loaded.is_some());
        let loaded = loaded.unwrap();
        assert_eq!(loaded.id, session.id);
        assert_eq!(loaded.model, session.model);

        Ok(())
    }

    #[tokio::test]
    async fn recover_root_session_repairs_missing_global_index_from_authoritative_file(
    ) -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let session = Session::new("ambiguous-create", "test-model");
        storage.save_session(&session).await?;

        storage
            .update_index(|index| {
                index.sessions.remove(&session.id);
                Ok(())
            })
            .await?;
        assert!(storage.get_index_entry(&session.id).await.is_none());
        let error = storage.load_session(&session.id).await.unwrap_err();
        assert!(error
            .get_ref()
            .is_some_and(|cause| cause.is::<bamboo_domain::SessionAuthorityConflict>()));

        let recovered = storage
            .recover_root_session_from_disk(&session.id)
            .await?
            .expect("authoritative session.json must survive index loss");
        assert_eq!(recovered.id, session.id);
        assert!(storage.get_index_entry(&session.id).await.is_some());
        assert!(storage.load_session(&session.id).await?.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn authoritative_recovery_repairs_path_without_regressing_newer_index_fields(
    ) -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let session = Session::new("ambiguous-newer-index", "test-model");
        storage.save_session(&session).await?;
        let newer_at = session.updated_at + chrono::Duration::hours(1);
        storage
            .update_index(|index| {
                let entry = index.sessions.get_mut(&session.id).unwrap();
                entry.title = "newer-live-title".to_string();
                entry.updated_at = newer_at;
                entry.rel_path = "sessions/wrong-root".to_string();
                Ok(())
            })
            .await?;

        storage
            .recover_root_session_from_disk(&session.id)
            .await?
            .expect("authoritative root remains available");
        let repaired = storage.get_index_entry(&session.id).await.unwrap();
        assert_eq!(repaired.rel_path, format!("sessions/{}", session.id));
        assert_eq!(repaired.title, "newer-live-title");
        assert_eq!(repaired.updated_at, newer_at);
        assert_eq!(repaired.kind, SessionKind::Root);
        assert_eq!(repaired.root_session_id, session.id);
        Ok(())
    }

    #[tokio::test]
    async fn rebuild_entry_waits_for_delete_and_does_not_resurrect_removed_session(
    ) -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let storage =
            std::sync::Arc::new(SessionStoreV2::new(temp_dir.path().to_path_buf()).await?);
        let session = Session::new("rebuild-delete-race", "test-model");
        storage.save_session(&session).await?;
        let abs_dir = storage.sessions_dir.join(&session.id);
        let rel_path = SessionStoreV2::root_rel_path(&session.id);

        let delete_claim = storage.lock_session_lifecycle_exclusive().await?;
        let rebuilding = std::sync::Arc::clone(&storage);
        let session_id = session.id.clone();
        let mut late_rebuild = tokio::spawn(async move {
            rebuilding
                .rebuild_index_entry_from_dir(&abs_dir, &session_id, rel_path)
                .await
        });
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(50), &mut late_rebuild)
                .await
                .is_err(),
            "rebuild probe must wait behind the exclusive delete lifecycle claim"
        );

        fs::remove_dir_all(storage.sessions_dir.join(&session.id)).await?;
        storage
            .update_index(|index| {
                index.sessions.remove(&session.id);
                Ok(())
            })
            .await?;
        drop(delete_claim);

        assert!(!late_rebuild.await.map_err(io::Error::other)??);
        assert!(storage.get_index_entry(&session.id).await.is_none());
        let persisted: SessionsIndex =
            serde_json::from_slice(&fs::read(storage.index_path()).await?)
                .map_err(io::Error::other)?;
        assert!(!persisted.sessions.contains_key(&session.id));
        Ok(())
    }

    #[tokio::test]
    async fn recover_root_session_does_not_treat_corrupt_authoritative_file_as_missing(
    ) -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let session = Session::new("ambiguous-corrupt-create", "test-model");
        storage.save_session(&session).await?;
        fs::write(
            storage.sessions_dir.join(&session.id).join("session.json"),
            b"not-json",
        )
        .await?;

        let error = storage
            .recover_root_session_from_disk(&session.id)
            .await
            .expect_err("corrupt authoritative data must remain retryable, not look deleted");
        assert!(error
            .to_string()
            .contains("invalid authoritative session.json"));
        Ok(())
    }

    #[tokio::test]
    async fn independent_store_index_updates_rebase_without_losing_entries() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        // Construct both before either write so the second instance starts with
        // the exact stale empty snapshot that previously lost the first entry.
        let first = SessionStoreV2::new(bamboo_home.clone()).await?;
        let second = SessionStoreV2::new(bamboo_home.clone()).await?;
        let first_session = Session::new("cross-process-index-first", "test-model");
        let second_session = Session::new("cross-process-index-second", "test-model");

        first.save_session(&first_session).await?;
        second.save_session(&second_session).await?;

        let persisted: SessionsIndex =
            serde_json::from_slice(&fs::read(bamboo_home.join("sessions.json")).await?)
                .map_err(io::Error::other)?;
        assert!(persisted.sessions.contains_key(&first_session.id));
        assert!(persisted.sessions.contains_key(&second_session.id));

        let reopened = SessionStoreV2::new(bamboo_home).await?;
        assert!(reopened.get_index_entry(&first_session.id).await.is_some());
        assert!(reopened.get_index_entry(&second_session.id).await.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn test_load_session_returns_none_when_not_found() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let loaded = storage.load_session("nonexistent").await?;
        assert!(loaded.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn nested_grandchild_persists_under_root() -> io::Result<()> {
        // Nesting: a grandchild whose parent is itself a child (parent != root)
        // must persist (previously rejected with "no nesting") and load back
        // with its real parent lineage. All descendants live flat under the
        // tree root's directory.
        let (storage, _t) = create_temp_storage().await?;
        let root = Session::new("root-1", "m");
        storage.save_session(&root).await?;
        let child = Session::new_child_of("child-1", &root, "m", "c");
        storage.save_session(&child).await?;
        let grandchild = Session::new_child_of("gc-1", &child, "m", "g");
        storage.save_session(&grandchild).await?;

        let loaded = storage.load_session("gc-1").await?.expect("grandchild");
        assert_eq!(loaded.parent_session_id.as_deref(), Some("child-1"));
        assert_eq!(loaded.root_session_id, "root-1");
        assert_eq!(loaded.spawn_depth, 2);

        // The grandchild is indexed under the tree root, keyed by its real parent.
        let entry = storage.get_index_entry("gc-1").await.expect("indexed");
        assert_eq!(entry.parent_session_id.as_deref(), Some("child-1"));
        assert_eq!(entry.root_session_id, "root-1");
        Ok(())
    }

    #[tokio::test]
    async fn test_list_index_entries_empty() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let entries = storage.list_index_entries().await;
        assert!(entries.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn test_list_index_entries_with_sessions() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;

        let session1 = Session::new("session-1", "model-1");
        let session2 = Session::new("session-2", "model-2");

        storage.save_session(&session1).await?;
        storage.save_session(&session2).await?;

        let entries = storage.list_index_entries().await;
        assert_eq!(entries.len(), 2);

        Ok(())
    }

    #[tokio::test]
    async fn test_get_index_entry() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let session = Session::new("session-1", "test-model");

        storage.save_session(&session).await?;

        let entry = storage.get_index_entry(&session.id).await;
        assert!(entry.is_some());
        let entry = entry.unwrap();
        assert_eq!(entry.id, session.id);

        Ok(())
    }

    #[tokio::test]
    async fn test_get_index_entry_returns_none_when_not_found() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let entry = storage.get_index_entry("nonexistent").await;
        assert!(entry.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn copy_session_creates_independent_root_and_copies_attachments() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let root = Session::new("root-source", "model");
        storage.save_session(&root).await?;
        let mut source = Session::new_child("child-source", &root.id, "gpt-5", "Research");
        source.pinned = true;
        source.model_ref = Some(ProviderModelRef::new("openai-instance", "gpt-5"));
        source.reasoning_effort = Some(ReasoningEffort::High);
        source.set_project_id_meta("project-1");
        source.set_workspace_path_meta("/workspaces/project-1");
        source.set_provider_name("openai-instance");
        source
            .metadata
            .insert("base_system_prompt".into(), "You are exact.".into());
        source.set_pending_question(
            "call-1".into(),
            "Question".into(),
            "Proceed?".into(),
            vec![],
            true,
        );
        source.set_last_run_status("running");
        source.set_last_run_error("old failure");
        source.set_pending_injected_messages(vec![serde_json::json!({"content":"queued"})]);
        source
            .metadata
            .insert("gold_config".into(), r#"{"goal":"ship"}"#.into());
        source
            .metadata
            .insert("a2a.context_id".into(), "remote-context".into());
        source
            .metadata
            .insert("created_by_schedule_id".into(), "schedule-1".into());
        source
            .metadata
            .insert("assignment_prompt".into(), "child-only".into());
        source
            .metadata
            .insert("goal.state".into(), r#"{"status":"active"}"#.into());
        source
            .metadata
            .insert("permission.audit_revision".into(), "42".into());
        source
            .metadata
            .insert("runtime_prompt_snapshot".into(), "stale".into());
        source
            .metadata
            .insert("workflow.run_ids.v1".into(), "[]".into());
        source.metadata.insert(
            "workflow.selection.v1".into(),
            r#"{"id":"review","source":"user","revision":1,"args":{}}"#.into(),
        );
        source
            .metadata
            .insert("workflow.orchestration_opt_in".into(), "true".into());
        source
            .metadata
            .insert("workflow.active.v1".into(), "stale-active".into());
        source.metadata.insert(
            "workflow.active.snapshot.v1".into(),
            "durable-snapshot".into(),
        );
        source
            .metadata
            .insert("workflow.activation_event.v1".into(), "stale-event".into());
        source.metadata.insert(
            "skill_runtime_selected_skill_ids".into(),
            r#"["stale"]"#.into(),
        );
        source
            .metadata
            .insert("selected_skill_ids".into(), r#"["review"]"#.into());
        source.metadata.insert("skill_mode".into(), "code".into());
        source
            .metadata
            .insert("workspace_source".into(), "project_default".into());
        source.metadata.insert(
            "execute.pending_turn_message_id".into(),
            "message-old".into(),
        );
        source
            .metadata
            .insert("context_pressure_last_level".into(), "high".into());
        source
            .metadata
            .insert("permission.reexecute_tool_call_id".into(), "call-1".into());
        source.metadata.insert(
            "permission.reexecute_request_generation".into(),
            "generation-call-1".into(),
        );
        source
            .metadata
            .insert("prefix_cache_section_state".into(), "stale".into());
        source
            .metadata
            .insert("llm_request_render".into(), "stale".into());
        source
            .metadata
            .insert("custom.copy_config".into(), "preserve-me".into());
        source.task_list = Some(transaction_task_list(&source.id, "Source tasks"));
        source.set_task_list_version_meta("7");
        source.token_budget = Some(bamboo_domain::TokenBudget::for_model(1024));
        source.token_usage = Some(TokenBudgetUsage {
            system_tokens: 1,
            summary_tokens: 2,
            window_tokens: 3,
            total_tokens: 6,
            max_context_tokens: 1024,
            budget_limit: 900,
            truncation_occurred: false,
            segments_removed: 0,
            prompt_cached_tool_outputs: 0,
            prompt_cached_tool_tokens_saved: 0,
            thinking_tokens: 0,
            cache_read_input_tokens: 0,
            provider_prompt_usage: None,
        });
        source.agent_runtime_state = Some(bamboo_domain::AgentRuntimeState::new("run-1"));
        source
            .agent_runtime_state
            .as_mut()
            .unwrap()
            .set_permission_mode(bamboo_domain::SessionPermissionMode::Auto);
        storage.save_session(&source).await?;

        let (attachment_id, attachment_url) = storage
            .write_image_attachment(&source, "data:image/png;base64,aGVsbG8=", Some("image/png"))
            .await?;
        let mut message = Message::user_with_parts(
            "look",
            vec![MessagePart::ImageUrl {
                image_url: ImageUrlRef {
                    url: attachment_url.clone(),
                    detail: None,
                },
            }],
        );
        message.image_ocr = Some(vec![ImageOcrResult {
            image_url: attachment_url,
            lines: vec![],
            error: None,
        }]);
        source.add_message(message);
        storage.save_session(&source).await?;
        let source_before = serde_json::to_value(&source).expect("serialize source snapshot");

        let copied = storage
            .copy_session(&source.id, "copy-root")
            .await?
            .expect("source exists");
        assert_eq!(copied.kind, SessionKind::Root);
        assert_eq!(copied.id, "copy-root");
        assert_eq!(copied.root_session_id, "copy-root");
        assert!(copied.parent_session_id.is_none());
        assert_eq!(copied.spawn_depth, 0);
        assert_eq!(copied.title, "Research (copy)");
        assert!(copied.title_generated);
        assert!(!copied.pinned);
        assert_eq!(copied.model_ref, source.model_ref);
        assert_eq!(copied.project_id_meta().as_deref(), Some("project-1"));
        assert_eq!(
            copied.workspace_path_meta().as_deref(),
            Some("/workspaces/project-1")
        );
        assert_eq!(copied.provider_name().as_deref(), Some("openai-instance"));
        assert_eq!(copied.reasoning_effort, Some(ReasoningEffort::High));
        assert_eq!(
            copied
                .metadata
                .get("base_system_prompt")
                .map(String::as_str),
            Some("You are exact.")
        );
        assert_eq!(
            copied.metadata.get("gold_config").map(String::as_str),
            Some(r#"{"goal":"ship"}"#)
        );
        assert!(!copied.has_pending_question());
        assert!(copied.last_run_status().is_none());
        assert!(copied.last_run_error().is_none());
        assert!(!copied.has_pending_injected_messages());
        assert!(!copied.metadata.contains_key("a2a.context_id"));
        assert!(!copied.metadata.contains_key("created_by_schedule_id"));
        assert!(!copied.metadata.contains_key("assignment_prompt"));
        assert!(!copied.metadata.contains_key("goal.state"));
        assert!(!copied.metadata.contains_key("permission.audit_revision"));
        assert!(!copied.metadata.contains_key("runtime_prompt_snapshot"));
        assert!(!copied.metadata.contains_key("workflow.run_ids.v1"));
        assert_eq!(
            copied.metadata.get("workflow.active.v1"),
            Some(&"stale-active".to_string())
        );
        assert_eq!(
            copied.metadata.get("workflow.active.snapshot.v1"),
            Some(&"durable-snapshot".to_string())
        );
        assert!(!copied.metadata.contains_key("workflow.activation_event.v1"));
        assert_eq!(
            copied.metadata.get("workflow.selection.v1"),
            source.metadata.get("workflow.selection.v1")
        );
        assert_eq!(
            copied.metadata.get("workflow.orchestration_opt_in"),
            Some(&"true".to_string())
        );
        assert!(!copied
            .metadata
            .contains_key("skill_runtime_selected_skill_ids"));
        assert_eq!(
            copied.metadata.get("selected_skill_ids"),
            Some(&r#"["review"]"#.to_string())
        );
        assert_eq!(copied.metadata.get("skill_mode"), Some(&"code".to_string()));
        assert_eq!(
            copied.metadata.get("workspace_source"),
            Some(&"project_default".to_string())
        );
        for key in [
            "execute.pending_turn_message_id",
            "context_pressure_last_level",
            "permission.reexecute_tool_call_id",
            "permission.reexecute_request_generation",
            "prefix_cache_section_state",
            "llm_request_render",
        ] {
            assert!(!copied.metadata.contains_key(key), "{key} must be cleared");
        }
        assert_eq!(
            copied.metadata.get("custom.copy_config"),
            Some(&"preserve-me".to_string())
        );
        assert!(copied.token_budget.is_none());
        assert!(copied.token_usage.is_none());
        assert!(copied.task_list.is_none());
        assert!(copied.task_list_version_meta().is_none());
        assert!(copied.prompt_snapshot.is_none());
        assert!(copied.model_context_state.is_none());
        assert_eq!(
            copied
                .agent_runtime_state
                .as_ref()
                .unwrap()
                .effective_permission_mode(),
            bamboo_domain::SessionPermissionMode::Auto
        );
        assert!(copied
            .agent_runtime_state
            .as_ref()
            .unwrap()
            .run_id
            .is_empty());
        let copied_url = match &copied
            .messages
            .last()
            .unwrap()
            .content_parts
            .as_ref()
            .unwrap()[0]
        {
            MessagePart::ImageUrl { image_url } => image_url.url.as_str(),
            _ => panic!("expected image"),
        };
        assert_eq!(
            copied_url,
            format!("bamboo-attachment://copy-root/{attachment_id}")
        );
        assert_eq!(
            copied.messages.last().unwrap().image_ocr.as_ref().unwrap()[0].image_url,
            format!("bamboo-attachment://copy-root/{attachment_id}")
        );
        assert_eq!(
            storage
                .read_attachment("copy-root", &attachment_id)
                .await?
                .expect("copied attachment")
                .0,
            b"hello"
        );
        let source_after_copy = storage
            .load_session(&source.id)
            .await?
            .expect("source remains after copy");
        assert_eq!(
            serde_json::to_value(source_after_copy).expect("serialize source after copy"),
            source_before
        );

        storage.delete_session(&source.id).await?;
        assert!(storage
            .read_attachment("copy-root", &attachment_id)
            .await?
            .is_some());
        assert!(storage.load_session("copy-root").await?.is_some());
        let parent_after = storage
            .load_session("root-source")
            .await?
            .expect("unrelated parent remains");
        assert_eq!(parent_after.id, root.id);
        Ok(())
    }

    #[tokio::test]
    async fn concurrent_copy_requests_create_independent_sessions() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let storage = Arc::new(SessionStoreV2::new(bamboo_home).await?);
        let mut source = Session::new("copy-source", "model");
        source.add_message(Message::user("same snapshot"));
        storage.save_session(&source).await?;

        let first_store = storage.clone();
        let second_store = storage.clone();
        let (first, second) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
            tokio::join!(
                async move { first_store.copy_session("copy-source", "copy-one").await },
                async move { second_store.copy_session("copy-source", "copy-two").await }
            )
        })
        .await
        .expect("projection guards must be released before concurrent copy returns");
        let first = first?.expect("first copy");
        let second = second?.expect("second copy");
        assert_ne!(first.id, second.id);
        assert_eq!(first.messages.len(), source.messages.len());
        assert_eq!(second.messages.len(), source.messages.len());
        assert!(storage.get_index_entry(&first.id).await.is_some());
        assert!(storage.get_index_entry(&second.id).await.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn copy_session_missing_source_leaves_no_target() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        assert!(storage
            .copy_session("missing", "copy-root")
            .await?
            .is_none());
        assert!(storage.get_index_entry("copy-root").await.is_none());
        assert!(!storage.sessions_root_dir().join("copy-root").exists());
        Ok(())
    }

    #[tokio::test]
    async fn copy_session_rolls_back_directory_when_index_publish_fails() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let source = Session::new("copy-source", "model");
        storage.save_session(&source).await?;

        // Force the copy to fail after its fully-written staging directory has
        // been renamed, but before a visible index entry can be committed.
        fs::write(storage.index_path(), b"{not valid json").await?;
        let error = storage
            .copy_session(&source.id, "copy-root")
            .await
            .expect_err("corrupt index must fail publication");
        assert!(error.to_string().contains("invalid sessions.json"));
        assert!(storage.get_index_entry("copy-root").await.is_none());
        assert!(!storage.sessions_root_dir().join("copy-root").exists());
        assert_eq!(storage.session_copy_journal_paths().await?.len(), 1);
        let mut home_entries = fs::read_dir(storage.bamboo_home_dir()).await?;
        while let Some(entry) = home_entries.next_entry().await? {
            let name = entry.file_name().to_string_lossy().into_owned();
            assert!(
                !name.starts_with(".session-copy-") || name == SESSION_COPY_TRANSACTION_DIR,
                "staging directory leaked after rollback: {name}"
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn copy_session_rejects_corrupt_source_main_and_runtime_sidecar() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let source = Session::new("copy-source", "model");
        storage.save_session(&source).await?;
        let source_dir = storage.sessions_root_dir().join(&source.id);
        let main_path = source_dir.join("session.json");
        let before_main = fs::read(&main_path).await?;

        fs::write(&main_path, b"not-json").await?;
        let error = storage
            .copy_session(&source.id, "copy-main-corrupt")
            .await
            .expect_err("corrupt authoritative source must fail");
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(storage.get_index_entry("copy-main-corrupt").await.is_none());

        // A corrupt Root main cannot be republished from runtime alone.
        // Restore independently recorded bytes before testing sidecar damage.
        fs::write(&main_path, before_main).await?;
        fs::write(source_dir.join(RUNTIME_SIDECAR_FILE), b"not-json").await?;
        let error = storage
            .copy_session(&source.id, "copy-sidecar-corrupt")
            .await
            .expect_err("corrupt source sidecar must fail instead of copying stale state");
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(storage
            .get_index_entry("copy-sidecar-corrupt")
            .await
            .is_none());
        Ok(())
    }

    #[tokio::test]
    async fn copy_session_rejects_noncanonical_or_mismatched_index_identity() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let source = Session::new("copy-source", "model");
        storage.save_session(&source).await?;

        storage
            .update_index(|index| {
                index
                    .sessions
                    .get_mut(&source.id)
                    .expect("source index")
                    .rel_path = "sessions/another-root".to_string();
                Ok(())
            })
            .await?;
        let error = storage
            .copy_session(&source.id, "copy-target")
            .await
            .expect_err("noncanonical indexed source path must fail closed");
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(storage.get_index_entry("copy-target").await.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn copy_session_accepts_legacy_root_without_root_session_id() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let source = Session::new("legacy-root", "model");
        storage.save_session(&source).await?;
        let source_dir = storage.sessions_root_dir().join(&source.id);

        for filename in ["session.json", RUNTIME_SIDECAR_FILE] {
            let path = source_dir.join(filename);
            let mut value: serde_json::Value =
                serde_json::from_slice(&fs::read(&path).await?).map_err(io::Error::other)?;
            let fields = value.as_object_mut().expect("session snapshot object");
            // Actual legacy Main has no compact section; Runtime remains legacy.
            fields.remove(compact_main::MEMBER);
            fields.remove("root_session_id");
            fs::write(
                path,
                serde_json::to_vec_pretty(&value).map_err(io::Error::other)?,
            )
            .await?;
        }

        let copied = storage
            .copy_session(&source.id, "legacy-root-copy")
            .await?
            .expect("legacy root remains copyable");
        assert_eq!(copied.id, "legacy-root-copy");
        assert_eq!(copied.kind, SessionKind::Root);
        assert_eq!(copied.root_session_id, copied.id);
        assert!(storage.get_index_entry("legacy-root-copy").await.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn startup_rolls_back_prepared_session_copy_transaction() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
        let source = Session::new("copy-source", "model");
        storage.save_session(&source).await?;
        let copied = storage
            .copy_session(&source.id, "copy-target")
            .await?
            .expect("copy succeeds");
        let journal = SessionCopyTransactionJournal {
            version: SESSION_COPY_TRANSACTION_VERSION,
            transaction_id: Uuid::new_v4().to_string(),
            source_id: source.id.clone(),
            target_id: copied.id.clone(),
        };
        storage.write_session_copy_journal(&journal).await?;
        drop(storage);

        let reopened = SessionStoreV2::new(bamboo_home).await?;
        assert!(reopened.get_index_entry(&copied.id).await.is_none());
        assert!(!reopened.sessions_root_dir().join(&copied.id).exists());
        assert!(reopened.session_copy_journal_paths().await?.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn startup_finishes_committed_session_copy_transaction() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
        let source = Session::new("copy-source", "model");
        storage.save_session(&source).await?;
        let copied = storage
            .copy_session(&source.id, "copy-target")
            .await?
            .expect("copy succeeds");
        let journal = SessionCopyTransactionJournal {
            version: SESSION_COPY_TRANSACTION_VERSION,
            transaction_id: Uuid::new_v4().to_string(),
            source_id: source.id.clone(),
            target_id: copied.id.clone(),
        };
        let prepared = storage.write_session_copy_journal(&journal).await?;
        let committed = prepared.with_extension("committed");
        atomic_rename(&prepared, &committed).await?;
        sync_parent_directory_entry(&committed).await?;
        storage
            .update_index(|index| {
                index.sessions.remove(&copied.id);
                Ok(())
            })
            .await?;
        drop(storage);

        let reopened = SessionStoreV2::new(bamboo_home).await?;
        assert!(reopened.get_index_entry(&copied.id).await.is_some());
        assert!(reopened.load_session(&copied.id).await?.is_some());
        assert!(reopened.session_copy_journal_paths().await?.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn delete_recovers_retained_committed_copy_marker_before_removal() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let bamboo_home = temp_dir.path().to_path_buf();
        let storage = SessionStoreV2::new(bamboo_home.clone()).await?;
        let source = Session::new("copy-source", "model");
        storage.save_session(&source).await?;
        let copied = storage
            .copy_session(&source.id, "copy-target")
            .await?
            .expect("copy succeeds");

        // Model a successful copy whose post-commit marker deactivation was
        // interrupted. Deletion must settle that marker before removing the
        // target so restart cannot resurrect it or fail on a missing target.
        let journal = SessionCopyTransactionJournal {
            version: SESSION_COPY_TRANSACTION_VERSION,
            transaction_id: Uuid::new_v4().to_string(),
            source_id: source.id.clone(),
            target_id: copied.id.clone(),
        };
        let prepared = storage.write_session_copy_journal(&journal).await?;
        let committed = prepared.with_extension("committed");
        atomic_rename(&prepared, &committed).await?;
        sync_parent_directory_entry(&committed).await?;

        assert!(storage.delete_session(&copied.id).await?);
        assert!(storage.get_index_entry(&copied.id).await.is_none());
        assert!(!storage.sessions_root_dir().join(&copied.id).exists());
        assert!(storage.session_copy_journal_paths().await?.is_empty());
        drop(storage);

        let reopened = SessionStoreV2::new(bamboo_home).await?;
        assert!(reopened.get_index_entry(&copied.id).await.is_none());
        assert!(reopened.load_session(&copied.id).await?.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn test_delete_session() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let session = Session::new("session-1", "test-model");

        storage.save_session(&session).await?;
        assert!(storage.load_session(&session.id).await?.is_some());

        let deleted = storage.delete_session(&session.id).await?;
        assert!(deleted);
        assert!(storage.load_session(&session.id).await?.is_none());

        Ok(())
    }

    #[tokio::test]
    async fn test_delete_session_returns_false_when_not_found() -> io::Result<()> {
        let (storage, _temp_dir) = create_temp_storage().await?;
        let deleted = storage.delete_session("nonexistent").await?;
        assert!(!deleted);
        Ok(())
    }

    #[tokio::test]
    async fn delete_wins_before_delivery_without_recreating_an_orphan_inbox() -> io::Result<()> {
        let temp_dir = TempDir::new().map_err(io::Error::other)?;
        let storage = Arc::new(SessionStoreV2::new(temp_dir.path().to_path_buf()).await?);
        let session = Session::new("delete-inbox-race", "model");
        storage.save_session(&session).await?;
        let rel_path = storage
            .resolve_rel_path(&session.id)
            .await
            .expect("saved session has an indexed path");
        let session_dir = storage.abs_path_from_rel(&rel_path);
        // A second store instance models another Bamboo process: its in-memory
        // index stays stale after the first instance deletes the target, so
        // correctness also depends on the shared file lock and post-lock
        // `session.json` validation.
        let delivery_storage = Arc::new(SessionStoreV2::new(temp_dir.path().to_path_buf()).await?);
        let inbox = crate::FileSessionInbox::new(
            delivery_storage,
            bamboo_domain::SessionInboxLimits::default(),
        );

        // Hold the exact lifecycle exclusion that deletion owns. A delivery
        // started now cannot resolve or recreate the target until the deletion
        // and index removal have linearized.
        let lifecycle = storage.lock_session_lifecycle_exclusive().await?;
        let runtime_task = storage.lock_runtime_task_transaction_exclusive().await?;
        let guards = Arc::new(SessionDeletionGuards {
            runtime_task,
            _lifecycle: lifecycle,
        });
        let target = session.id.clone();
        let delivery = tokio::spawn(async move {
            inbox
                .deliver(&SessionMessageEnvelope::user_input(target, "late"))
                .await
        });
        tokio::task::yield_now().await;
        assert!(!delivery.is_finished());

        assert!(
            storage
                .delete_session_recursive_locked(&session.id, true, &guards)
                .await?
        );
        assert!(!session_dir.exists());
        drop(guards);

        let error = tokio::time::timeout(std::time::Duration::from_secs(2), delivery)
            .await
            .expect("blocked delivery must resume after deletion")
            .expect("delivery task must not panic")
            .expect_err("a deleted target cannot acknowledge a new inbox");
        assert!(matches!(
            error,
            SessionInboxError::TargetNotFound(ref id) if id == &session.id
        ));
        assert!(
            !session_dir.exists(),
            "failed delivery must not recreate an orphan session/inbox tree"
        );
        Ok(())
    }

    #[test]
    fn test_validate_session_id_empty() {
        assert!(validate_session_id("").is_err());
    }

    #[test]
    fn test_validate_session_id_with_slash() {
        assert!(validate_session_id("session/1").is_err());
    }

    #[test]
    fn test_validate_session_id_with_backslash() {
        assert!(validate_session_id("session\\1").is_err());
    }

    #[test]
    fn test_validate_session_id_with_double_dot() {
        assert!(validate_session_id("session..1").is_err());
    }

    #[test]
    fn test_validate_session_id_valid() {
        assert!(validate_session_id("session-123").is_ok());
    }

    #[test]
    fn test_root_rel_path() {
        let path = SessionStoreV2::root_rel_path("session-123");
        assert_eq!(path, "sessions/session-123");
    }

    #[test]
    fn test_child_rel_path() {
        let path = SessionStoreV2::child_rel_path("root-1", "child-2");
        assert_eq!(path, "sessions/root-1/children/child-2");
    }

    #[test]
    fn test_mime_to_extension() {
        assert_eq!(mime_to_extension("image/png"), Some("png"));
        assert_eq!(mime_to_extension("image/jpeg"), Some("jpg"));
        assert_eq!(mime_to_extension("image/webp"), Some("webp"));
        assert_eq!(mime_to_extension("image/gif"), Some("gif"));
        assert_eq!(mime_to_extension("image/bmp"), Some("bmp"));
        assert_eq!(mime_to_extension("unknown/type"), None);
    }

    #[test]
    fn test_extension_to_mime() {
        assert_eq!(extension_to_mime("png"), Some("image/png"));
        assert_eq!(extension_to_mime("jpg"), Some("image/jpeg"));
        assert_eq!(extension_to_mime("jpeg"), Some("image/jpeg"));
        assert_eq!(extension_to_mime("webp"), Some("image/webp"));
        assert_eq!(extension_to_mime("gif"), Some("image/gif"));
        assert_eq!(extension_to_mime("bmp"), Some("image/bmp"));
        assert_eq!(extension_to_mime("unknown"), None);
    }

    #[test]
    fn test_extension_to_mime_case_insensitive() {
        assert_eq!(extension_to_mime("PNG"), Some("image/png"));
        assert_eq!(extension_to_mime("JPG"), Some("image/jpeg"));
        assert_eq!(extension_to_mime("JPEG"), Some("image/jpeg"));
    }

    #[test]
    fn test_extension_to_mime_with_whitespace() {
        assert_eq!(extension_to_mime("  png  "), Some("image/png"));
        assert_eq!(extension_to_mime("\tjpg\t"), Some("image/jpeg"));
    }
}