starweaver-session 0.10.0

Durable session contracts for Starweaver
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
//! In-memory session store implementation.

mod approvals;
mod checkpoints;
mod host_events;
mod runs;
mod sessions;
mod streams;
mod traces;

use std::{
    collections::BTreeMap,
    sync::{Arc, Mutex},
};

use async_trait::async_trait;
use starweaver_context::{AgentCheckpoint, ResumableState};
use starweaver_core::{RunId, RunLifecycle, SessionId};
use starweaver_stream::{AgentStreamRecord, ReplayEvent, ReplayScope};

use crate::{
    AcquireBackgroundSubagentContinuation, AcquireRunAdmission, AdmitRunControl,
    BackgroundSubagentArtifact, BackgroundSubagentArtifactLimits,
    BackgroundSubagentContinuationReceipt, BackgroundSubagentRecord,
    BackgroundSubagentTerminalCommit, DurableBackgroundSubagentDeliveryClaim,
    DurableBackgroundSubagentDeliveryRelease, DurableBackgroundSubagentDeliveryStatus,
    DurableBackgroundSubagentExecutionStatus, DurableBackgroundSubagentResultRef,
    DurableControlReceipt, DurableRunControlIntent, DurableRunControlStatus, ManagedRunTarget,
    ManagedSessionTarget, RunAdmissionLease, RunAdmissionReceipt, SessionContinuationFence,
    SessionDeletionFence, UpdateManagedSession,
    approval::{ApprovalRecord, ApprovalStatus, DeferredToolRecord},
    claim::{
        ContinuationEffectState, HitlResumeAbortOutcome, HitlResumeClaim, HitlResumeClaimState,
    },
    error::{SessionStoreError, SessionStoreResult},
    evidence::RunEvidenceCommit,
    host_events::{
        DurableHostEventClass, DurableHostEventPage, DurableHostEventQuery, DurableHostEventRecord,
        DurableHostEventScope, EventPublicationKey, PendingHostEventPublication,
        append_authoritative_run_publications,
    },
    publication::{PendingStreamPublication, StreamPublicationTarget},
    records::{
        EnvironmentStateRef, ExecutionStatus, RunRecord, RunStatus, RunTerminalError,
        RunTerminalProjection, SessionRecord, SessionStatus, StreamCursorRef,
    },
    resume::SessionResumeSnapshot,
    trace::{CompactRunTrace, CompactSessionTrace},
};

use self::host_events::enqueue_host_event_publications_locked;
use super::{SessionFilter, SessionPage, SessionPageQuery, SessionStore};

/// In-memory session store for deterministic tests and single-process hosts.
#[derive(Clone, Debug, Default)]
pub struct InMemorySessionStore {
    inner: Arc<Mutex<StoreInner>>,
}

#[derive(Clone, Debug, Default)]
struct StoreInner {
    sessions: BTreeMap<SessionId, SessionRecord>,
    runs: BTreeMap<(SessionId, RunId), RunRecord>,
    checkpoints: BTreeMap<(SessionId, RunId), Vec<AgentCheckpoint>>,
    streams: BTreeMap<(SessionId, RunId), Vec<AgentStreamRecord>>,
    replay_events: BTreeMap<(ReplayScope, usize), ReplayEvent>,
    approvals: BTreeMap<(SessionId, RunId), Vec<ApprovalRecord>>,
    deferred_tools: BTreeMap<(SessionId, RunId), Vec<DeferredToolRecord>>,
    evidence_commits: BTreeMap<(SessionId, RunId), RunEvidenceCommit>,
    evidence_digests: BTreeMap<(SessionId, RunId), String>,
    hitl_resume_claims: BTreeMap<(SessionId, RunId), HitlResumeClaim>,
    stream_publication_outbox: BTreeMap<String, PendingStreamPublication>,
    host_event_outbox: BTreeMap<EventPublicationKey, PendingHostEventPublication>,
    host_event_outbox_order: BTreeMap<u64, EventPublicationKey>,
    host_event_outbox_sequences: BTreeMap<EventPublicationKey, u64>,
    last_host_event_outbox_sequence: u64,
    host_event_records: BTreeMap<u64, DurableHostEventRecord>,
    host_event_positions: BTreeMap<EventPublicationKey, u64>,
    host_event_ids: BTreeMap<String, EventPublicationKey>,
    last_host_event_position: u64,
    session_idempotency: BTreeMap<(String, String), (String, SessionRecord)>,
    run_admission_idempotency: BTreeMap<(String, String), (String, RunAdmissionReceipt)>,
    run_admissions: BTreeMap<ManagedSessionTarget, RunAdmissionLease>,
    admission_generations: BTreeMap<ManagedSessionTarget, u64>,
    control_receipts: BTreeMap<String, DurableControlReceipt>,
    control_idempotency: BTreeMap<(ManagedRunTarget, String), String>,
    run_control_intents: BTreeMap<(ManagedRunTarget, String), DurableRunControlIntent>,
    run_control_authority_keys: BTreeMap<(String, String), (ManagedRunTarget, String)>,
    background_subagents: BTreeMap<starweaver_core::SubagentAttemptId, BackgroundSubagentRecord>,
    background_artifacts: BTreeMap<String, BackgroundSubagentArtifact>,
    background_terminal_fingerprints: BTreeMap<starweaver_core::SubagentAttemptId, String>,
}

impl InMemorySessionStore {
    /// Create an empty store.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

fn run_key(session_id: &SessionId, run_id: &RunId) -> (SessionId, RunId) {
    (session_id.clone(), run_id.clone())
}

fn run_key_label(session_id: &SessionId, run_id: &RunId) -> String {
    format!("{}:{}", session_id.as_str(), run_id.as_str())
}

fn advance_run_revision(run: &mut RunRecord) -> SessionStoreResult<()> {
    run.revision = run.revision.checked_add(1).ok_or_else(|| {
        SessionStoreError::Failed(format!("run {} revision overflow", run.run_id.as_str()))
    })?;
    Ok(())
}

fn validate_approval_transition(
    existing: &ApprovalRecord,
    resolved: &ApprovalRecord,
) -> SessionStoreResult<()> {
    if existing == resolved {
        return Ok(());
    }
    let same_request = existing.approval_id == resolved.approval_id
        && existing.session_id == resolved.session_id
        && existing.run_id == resolved.run_id
        && existing.action_id == resolved.action_id
        && existing.action_name == resolved.action_name
        && existing.request == resolved.request
        && existing.reviewed_arguments == resolved.reviewed_arguments
        && existing.created_at == resolved.created_at
        && existing.trace_context == resolved.trace_context
        && existing.metadata == resolved.metadata;
    if existing.status != ApprovalStatus::Pending
        || resolved.status == ApprovalStatus::Pending
        || resolved.decision.is_none()
        || !same_request
    {
        return Err(SessionStoreError::Failed(format!(
            "approval transition conflict for {}",
            resolved.approval_id
        )));
    }
    Ok(())
}

const fn checkpoint_run_status(status: RunLifecycle) -> RunStatus {
    match status {
        RunLifecycle::Starting | RunLifecycle::Running => RunStatus::Running,
        RunLifecycle::Waiting => RunStatus::Waiting,
        RunLifecycle::Completed => RunStatus::Completed,
        RunLifecycle::Failed => RunStatus::Failed,
        RunLifecycle::Cancelled => RunStatus::Cancelled,
    }
}

fn checkpoint_terminal_error(status: RunLifecycle) -> Option<RunTerminalError> {
    match status {
        RunLifecycle::Failed => Some(RunTerminalError::new(
            "checkpoint_run_failed",
            "run failed while checkpointing",
        )),
        RunLifecycle::Cancelled => Some(RunTerminalError::new(
            "checkpoint_run_cancelled",
            "run was cancelled while checkpointing",
        )),
        RunLifecycle::Starting
        | RunLifecycle::Running
        | RunLifecycle::Waiting
        | RunLifecycle::Completed => None,
    }
}

fn validate_deferred_transition(
    existing: &DeferredToolRecord,
    resolved: &DeferredToolRecord,
) -> SessionStoreResult<()> {
    if existing == resolved {
        return Ok(());
    }
    let same_request = existing.deferred_id == resolved.deferred_id
        && existing.session_id == resolved.session_id
        && existing.run_id == resolved.run_id
        && existing.tool_call_id == resolved.tool_call_id
        && existing.tool_name == resolved.tool_name
        && existing.request == resolved.request
        && existing.created_at == resolved.created_at
        && existing.trace_context == resolved.trace_context;
    if !matches!(
        existing.status,
        ExecutionStatus::Pending | ExecutionStatus::Waiting
    ) || matches!(
        resolved.status,
        ExecutionStatus::Pending | ExecutionStatus::Running | ExecutionStatus::Waiting
    ) || !same_request
    {
        return Err(SessionStoreError::Failed(format!(
            "deferred tool transition conflict for {}",
            resolved.deferred_id
        )));
    }
    Ok(())
}

#[allow(clippy::needless_pass_by_value)]
fn store_failed(
    error: std::sync::PoisonError<std::sync::MutexGuard<'_, StoreInner>>,
) -> SessionStoreError {
    SessionStoreError::Failed(error.to_string())
}

fn session_mutation_time(
    publications: &[PendingHostEventPublication],
) -> SessionStoreResult<chrono::DateTime<chrono::Utc>> {
    let Some(first) = publications.first() else {
        return Ok(chrono::Utc::now());
    };
    if publications
        .iter()
        .any(|publication| publication.occurred_at != first.occurred_at)
    {
        return Err(SessionStoreError::Conflict(
            "session mutation publications must share one occurred_at".to_string(),
        ));
    }
    Ok(first.occurred_at)
}

fn ensure_active_admission_locked(
    inner: &StoreInner,
    lease: &RunAdmissionLease,
    now: chrono::DateTime<chrono::Utc>,
) -> SessionStoreResult<()> {
    let key = ManagedSessionTarget::new(
        lease.target.namespace_id.clone(),
        lease.target.session_id.clone(),
    );
    let current = inner.run_admissions.get(&key).ok_or_else(|| {
        SessionStoreError::StaleFence("run has no active owner lease".to_string())
    })?;
    if current.target != lease.target
        || current.admission_id != lease.admission_id
        || current.host_instance_id != lease.host_instance_id
        || current.fencing_generation != lease.fencing_generation
    {
        return Err(SessionStoreError::StaleFence(
            "stale admission owner".to_string(),
        ));
    }
    if current.expired_at(now) {
        return Err(SessionStoreError::StaleFence(
            "run admission lease expired".to_string(),
        ));
    }
    Ok(())
}

fn reconcile_run_control_intents_locked(
    inner: &mut StoreInner,
    lease: &RunAdmissionLease,
    occurred_at: chrono::DateTime<chrono::Utc>,
) -> SessionStoreResult<()> {
    let keys = inner
        .run_control_intents
        .iter()
        .filter(|(_, intent)| {
            intent.target == lease.target
                && intent.admission_id == lease.admission_id
                && intent.fencing_generation == lease.fencing_generation
                && matches!(
                    intent.status,
                    DurableRunControlStatus::Pending | DurableRunControlStatus::Delivered
                )
        })
        .map(|(key, _)| key.clone())
        .collect::<Vec<_>>();
    for key in keys {
        let mut intent = inner
            .run_control_intents
            .get(&key)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(key.1.clone()))?;
        intent
            .advance(DurableRunControlStatus::Reconciled, occurred_at)
            .map_err(|error| SessionStoreError::Conflict(error.to_string()))?;
        inner
            .control_receipts
            .insert(intent.receipt.receipt_id.clone(), intent.receipt.clone());
        inner.run_control_intents.insert(key, intent);
    }
    Ok(())
}

fn apply_run_status_locked(
    inner: &mut StoreInner,
    session_id: &SessionId,
    run_id: &RunId,
    status: RunStatus,
    output_preview: Option<String>,
    terminal_error: Option<RunTerminalError>,
    updated_at: chrono::DateTime<chrono::Utc>,
) -> SessionStoreResult<RunRecord> {
    let key = run_key(session_id, run_id);
    let run = inner
        .runs
        .get_mut(&key)
        .ok_or_else(|| SessionStoreError::NotFound(run_key_label(session_id, run_id)))?;
    if (run.status, &run.output_preview, &run.terminal_error)
        == (status, &output_preview, &terminal_error)
    {
        return Ok(run.clone());
    }
    run.status = status;
    run.output_preview = output_preview;
    run.terminal_error = terminal_error;
    advance_run_revision(run)?;
    run.updated_at = updated_at;
    let result = run.clone();
    if let Some(session) = inner.sessions.get_mut(session_id) {
        session.head_run_id = Some(run_id.clone());
        if status.is_active() {
            session.active_run_id = Some(run_id.clone());
        } else {
            if status == RunStatus::Completed {
                session.head_success_run_id = Some(run_id.clone());
            }
            if session.active_run_id.as_ref() == Some(run_id) {
                session.active_run_id = None;
            }
        }
        session.revision = session.revision.saturating_add(1);
        session.updated_at = updated_at;
    }
    Ok(result)
}

fn terminalize_started_hitl_source_locked(
    inner: &mut StoreInner,
    replacement: &RunRecord,
    now: chrono::DateTime<chrono::Utc>,
) -> SessionStoreResult<bool> {
    let Some(source_run_id) = replacement.restore_from_run_id.as_ref() else {
        return Ok(false);
    };
    let source_key = run_key(&replacement.session_id, source_run_id);
    let source = inner.runs.get(&source_key).ok_or_else(|| {
        SessionStoreError::NotFound(run_key_label(&replacement.session_id, source_run_id))
    })?;
    if source.status != RunStatus::Waiting {
        return Ok(false);
    }
    let claim = inner
        .hitl_resume_claims
        .get(&source_key)
        .cloned()
        .ok_or_else(|| {
            SessionStoreError::Conflict(format!(
                "waiting replacement source {} has no resume claim",
                source_run_id.as_str()
            ))
        })?;
    if claim.session_id != replacement.session_id || claim.run_id != *source_run_id {
        return Err(SessionStoreError::Conflict(format!(
            "waiting replacement source {} has a mismatched resume claim",
            source_run_id.as_str()
        )));
    }
    if claim.state == HitlResumeClaimState::Preflight {
        return Err(SessionStoreError::Conflict(format!(
            "waiting replacement source {} has an invalid preflight claim",
            source_run_id.as_str()
        )));
    }
    if claim.state == HitlResumeClaimState::Started {
        let source = inner.runs.get_mut(&source_key).ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(&replacement.session_id, source_run_id))
        })?;
        source.status = RunStatus::Cancelled;
        source.output_preview = Some("interrupted after host lease expired".to_string());
        source.terminal_error = Some(RunTerminalError::new(
            "admission_lease_expired",
            "interrupted after host lease expired",
        ));
        advance_run_revision(source)?;
        source.updated_at = now;
        ContinuationEffectState::indeterminate()
            .insert_into(&mut source.metadata)
            .map_err(|error| SessionStoreError::Failed(error.to_string()))?;
    }
    let consumed = inner.hitl_resume_claims.remove(&source_key);
    if consumed.as_ref() != Some(&claim) {
        return Err(SessionStoreError::Conflict(format!(
            "resume claim changed while terminalizing run {}",
            source_run_id.as_str()
        )));
    }
    Ok(claim.state == HitlResumeClaimState::Started)
}

fn resolve_evidence_retry(
    inner: &StoreInner,
    key: &(SessionId, RunId),
    commit: &RunEvidenceCommit,
    digest: &str,
) -> SessionStoreResult<Option<RunRecord>> {
    let Some(existing_digest) = inner.evidence_digests.get(key) else {
        return Ok(None);
    };
    if existing_digest == digest {
        return inner.runs.get(key).cloned().map(Some).ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(&commit.run.session_id, &commit.run.run_id))
        });
    }
    Err(SessionStoreError::Failed(format!(
        "run evidence conflict for session {} and run {}",
        commit.run.session_id.as_str(),
        commit.run.run_id.as_str()
    )))
}

fn validate_related_evidence(
    inner: &StoreInner,
    commit: &RunEvidenceCommit,
) -> SessionStoreResult<()> {
    for update in &commit.related_run_updates {
        let related_key = run_key(&commit.run.session_id, &update.run_id);
        let claim_id = update.resume_claim_id.as_deref().ok_or_else(|| {
            SessionStoreError::Failed(format!(
                "related run {} requires an exclusive resume claim",
                update.run_id.as_str()
            ))
        })?;
        let claim = inner.hitl_resume_claims.get(&related_key).ok_or_else(|| {
            SessionStoreError::Failed(format!(
                "related run {} has no active resume claim",
                update.run_id.as_str()
            ))
        })?;
        if claim.claim_id != claim_id || claim.state != HitlResumeClaimState::Started {
            return Err(SessionStoreError::Failed(format!(
                "started resume claim conflict for related run {}",
                update.run_id.as_str()
            )));
        }
        for approval in &update.approvals {
            let existing = inner
                .approvals
                .get(&related_key)
                .into_iter()
                .flatten()
                .find(|existing| existing.approval_id == approval.approval_id)
                .ok_or_else(|| SessionStoreError::NotFound(approval.approval_id.clone()))?;
            validate_approval_transition(existing, approval)?;
        }
        for deferred in &update.deferred_tools {
            let existing = inner
                .deferred_tools
                .get(&related_key)
                .into_iter()
                .flatten()
                .find(|existing| existing.deferred_id == deferred.deferred_id)
                .ok_or_else(|| SessionStoreError::NotFound(deferred.deferred_id.clone()))?;
            validate_deferred_transition(existing, deferred)?;
        }
    }
    Ok(())
}

fn validate_existing_evidence(
    inner: &StoreInner,
    key: &(SessionId, RunId),
    commit: &RunEvidenceCommit,
) -> SessionStoreResult<()> {
    if let Some(existing_run) = inner.runs.get(key) {
        for cursor in &commit.stream_cursors {
            for existing in existing_run.stream_cursors.iter().chain(
                inner
                    .sessions
                    .get(&commit.run.session_id)
                    .into_iter()
                    .flat_map(|session| session.stream_cursors.iter()),
            ) {
                cursor
                    .validate_progression(existing)
                    .map_err(|error| SessionStoreError::Failed(error.to_string()))?;
            }
        }
    }
    for approval in &commit.approvals {
        if let Some(existing) = inner
            .approvals
            .get(key)
            .into_iter()
            .flatten()
            .find(|existing| existing.approval_id == approval.approval_id)
            && existing != approval
        {
            return Err(SessionStoreError::Failed(format!(
                "approval conflict for id {}",
                approval.approval_id
            )));
        }
    }
    for deferred in &commit.deferred_tools {
        if let Some(existing) = inner
            .deferred_tools
            .get(key)
            .into_iter()
            .flatten()
            .find(|existing| existing.deferred_id == deferred.deferred_id)
            && existing != deferred
        {
            return Err(SessionStoreError::Failed(format!(
                "deferred tool conflict for id {}",
                deferred.deferred_id
            )));
        }
    }
    validate_related_evidence(inner, commit)
}

fn apply_related_evidence(
    staged: &InMemorySessionStore,
    commit: &RunEvidenceCommit,
) -> SessionStoreResult<()> {
    for update in &commit.related_run_updates {
        let source = staged.load_run_record(&commit.run.session_id, &update.run_id)?;
        if source.status != update.expected_status {
            return Err(SessionStoreError::Failed(format!(
                "related run {} status conflict: expected {}, found {}",
                update.run_id.as_str(),
                update.expected_status.as_str(),
                source.status.as_str()
            )));
        }
        staged.set_run_status(
            &commit.run.session_id,
            &update.run_id,
            update.status,
            update.output_preview.clone(),
            update.terminal_error.clone(),
        )?;
        for approval in update.approvals.clone() {
            staged.append_approval_record(approval)?;
        }
        for deferred in update.deferred_tools.clone() {
            staged.append_deferred_tool_record(deferred)?;
        }
        staged
            .inner
            .lock()
            .map_err(store_failed)?
            .hitl_resume_claims
            .remove(&run_key(&commit.run.session_id, &update.run_id));
    }
    Ok(())
}

fn apply_primary_evidence(
    staged: &InMemorySessionStore,
    commit: &RunEvidenceCommit,
) -> SessionStoreResult<()> {
    staged.append_run_record(commit.run.clone())?;
    staged.save_context_state_snapshot(&commit.run.session_id, commit.context_state.clone())?;
    for checkpoint in commit.checkpoints.clone() {
        staged.append_checkpoint_record_with_revision(&commit.run.session_id, checkpoint, false)?;
    }
    staged.append_stream_record_batch_with_revision(
        &commit.run.session_id,
        &commit.run.run_id,
        commit.stream_records.clone(),
        false,
    )?;
    for cursor in commit.stream_cursors.clone() {
        staged.save_stream_cursor_ref_with_revision(
            &commit.run.session_id,
            &commit.run.run_id,
            cursor,
            false,
        )?;
    }
    for approval in commit.approvals.clone() {
        staged.append_approval_record(approval)?;
    }
    for deferred in commit.deferred_tools.clone() {
        staged.append_deferred_tool_record(deferred)?;
    }
    Ok(())
}

fn finalize_staged_evidence(
    staged: &InMemorySessionStore,
    mut commit: RunEvidenceCommit,
    key: (SessionId, RunId),
    digest: String,
) -> SessionStoreResult<(StoreInner, RunRecord)> {
    let mut inner = staged.inner.lock().map_err(store_failed)?;
    let commit_timestamp = commit.run.updated_at;
    let target_key = run_key(&commit.run.session_id, &commit.run.run_id);
    inner
        .runs
        .get_mut(&target_key)
        .ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(&commit.run.session_id, &commit.run.run_id))
        })?
        .updated_at = commit_timestamp;
    for update in &commit.related_run_updates {
        if let Some(source) = inner
            .runs
            .get_mut(&run_key(&commit.run.session_id, &update.run_id))
        {
            source.updated_at = commit_timestamp;
        }
    }
    if let Some(session) = inner.sessions.get_mut(&commit.run.session_id) {
        session.updated_at = commit_timestamp;
    }
    let committed = inner.runs.get(&target_key).cloned().ok_or_else(|| {
        SessionStoreError::NotFound(run_key_label(&commit.run.session_id, &commit.run.run_id))
    })?;
    commit.run = committed.clone();
    let mut authoritative_runs = vec![committed.clone()];
    for update in &commit.related_run_updates {
        authoritative_runs.push(
            inner
                .runs
                .get(&run_key(&commit.run.session_id, &update.run_id))
                .cloned()
                .ok_or_else(|| {
                    SessionStoreError::NotFound(run_key_label(
                        &commit.run.session_id,
                        &update.run_id,
                    ))
                })?,
        );
    }
    append_authoritative_run_publications(
        &mut commit.host_event_publications,
        &format!("run-evidence:{digest}"),
        authoritative_runs.iter(),
    )?;
    if !commit.publication_targets.is_empty() {
        let mut publication = PendingStreamPublication::new(
            commit.run.session_id.clone(),
            commit.run.run_id.clone(),
            commit.publication_targets,
            commit.run.updated_at,
        );
        publication
            .stream_records
            .clone_from(&commit.stream_records);
        publication
            .display_messages
            .clone_from(&commit.display_messages);
        publication.replay_events.clone_from(&commit.replay_events);
        publication
            .display_snapshot
            .clone_from(&commit.display_snapshot);
        inner
            .stream_publication_outbox
            .insert(publication.publication_id.clone(), publication);
    }
    enqueue_host_event_publications_locked(&mut inner, &commit.host_event_publications)?;
    inner.evidence_commits.insert(key.clone(), commit);
    inner.evidence_digests.insert(key, digest);
    Ok((inner.clone(), committed))
}

#[allow(clippy::too_many_lines)]
fn acquire_run_admission_locked(
    inner: &mut StoreInner,
    request: AcquireRunAdmission,
) -> SessionStoreResult<RunAdmissionReceipt> {
    let idempotency_key = (
        request.namespace_id.clone(),
        request.idempotency_key.clone(),
    );
    if let Some((fingerprint, receipt)) = inner.run_admission_idempotency.get(&idempotency_key) {
        if fingerprint == &request.command_fingerprint {
            let mut receipt = receipt.clone();
            receipt.idempotent_replay = true;
            return Ok(receipt);
        }
        return Err(SessionStoreError::IdempotencyConflict(
            request.idempotency_key,
        ));
    }
    if request.replaces_waiting_run_id.is_some() != request.hitl_resume_claim_id.is_some() {
        return Err(SessionStoreError::Conflict(
            "waiting-run replacement requires exactly one preflight HITL claim".to_string(),
        ));
    }
    let session_target =
        ManagedSessionTarget::new(request.namespace_id.clone(), request.run.session_id.clone());
    let now = chrono::Utc::now();
    if let Some(active) = inner.run_admissions.get(&session_target).cloned() {
        if !active.expired_at(now) {
            return Err(SessionStoreError::RunConflict(format!(
                "session {} already has active run {}",
                request.run.session_id.as_str(),
                active.target.run_id.as_str()
            )));
        }
        let replacement_key = run_key(&active.target.session_id, &active.target.run_id);
        let replacement = inner.runs.get(&replacement_key).cloned().ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(
                &active.target.session_id,
                &active.target.run_id,
            ))
        })?;
        if replacement.status.is_active() {
            let effect_started = terminalize_started_hitl_source_locked(inner, &replacement, now)?;
            let run = inner.runs.get_mut(&replacement_key).ok_or_else(|| {
                SessionStoreError::NotFound(run_key_label(
                    &active.target.session_id,
                    &active.target.run_id,
                ))
            })?;
            run.status = RunStatus::Cancelled;
            run.output_preview = Some("interrupted after host lease expired".to_string());
            run.terminal_error = Some(RunTerminalError::new(
                "admission_lease_expired",
                "interrupted after host lease expired",
            ));
            advance_run_revision(run)?;
            run.updated_at = now;
            if effect_started {
                ContinuationEffectState::indeterminate()
                    .insert_into(&mut run.metadata)
                    .map_err(|error| SessionStoreError::Failed(error.to_string()))?;
            }
        }
        inner.run_admissions.remove(&session_target);
        if let Some(session) = inner.sessions.get_mut(&request.run.session_id)
            && session.active_run_id.as_ref() == Some(&active.target.run_id)
        {
            session.active_run_id = None;
        }
    }
    {
        let session = inner.sessions.get(&request.run.session_id).ok_or_else(|| {
            SessionStoreError::NotFound(request.run.session_id.as_str().to_string())
        })?;
        if session.namespace_id != request.namespace_id {
            return Err(SessionStoreError::NotFound(
                request.run.session_id.as_str().to_string(),
            ));
        }
        if session.status != SessionStatus::Active || session.deletion_fence.blocks_continuation() {
            return Err(SessionStoreError::Conflict(
                "session cannot admit new work".to_string(),
            ));
        }
        if let Some(active_run_id) = session.active_run_id.as_ref() {
            let valid_waiting_replacement = request.replaces_waiting_run_id.as_ref()
                == Some(active_run_id)
                && request.run.restore_from_run_id.as_ref() == Some(active_run_id)
                && inner
                    .runs
                    .get(&run_key(&request.run.session_id, active_run_id))
                    .is_some_and(|source| source.status == RunStatus::Waiting);
            if !valid_waiting_replacement {
                return Err(SessionStoreError::RunConflict(format!(
                    "session {} already has active run {}",
                    request.run.session_id.as_str(),
                    active_run_id.as_str()
                )));
            }
        } else if let Some(source_run_id) = request.replaces_waiting_run_id.as_ref() {
            // A pre-effect replacement may have terminalized and cleared the session pointer
            // while deliberately leaving its source Waiting. Permit exactly that source to claim
            // a new replacement; no unrelated run can be revived because the source binding and
            // status remain part of this atomic admission validation.
            let valid_unparked_waiting_replacement = request.run.restore_from_run_id.as_ref()
                == Some(source_run_id)
                && inner
                    .runs
                    .get(&run_key(&request.run.session_id, source_run_id))
                    .is_some_and(|source| source.status == RunStatus::Waiting);
            if !valid_unparked_waiting_replacement {
                return Err(SessionStoreError::Conflict(
                    "waiting-run replacement has no retryable waiting source".to_string(),
                ));
            }
        }
    }
    let hitl_claim_key = match (
        request.replaces_waiting_run_id.as_ref(),
        request.hitl_resume_claim_id.as_deref(),
    ) {
        (Some(source_run_id), Some(claim_id)) => {
            let key = run_key(&request.run.session_id, source_run_id);
            let claim = inner.hitl_resume_claims.get(&key).ok_or_else(|| {
                SessionStoreError::NotFound(format!("resume claim for {}", source_run_id.as_str()))
            })?;
            if claim.claim_id != claim_id
                || claim.session_id != request.run.session_id
                || claim.run_id != *source_run_id
                || claim.state != HitlResumeClaimState::Preflight
            {
                return Err(SessionStoreError::Conflict(format!(
                    "invalid preflight resume claim for run {}",
                    source_run_id.as_str()
                )));
            }
            Some(key)
        }
        (None, None) => None,
        _ => unreachable!("replacement and claim presence checked above"),
    };
    if let Some(key) = hitl_claim_key.as_ref() {
        let claim = inner.hitl_resume_claims.get_mut(key).ok_or_else(|| {
            SessionStoreError::Conflict("validated preflight resume claim disappeared".to_string())
        })?;
        claim.state = HitlResumeClaimState::Admitted;
    }
    let mut run = request.run;
    run.normalize_for_admission();
    run.revision = 1;
    run.validate_new_write().map_err(|error| {
        SessionStoreError::Failed(format!(
            "invalid admitted run state for {}: {error}",
            run.run_id.as_str()
        ))
    })?;
    if run.sequence_no == 0 {
        run.sequence_no = inner
            .runs
            .values()
            .filter(|current| current.session_id == run.session_id)
            .map(|current| current.sequence_no)
            .max()
            .unwrap_or(0)
            .saturating_add(1);
    }
    run.updated_at = now;
    let generation = inner
        .admission_generations
        .entry(session_target.clone())
        .and_modify(|generation| *generation = generation.saturating_add(1))
        .or_insert(1);
    let lease = RunAdmissionLease {
        target: ManagedRunTarget::new(
            request.namespace_id,
            run.session_id.clone(),
            run.run_id.clone(),
        ),
        admission_id: request.admission_id,
        host_instance_id: request.host_instance_id,
        fencing_generation: *generation,
        lease_expires_at: request.lease_expires_at,
        heartbeat_at: now,
        command_fingerprint: request.command_fingerprint.clone(),
        idempotency_key: request.idempotency_key,
    };
    inner
        .runs
        .insert(run_key(&run.session_id, &run.run_id), run.clone());
    let session = inner
        .sessions
        .get_mut(&run.session_id)
        .ok_or_else(|| SessionStoreError::NotFound(run.session_id.as_str().to_string()))?;
    session.head_run_id = Some(run.run_id.clone());
    session.active_run_id = Some(run.run_id.clone());
    session.revision = session.revision.saturating_add(1);
    session.updated_at = now;
    inner.run_admissions.insert(session_target, lease.clone());
    let receipt = RunAdmissionReceipt {
        run,
        lease,
        idempotent_replay: false,
    };
    inner.run_admission_idempotency.insert(
        idempotency_key,
        (request.command_fingerprint, receipt.clone()),
    );
    Ok(receipt)
}

fn same_background_identity(
    current: &BackgroundSubagentRecord,
    next: &BackgroundSubagentRecord,
) -> bool {
    current.schema_version == next.schema_version
        && current.attempt_id == next.attempt_id
        && current.agent_id == next.agent_id
        && current.linked_task_id == next.linked_task_id
        && current.subagent_name == next.subagent_name
        && current.namespace_id == next.namespace_id
        && current.parent_session_id == next.parent_session_id
        && current.parent_run_id == next.parent_run_id
        && current.profile == next.profile
        && current.owner_lease.host_instance_id == next.owner_lease.host_instance_id
        && current.owner_lease.fencing_generation == next.owner_lease.fencing_generation
        && current.accepted_at == next.accepted_at
}

fn same_background_owner(
    current: &BackgroundSubagentRecord,
    next: &BackgroundSubagentRecord,
) -> bool {
    current.owner_lease.host_instance_id == next.owner_lease.host_instance_id
        && current.owner_lease.fencing_generation == next.owner_lease.fencing_generation
}

fn valid_background_terminal_base(
    current: &BackgroundSubagentRecord,
    next: &BackgroundSubagentRecord,
) -> bool {
    current.delivery_status == DurableBackgroundSubagentDeliveryStatus::Undelivered
        && current.delivery_claim.is_none()
        && current.delivered_claim_id.is_none()
        && current.continuation_run_id.is_none()
        && current
            .automatic_continuation_suppressed_by_run_id
            .is_none()
        && next.automatic_continuation_suppressed_by_run_id.is_none()
        && current.retention_status == crate::DurableBackgroundSubagentRetentionStatus::Inline
        && current.retention_expires_at.is_none()
        && matches!(
            next.retention_status,
            crate::DurableBackgroundSubagentRetentionStatus::Inline
                | crate::DurableBackgroundSubagentRetentionStatus::Artifact
        )
        && current.trace_context == next.trace_context
        && next.updated_at >= current.updated_at
}

fn same_background_non_execution_state(
    current: &BackgroundSubagentRecord,
    next: &BackgroundSubagentRecord,
) -> bool {
    current.continuation_run_id == next.continuation_run_id
        && current.result_ref == next.result_ref
        && current.failure_category == next.failure_category
        && current.cancellation_reason == next.cancellation_reason
        && current.delivery_status == next.delivery_status
        && current.delivery_claim == next.delivery_claim
        && current.delivered_claim_id == next.delivered_claim_id
        && current.automatic_continuation_suppressed_by_run_id
            == next.automatic_continuation_suppressed_by_run_id
        && current.retention_status == next.retention_status
        && current.retention_expires_at == next.retention_expires_at
        && current.trace_context == next.trace_context
        && current.terminal_at == next.terminal_at
        && next.updated_at >= current.updated_at
}

fn continuation_artifact_content(
    inner: &StoreInner,
    background: &BackgroundSubagentRecord,
    now: chrono::DateTime<chrono::Utc>,
) -> SessionStoreResult<Option<String>> {
    if background.retention_status != crate::DurableBackgroundSubagentRetentionStatus::Artifact {
        return Ok(None);
    }
    let result_ref = background.result_ref.as_ref().ok_or_else(|| {
        SessionStoreError::Conflict("artifact result is missing terminal evidence".to_string())
    })?;
    let artifact_ref = result_ref.artifact_ref.as_deref().ok_or_else(|| {
        SessionStoreError::Conflict("artifact result is missing its reference".to_string())
    })?;
    let artifact = inner
        .background_artifacts
        .get(artifact_ref)
        .ok_or_else(|| SessionStoreError::NotFound(artifact_ref.to_string()))?;
    if !artifact.is_available_at(now)
        || artifact.namespace_id != background.namespace_id
        || artifact.attempt_id != background.attempt_id
        || artifact.digest != result_ref.digest.clone().unwrap_or_default()
        || artifact.size_bytes != result_ref.size_bytes
        || background.retention_expires_at != Some(artifact.expires_at)
    {
        return Err(SessionStoreError::Conflict(
            "background-subagent artifact failed integrity or retention validation".to_string(),
        ));
    }
    Ok(Some(artifact.content.clone()))
}

fn continuation_receipt_matches_request(
    background: &BackgroundSubagentRecord,
    request: &AcquireBackgroundSubagentContinuation,
    admission: &RunAdmissionReceipt,
) -> bool {
    let proposed = &request.admission.run;
    let admitted = &admission.run;
    background.validates_continuation_cause_envelope(&request.cause, admitted)
        && admitted.session_id == proposed.session_id
        && admitted.run_id == proposed.run_id
        && admitted.conversation_id == proposed.conversation_id
        && admitted.input == proposed.input
        && admitted.parent_run_id == proposed.parent_run_id
        && admitted.parent_task_id == proposed.parent_task_id
        && admitted.trigger_type == proposed.trigger_type
        && admitted.profile == proposed.profile
        && admitted.trace_context == proposed.trace_context
        && admitted.metadata == proposed.metadata
        && admission.lease.target.session_id == proposed.session_id
        && admission.lease.target.run_id == proposed.run_id
        && admission.lease.target.namespace_id == request.admission.namespace_id
        && admission.lease.command_fingerprint == request.admission.command_fingerprint
        && admission.lease.idempotency_key == request.admission.idempotency_key
}

fn background_terminal_fingerprint(
    record: &BackgroundSubagentRecord,
    artifact: Option<&BackgroundSubagentArtifact>,
) -> SessionStoreResult<String> {
    BackgroundSubagentTerminalCommit {
        record: record.clone(),
        artifact: artifact.cloned(),
        artifact_limits: None,
    }
    .canonical_fingerprint()
    .map_err(|error| SessionStoreError::Failed(error.to_string()))
}

fn persisted_background_terminal_fingerprint(
    inner: &StoreInner,
    current: &BackgroundSubagentRecord,
) -> SessionStoreResult<Option<String>> {
    if let Some(fingerprint) = inner
        .background_terminal_fingerprints
        .get(&current.attempt_id)
    {
        return Ok(Some(fingerprint.clone()));
    }
    reconstruct_background_terminal_fingerprint(inner, current)
}

fn reconstruct_background_terminal_fingerprint(
    inner: &StoreInner,
    current: &BackgroundSubagentRecord,
) -> SessionStoreResult<Option<String>> {
    if !current.execution_status.is_terminal()
        || current.retention_status == crate::DurableBackgroundSubagentRetentionStatus::Expired
        || current.result_ref.is_none()
    {
        return Ok(None);
    }
    let Some(terminal_at) = current.terminal_at else {
        return Ok(None);
    };
    if current
        .retention_expires_at
        .is_none_or(|deadline| deadline <= terminal_at)
    {
        return Ok(None);
    }
    let artifact = match current.retention_status {
        crate::DurableBackgroundSubagentRetentionStatus::Inline => None,
        crate::DurableBackgroundSubagentRetentionStatus::Artifact => {
            let Some(result_ref) = current.result_ref.as_ref() else {
                return Ok(None);
            };
            let Some(artifact_ref) = result_ref.artifact_ref.as_deref() else {
                return Ok(None);
            };
            let Some(artifact) = inner.background_artifacts.get(artifact_ref) else {
                return Ok(None);
            };
            if !artifact.is_valid()
                || artifact.namespace_id != current.namespace_id
                || artifact.attempt_id != current.attempt_id
                || artifact.digest != result_ref.digest.clone().unwrap_or_default()
                || artifact.size_bytes != result_ref.size_bytes
                || current.retention_expires_at != Some(artifact.expires_at)
            {
                return Ok(None);
            }
            Some(artifact)
        }
        crate::DurableBackgroundSubagentRetentionStatus::Expired => return Ok(None),
    };
    let mut terminal = current.clone();
    terminal.updated_at = terminal_at;
    background_terminal_fingerprint(&terminal, artifact).map(Some)
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum BackgroundClaimConsumerState {
    Reclaimable,
    Live,
    Completed(RunId),
    Terminated(RunId),
}

fn background_claim_consumer_state(
    inner: &StoreInner,
    record: &BackgroundSubagentRecord,
    claim: &DurableBackgroundSubagentDeliveryClaim,
    now: chrono::DateTime<chrono::Utc>,
) -> BackgroundClaimConsumerState {
    let Some(run_id) = claim.continuation_run_id.as_ref() else {
        return BackgroundClaimConsumerState::Reclaimable;
    };
    let Some(run) = inner.runs.get(&run_key(&record.parent_session_id, run_id)) else {
        return BackgroundClaimConsumerState::Reclaimable;
    };
    match run.status {
        RunStatus::Completed => BackgroundClaimConsumerState::Completed(run_id.clone()),
        RunStatus::Failed | RunStatus::Cancelled => {
            BackgroundClaimConsumerState::Terminated(run_id.clone())
        }
        status
            if status.is_active()
                && inner
                    .run_admissions
                    .get(&ManagedSessionTarget::new(
                        record.namespace_id.clone(),
                        record.parent_session_id.clone(),
                    ))
                    .is_some_and(|lease| {
                        lease.target.run_id == *run_id && !lease.expired_at(now)
                    }) =>
        {
            BackgroundClaimConsumerState::Live
        }
        _ => BackgroundClaimConsumerState::Reclaimable,
    }
}

fn validate_background_artifact_quota(
    inner: &StoreInner,
    artifact: &BackgroundSubagentArtifact,
    limits: BackgroundSubagentArtifactLimits,
    now: chrono::DateTime<chrono::Utc>,
) -> SessionStoreResult<()> {
    if !artifact.is_available_at(now) {
        return Err(SessionStoreError::Conflict(
            "background-subagent artifact is invalid or already expired".to_string(),
        ));
    }
    let retained_bytes = inner
        .background_artifacts
        .values()
        .filter(|current| {
            current.namespace_id == artifact.namespace_id
                && current.artifact_ref != artifact.artifact_ref
                && current.expires_at > now
        })
        .map(|current| current.size_bytes)
        .fold(0u64, u64::saturating_add);
    if artifact.size_bytes > limits.max_single_bytes
        || retained_bytes.saturating_add(artifact.size_bytes) > limits.max_retained_bytes
    {
        return Err(SessionStoreError::QuotaExceeded(
            "background-subagent artifact exceeds host retention quota".to_string(),
        ));
    }
    Ok(())
}

fn ensure_background_parent_writable(
    inner: &StoreInner,
    record: &BackgroundSubagentRecord,
) -> SessionStoreResult<()> {
    let session = inner
        .sessions
        .get(&record.parent_session_id)
        .filter(|session| session.namespace_id == record.namespace_id)
        .ok_or_else(|| {
            SessionStoreError::NotFound(record.parent_session_id.as_str().to_string())
        })?;
    if session.status != SessionStatus::Active || session.deletion_fence.blocks_continuation() {
        return Err(SessionStoreError::Conflict(
            "background owner write rejected because parent session is deleting or deleted"
                .to_string(),
        ));
    }
    Ok(())
}

fn commit_background_terminal(
    inner: &mut StoreInner,
    mut record: BackgroundSubagentRecord,
    artifact: Option<BackgroundSubagentArtifact>,
    artifact_limits: Option<BackgroundSubagentArtifactLimits>,
) -> SessionStoreResult<BackgroundSubagentRecord> {
    if !record.is_valid_terminal() {
        return Err(SessionStoreError::Conflict(
            "invalid background-subagent terminal record".to_string(),
        ));
    }
    if artifact.is_some() != artifact_limits.is_some()
        || artifact_limits.is_some_and(|limits| !limits.is_valid())
    {
        return Err(SessionStoreError::Conflict(
            "background-subagent artifact requires valid host quota limits".to_string(),
        ));
    }
    let current = inner
        .background_subagents
        .get(&record.attempt_id)
        .cloned()
        .ok_or_else(|| SessionStoreError::NotFound(record.attempt_id.as_str().to_string()))?;
    ensure_background_parent_writable(inner, &current)?;
    let terminal_fingerprint = background_terminal_fingerprint(&record, artifact.as_ref())?;
    if current.execution_status.is_terminal() {
        let persisted_fingerprint = persisted_background_terminal_fingerprint(inner, &current)?;
        return if persisted_fingerprint.as_deref() == Some(terminal_fingerprint.as_str()) {
            inner
                .background_terminal_fingerprints
                .insert(current.attempt_id.clone(), terminal_fingerprint);
            Ok(current)
        } else {
            Err(SessionStoreError::Conflict(format!(
                "terminal background attempt {} is immutable",
                record.attempt_id.as_str()
            )))
        };
    }
    let now = chrono::Utc::now();
    if current.owner_lease.expired_at(now) {
        return Err(SessionStoreError::Conflict(format!(
            "background owner lease expired for {}",
            record.attempt_id.as_str()
        )));
    }
    if let (Some(artifact), Some(limits)) = (artifact.as_ref(), artifact_limits) {
        validate_background_artifact_quota(inner, artifact, limits, now)?;
    }
    if !same_background_identity(&current, &record)
        || !same_background_owner(&current, &record)
        || !valid_background_terminal_base(&current, &record)
        || !valid_background_transition(current.execution_status, record.execution_status)
    {
        return Err(SessionStoreError::Conflict(format!(
            "invalid terminal background transition for {}",
            record.attempt_id.as_str()
        )));
    }
    if let Some(artifact) = artifact {
        let artifact_matches = artifact.is_available_at(now)
            && artifact.attempt_id == record.attempt_id
            && artifact.namespace_id == record.namespace_id
            && record.retention_status == crate::DurableBackgroundSubagentRetentionStatus::Artifact
            && record.retention_expires_at == Some(artifact.expires_at)
            && record.result_ref.as_ref().is_some_and(|result| {
                result.artifact_ref.as_deref() == Some(artifact.artifact_ref.as_str())
                    && result.digest.as_deref() == Some(artifact.digest.as_str())
                    && result.size_bytes == artifact.size_bytes
            });
        if !artifact_matches {
            return Err(SessionStoreError::Conflict(
                "background-subagent artifact does not match terminal evidence".to_string(),
            ));
        }
        if let Some(existing) = inner.background_artifacts.get(&artifact.artifact_ref) {
            if existing != &artifact {
                return Err(SessionStoreError::Conflict(
                    "background-subagent artifact identity conflict".to_string(),
                ));
            }
        } else {
            inner
                .background_artifacts
                .insert(artifact.artifact_ref.clone(), artifact);
        }
    } else if record.retention_status == crate::DurableBackgroundSubagentRetentionStatus::Artifact {
        return Err(SessionStoreError::Conflict(
            "artifact retention requires an atomic artifact payload".to_string(),
        ));
    }
    record.owner_lease = current.owner_lease;
    inner
        .background_terminal_fingerprints
        .insert(record.attempt_id.clone(), terminal_fingerprint);
    inner
        .background_subagents
        .insert(record.attempt_id.clone(), record.clone());
    Ok(record)
}

fn valid_background_transition(
    current: DurableBackgroundSubagentExecutionStatus,
    next: DurableBackgroundSubagentExecutionStatus,
) -> bool {
    current == next
        || matches!(
            (current, next),
            (
                DurableBackgroundSubagentExecutionStatus::Accepted,
                DurableBackgroundSubagentExecutionStatus::Starting
                    | DurableBackgroundSubagentExecutionStatus::Failed
                    | DurableBackgroundSubagentExecutionStatus::Cancelled
            ) | (
                DurableBackgroundSubagentExecutionStatus::Starting,
                DurableBackgroundSubagentExecutionStatus::Running
                    | DurableBackgroundSubagentExecutionStatus::Failed
                    | DurableBackgroundSubagentExecutionStatus::Cancelled
            ) | (
                DurableBackgroundSubagentExecutionStatus::Running,
                DurableBackgroundSubagentExecutionStatus::Waiting
                    | DurableBackgroundSubagentExecutionStatus::Completed
                    | DurableBackgroundSubagentExecutionStatus::Failed
                    | DurableBackgroundSubagentExecutionStatus::Cancelled
            ) | (
                DurableBackgroundSubagentExecutionStatus::Waiting,
                DurableBackgroundSubagentExecutionStatus::Running
                    | DurableBackgroundSubagentExecutionStatus::Completed
                    | DurableBackgroundSubagentExecutionStatus::Failed
                    | DurableBackgroundSubagentExecutionStatus::Cancelled
            )
        )
}

#[allow(clippy::too_many_lines)]
#[async_trait]
impl SessionStore for InMemorySessionStore {
    async fn commit_run_evidence(
        &self,
        mut commit: RunEvidenceCommit,
    ) -> SessionStoreResult<RunRecord> {
        commit.run.stream_cursors.clone_from(&commit.stream_cursors);
        commit.validate_structure()?;
        let digest = commit.digest()?;
        let key = run_key(&commit.run.session_id, &commit.run.run_id);
        let mut original = self.inner.lock().map_err(store_failed)?;
        if let Some(existing) = resolve_evidence_retry(&original, &key, &commit, &digest)? {
            return Ok(existing);
        }
        commit.validate_terminal_projections()?;
        validate_existing_evidence(&original, &key, &commit)?;
        let staged = Self {
            inner: Arc::new(Mutex::new(original.clone())),
        };
        apply_related_evidence(&staged, &commit)?;
        apply_primary_evidence(&staged, &commit)?;
        let (committed_inner, committed_run) =
            finalize_staged_evidence(&staged, commit, key, digest)?;
        *original = committed_inner;
        Ok(committed_run)
    }

    async fn commit_run_evidence_fenced(
        &self,
        lease: &RunAdmissionLease,
        mut commit: RunEvidenceCommit,
    ) -> SessionStoreResult<RunRecord> {
        if lease.target.session_id != commit.run.session_id
            || lease.target.run_id != commit.run.run_id
        {
            return Err(SessionStoreError::Conflict(
                "run evidence does not match admission target".to_string(),
            ));
        }
        commit.run.stream_cursors.clone_from(&commit.stream_cursors);
        commit.validate_structure()?;
        let digest = commit.digest()?;
        let key = run_key(&commit.run.session_id, &commit.run.run_id);
        let mut original = self.inner.lock().map_err(store_failed)?;
        if let Some(existing) = resolve_evidence_retry(&original, &key, &commit, &digest)? {
            return Ok(existing);
        }
        commit.validate_terminal_projections()?;
        ensure_active_admission_locked(&original, lease, chrono::Utc::now())?;
        validate_existing_evidence(&original, &key, &commit)?;
        let staged = Self {
            inner: Arc::new(Mutex::new(original.clone())),
        };
        apply_related_evidence(&staged, &commit)?;
        apply_primary_evidence(&staged, &commit)?;
        let (committed_inner, committed_run) =
            finalize_staged_evidence(&staged, commit, key, digest)?;
        *original = committed_inner;
        Ok(committed_run)
    }

    async fn append_replay_events_fenced(
        &self,
        lease: &RunAdmissionLease,
        events: Vec<ReplayEvent>,
    ) -> SessionStoreResult<()> {
        let expected_scope = ReplayScope::run(lease.target.run_id.as_str());
        for event in &events {
            if event.scope != expected_scope {
                return Err(SessionStoreError::Conflict(format!(
                    "replay event scope {} does not match admission run {}",
                    event.scope.as_str(),
                    lease.target.run_id.as_str()
                )));
            }
            i64::try_from(event.sequence).map_err(|error| {
                SessionStoreError::Failed(format!("invalid replay event sequence: {error}"))
            })?;
        }

        let mut inner = self.inner.lock().map_err(store_failed)?;
        ensure_active_admission_locked(&inner, lease, chrono::Utc::now())?;
        let mut staged = inner.replay_events.clone();
        for event in events {
            let key = (expected_scope.clone(), event.sequence);
            if let Some(persisted) = staged.get(&key) {
                if persisted != &event {
                    return Err(SessionStoreError::Failed(format!(
                        "replay event conflict for scope {} at sequence {}",
                        expected_scope.as_str(),
                        event.sequence
                    )));
                }
            } else {
                staged.insert(key, event);
            }
        }
        inner.replay_events = staged;
        Ok(())
    }

    async fn commit_checkpoint(
        &self,
        session_id: &SessionId,
        checkpoint: AgentCheckpoint,
    ) -> SessionStoreResult<()> {
        let mut original = self.inner.lock().map_err(store_failed)?;
        let staged = Self {
            inner: Arc::new(Mutex::new(original.clone())),
        };
        if staged.load_session_record(session_id).is_err() {
            staged.save_session_record(SessionRecord::new(session_id.clone()))?;
        }
        let created_run = staged
            .load_run_record(session_id, &checkpoint.run_id)
            .is_err();
        if created_run {
            let mut run = RunRecord::new(
                session_id.clone(),
                checkpoint.run_id.clone(),
                checkpoint.conversation_id.clone(),
            );
            run.status = checkpoint_run_status(checkpoint.resume.status);
            run.terminal_error = checkpoint_terminal_error(checkpoint.resume.status);
            run.trace_context = checkpoint.resume.trace_context.clone();
            run.parent_run_id
                .clone_from(&checkpoint.state.parent_run_id);
            run.parent_task_id
                .clone_from(&checkpoint.state.parent_task_id);
            staged.append_run_record(run)?;
        }
        staged.append_checkpoint_record_with_revision(session_id, checkpoint, !created_run)?;
        let staged_inner = staged.inner.lock().map_err(store_failed)?;
        *original = staged_inner.clone();
        Ok(())
    }

    async fn commit_checkpoint_fenced(
        &self,
        lease: &RunAdmissionLease,
        checkpoint: AgentCheckpoint,
    ) -> SessionStoreResult<()> {
        if lease.target.run_id != checkpoint.run_id {
            return Err(SessionStoreError::Conflict(
                "checkpoint does not match admission target".to_string(),
            ));
        }
        let key = run_key(&lease.target.session_id, &checkpoint.run_id);
        let mut original = self.inner.lock().map_err(store_failed)?;
        if let Some(existing) = original
            .checkpoints
            .get(&key)
            .into_iter()
            .flatten()
            .find(|existing| existing.checkpoint_id == checkpoint.checkpoint_id)
        {
            if existing == &checkpoint {
                return Ok(());
            }
            return Err(SessionStoreError::Failed(format!(
                "checkpoint conflict for session {} run {} checkpoint {}",
                lease.target.session_id.as_str(),
                checkpoint.run_id.as_str(),
                checkpoint.checkpoint_id.as_str()
            )));
        }
        ensure_active_admission_locked(&original, lease, chrono::Utc::now())?;
        let staged = Self {
            inner: Arc::new(Mutex::new(original.clone())),
        };
        if staged
            .load_session_record(&lease.target.session_id)
            .is_err()
        {
            staged.save_session_record(SessionRecord::new(lease.target.session_id.clone()))?;
        }
        let created_run = staged
            .load_run_record(&lease.target.session_id, &checkpoint.run_id)
            .is_err();
        if created_run {
            let mut run = RunRecord::new(
                lease.target.session_id.clone(),
                checkpoint.run_id.clone(),
                checkpoint.conversation_id.clone(),
            );
            run.status = checkpoint_run_status(checkpoint.resume.status);
            run.terminal_error = checkpoint_terminal_error(checkpoint.resume.status);
            run.trace_context = checkpoint.resume.trace_context.clone();
            run.parent_run_id
                .clone_from(&checkpoint.state.parent_run_id);
            run.parent_task_id
                .clone_from(&checkpoint.state.parent_task_id);
            staged.append_run_record(run)?;
        }
        staged.append_checkpoint_record_with_revision(
            &lease.target.session_id,
            checkpoint,
            !created_run,
        )?;
        let staged_inner = staged.inner.lock().map_err(store_failed)?;
        *original = staged_inner.clone();
        Ok(())
    }

    async fn claim_hitl_resume(&self, claim: HitlResumeClaim) -> SessionStoreResult<()> {
        if !claim.is_valid_preflight() {
            return Err(SessionStoreError::Failed(
                "invalid HITL preflight claim".to_string(),
            ));
        }
        let key = run_key(&claim.session_id, &claim.run_id);
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let run = inner.runs.get(&key).ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(&claim.session_id, &claim.run_id))
        })?;
        if run.status != RunStatus::Waiting {
            return Err(SessionStoreError::Failed(format!(
                "run {} is not waiting",
                claim.run_id.as_str()
            )));
        }
        if let Some(existing) = inner.hitl_resume_claims.get(&key) {
            if existing.claim_id == claim.claim_id
                && existing.session_id == claim.session_id
                && existing.run_id == claim.run_id
                && existing.state == HitlResumeClaimState::Preflight
            {
                return Ok(());
            }
            return Err(SessionStoreError::Failed(format!(
                "run {} already has an active resume claim",
                claim.run_id.as_str()
            )));
        }
        inner.hitl_resume_claims.insert(key, claim);
        Ok(())
    }

    async fn start_hitl_resume_effect(
        &self,
        lease: &RunAdmissionLease,
        source_run_id: &RunId,
        claim_id: &str,
    ) -> SessionStoreResult<()> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        ensure_active_admission_locked(&inner, lease, chrono::Utc::now())?;
        let target = inner
            .runs
            .get(&run_key(&lease.target.session_id, &lease.target.run_id))
            .ok_or_else(|| {
                SessionStoreError::NotFound(run_key_label(
                    &lease.target.session_id,
                    &lease.target.run_id,
                ))
            })?;
        if target.restore_from_run_id.as_ref() != Some(source_run_id) || !target.status.is_active()
        {
            return Err(SessionStoreError::Conflict(
                "active admission is not bound to the HITL source run".to_string(),
            ));
        }
        let source_key = run_key(&lease.target.session_id, source_run_id);
        let source = inner.runs.get(&source_key).ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(&lease.target.session_id, source_run_id))
        })?;
        if source.status != RunStatus::Waiting {
            return Err(SessionStoreError::Conflict(
                "HITL source run is not waiting".to_string(),
            ));
        }
        let claim = inner
            .hitl_resume_claims
            .get_mut(&source_key)
            .ok_or_else(|| {
                SessionStoreError::NotFound(format!("resume claim for {}", source_run_id.as_str()))
            })?;
        if claim.claim_id != claim_id
            || claim.session_id != lease.target.session_id
            || claim.run_id != *source_run_id
            || claim.state != HitlResumeClaimState::Admitted
        {
            return Err(SessionStoreError::Conflict(format!(
                "invalid admitted resume claim for run {}",
                source_run_id.as_str()
            )));
        }
        claim.state = HitlResumeClaimState::Started;
        Ok(())
    }

    async fn abort_admitted_hitl_resume(
        &self,
        lease: &RunAdmissionLease,
        source_run_id: &RunId,
        claim_id: &str,
        output_preview: &str,
    ) -> SessionStoreResult<HitlResumeAbortOutcome> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        ensure_active_admission_locked(&inner, lease, chrono::Utc::now())?;
        let target_key = run_key(&lease.target.session_id, &lease.target.run_id);
        let target = inner.runs.get(&target_key).ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(
                &lease.target.session_id,
                &lease.target.run_id,
            ))
        })?;
        if target.restore_from_run_id.as_ref() != Some(source_run_id) || !target.status.is_active()
        {
            return Err(SessionStoreError::Conflict(
                "active admission is not bound to the HITL source run".to_string(),
            ));
        }
        let source_key = run_key(&lease.target.session_id, source_run_id);
        let source = inner.runs.get(&source_key).ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(&lease.target.session_id, source_run_id))
        })?;
        if source.status != RunStatus::Waiting {
            return Err(SessionStoreError::Conflict(
                "HITL source run is not waiting".to_string(),
            ));
        }
        let claim = inner
            .hitl_resume_claims
            .get(&source_key)
            .cloned()
            .ok_or_else(|| {
                SessionStoreError::NotFound(format!("resume claim for {}", source_run_id.as_str()))
            })?;
        if claim.claim_id != claim_id
            || claim.session_id != lease.target.session_id
            || claim.run_id != *source_run_id
        {
            return Err(SessionStoreError::Conflict(format!(
                "invalid resume claim for run {}",
                source_run_id.as_str()
            )));
        }
        if claim.state == HitlResumeClaimState::Started {
            return Ok(HitlResumeAbortOutcome::EffectStarted);
        }
        if claim.state != HitlResumeClaimState::Admitted {
            return Err(SessionStoreError::Conflict(format!(
                "invalid admitted resume claim for run {}",
                source_run_id.as_str()
            )));
        }
        apply_run_status_locked(
            &mut inner,
            &lease.target.session_id,
            &lease.target.run_id,
            RunStatus::Failed,
            Some(output_preview.to_string()),
            Some(RunTerminalError::new(
                "hitl_resume_preparation_failed",
                output_preview,
            )),
            chrono::Utc::now(),
        )?;
        let consumed = inner.hitl_resume_claims.remove(&source_key);
        if consumed.as_ref() != Some(&claim) {
            return Err(SessionStoreError::Conflict(format!(
                "admitted resume claim changed while aborting run {}",
                source_run_id.as_str()
            )));
        }
        Ok(HitlResumeAbortOutcome::AbortedBeforeEffect)
    }

    async fn mark_hitl_resume_started(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
        claim_id: &str,
    ) -> SessionStoreResult<()> {
        let key = run_key(session_id, run_id);
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let claim = inner.hitl_resume_claims.get_mut(&key).ok_or_else(|| {
            SessionStoreError::NotFound(format!("resume claim for {}", run_id.as_str()))
        })?;
        if claim.claim_id != claim_id {
            return Err(SessionStoreError::Failed(format!(
                "resume claim conflict for run {}",
                run_id.as_str()
            )));
        }
        if claim.state == HitlResumeClaimState::Preflight {
            claim.state = HitlResumeClaimState::Started;
        }
        Ok(())
    }

    async fn release_hitl_resume_claim(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
        claim_id: &str,
    ) -> SessionStoreResult<()> {
        let key = run_key(session_id, run_id);
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let Some(existing) = inner.hitl_resume_claims.get(&key) else {
            return Ok(());
        };
        if existing.claim_id != claim_id {
            return Err(SessionStoreError::Failed(format!(
                "resume claim conflict for run {}",
                run_id.as_str()
            )));
        }
        if existing.state != HitlResumeClaimState::Preflight {
            return Err(SessionStoreError::Failed(format!(
                "started resume claim for run {} cannot be released",
                run_id.as_str()
            )));
        }
        inner.hitl_resume_claims.remove(&key);
        Ok(())
    }

    async fn pending_stream_publications(
        &self,
        session_id: &SessionId,
    ) -> SessionStoreResult<Vec<PendingStreamPublication>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        Ok(inner
            .stream_publication_outbox
            .values()
            .filter(|publication| &publication.session_id == session_id)
            .cloned()
            .collect())
    }

    async fn acknowledge_stream_publication(
        &self,
        publication_id: &str,
        target: StreamPublicationTarget,
    ) -> SessionStoreResult<()> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let Some(publication) = inner.stream_publication_outbox.get_mut(publication_id) else {
            return Ok(());
        };
        match target {
            StreamPublicationTarget::Archive => publication.archive_pending = false,
            StreamPublicationTarget::Replay => publication.replay_pending = false,
        }
        if publication.is_complete() {
            inner.stream_publication_outbox.remove(publication_id);
        }
        Ok(())
    }

    async fn enqueue_host_event_publications(
        &self,
        publications: Vec<PendingHostEventPublication>,
    ) -> SessionStoreResult<()> {
        self.enqueue_host_event_publication_batch(&publications)
    }

    async fn pending_host_event_publications(
        &self,
        limit: usize,
    ) -> SessionStoreResult<Vec<PendingHostEventPublication>> {
        self.pending_host_event_publication_batch(limit)
    }

    async fn materialize_host_event_publications(
        &self,
        limit: usize,
    ) -> SessionStoreResult<Vec<DurableHostEventRecord>> {
        self.materialize_host_event_publication_batch(limit)
    }

    async fn replay_host_events(
        &self,
        query: DurableHostEventQuery,
    ) -> SessionStoreResult<DurableHostEventPage> {
        self.replay_host_event_page(query)
    }

    async fn host_event_fence(
        &self,
        scope: &DurableHostEventScope,
        event_classes: &[DurableHostEventClass],
    ) -> SessionStoreResult<Option<u64>> {
        self.host_event_fence_position(scope, event_classes)
    }

    async fn create_session_idempotent(
        &self,
        mut session: SessionRecord,
        idempotency_key: &str,
        command_fingerprint: &str,
    ) -> SessionStoreResult<SessionRecord> {
        let key = (session.namespace_id.clone(), idempotency_key.to_string());
        let mut inner = self.inner.lock().map_err(store_failed)?;
        if let Some((fingerprint, existing)) = inner.session_idempotency.get(&key) {
            if fingerprint == command_fingerprint {
                return Ok(existing.clone());
            }
            return Err(SessionStoreError::IdempotencyConflict(
                idempotency_key.to_string(),
            ));
        }
        if inner.sessions.contains_key(&session.session_id) {
            return Err(SessionStoreError::AlreadyExists(
                session.session_id.as_str().to_string(),
            ));
        }
        session.revision = session.revision.max(1);
        session.updated_at = chrono::Utc::now();
        inner
            .sessions
            .insert(session.session_id.clone(), session.clone());
        inner
            .session_idempotency
            .insert(key, (command_fingerprint.to_string(), session.clone()));
        Ok(session)
    }

    async fn create_session_idempotent_with_host_events(
        &self,
        mut session: SessionRecord,
        idempotency_key: &str,
        command_fingerprint: &str,
        publications: Vec<PendingHostEventPublication>,
    ) -> SessionStoreResult<SessionRecord> {
        let key = (session.namespace_id.clone(), idempotency_key.to_string());
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut staged = inner.clone();
        let result = if let Some((fingerprint, existing)) = staged.session_idempotency.get(&key) {
            if fingerprint != command_fingerprint {
                return Err(SessionStoreError::IdempotencyConflict(
                    idempotency_key.to_string(),
                ));
            }
            existing.clone()
        } else {
            if staged.sessions.contains_key(&session.session_id) {
                return Err(SessionStoreError::AlreadyExists(
                    session.session_id.as_str().to_string(),
                ));
            }
            session.revision = session.revision.max(1);
            session.updated_at = session_mutation_time(&publications)?;
            staged
                .sessions
                .insert(session.session_id.clone(), session.clone());
            staged
                .session_idempotency
                .insert(key, (command_fingerprint.to_string(), session.clone()));
            session
        };
        enqueue_host_event_publications_locked(&mut staged, &publications)?;
        *inner = staged;
        Ok(result)
    }

    async fn load_session_mutation_receipt(
        &self,
        namespace_id: &str,
        idempotency_key: &str,
        command_fingerprint: &str,
    ) -> SessionStoreResult<Option<SessionRecord>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        let key = (namespace_id.to_string(), idempotency_key.to_string());
        let Some((fingerprint, session)) = inner.session_idempotency.get(&key) else {
            return Ok(None);
        };
        if fingerprint != command_fingerprint {
            return Err(SessionStoreError::IdempotencyConflict(
                idempotency_key.to_string(),
            ));
        }
        Ok(Some(session.clone()))
    }

    async fn update_managed_session(
        &self,
        command: UpdateManagedSession,
        command_fingerprint: &str,
    ) -> SessionStoreResult<SessionRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let namespace = inner
            .sessions
            .get(&command.session_id)
            .ok_or_else(|| SessionStoreError::NotFound(command.session_id.as_str().to_string()))?
            .namespace_id
            .clone();
        let idempotency_key = (namespace, command.idempotency_key.clone());
        if let Some((fingerprint, existing)) = inner.session_idempotency.get(&idempotency_key) {
            if fingerprint == command_fingerprint {
                return Ok(existing.clone());
            }
            return Err(SessionStoreError::IdempotencyConflict(
                command.idempotency_key,
            ));
        }
        let session = inner
            .sessions
            .get_mut(&command.session_id)
            .ok_or_else(|| SessionStoreError::NotFound(command.session_id.as_str().to_string()))?;
        if session.revision != command.expected_revision {
            return Err(SessionStoreError::Conflict(format!(
                "expected revision {}, current {}",
                command.expected_revision, session.revision
            )));
        }
        if session.deletion_fence.blocks_continuation() || session.status == SessionStatus::Deleted
        {
            return Err(SessionStoreError::Conflict(
                "session is deleting or deleted".to_string(),
            ));
        }
        if let Some(title) = command.patch.title {
            session.title = title.map(|value| value.chars().take(256).collect());
        }
        if let Some(profile) = command.patch.profile {
            session.profile = profile;
        }
        if let Some(archived) = command.patch.archived {
            session.status = if archived {
                SessionStatus::Archived
            } else {
                SessionStatus::Active
            };
        }
        for (key, value) in command.patch.metadata {
            if value.is_null() {
                session.metadata.remove(&key);
            } else {
                session.metadata.insert(key, value);
            }
        }
        session.revision = session.revision.saturating_add(1);
        session.updated_at = chrono::Utc::now();
        let result = session.clone();
        inner.session_idempotency.insert(
            idempotency_key,
            (command_fingerprint.to_string(), result.clone()),
        );
        Ok(result)
    }

    async fn update_managed_session_with_host_events(
        &self,
        command: UpdateManagedSession,
        command_fingerprint: &str,
        publications: Vec<PendingHostEventPublication>,
    ) -> SessionStoreResult<SessionRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut staged = inner.clone();
        let namespace = staged
            .sessions
            .get(&command.session_id)
            .ok_or_else(|| SessionStoreError::NotFound(command.session_id.as_str().to_string()))?
            .namespace_id
            .clone();
        let idempotency_key = (namespace, command.idempotency_key.clone());
        let result = if let Some((fingerprint, existing)) =
            staged.session_idempotency.get(&idempotency_key)
        {
            if fingerprint != command_fingerprint {
                return Err(SessionStoreError::IdempotencyConflict(
                    command.idempotency_key,
                ));
            }
            existing.clone()
        } else {
            let session = staged
                .sessions
                .get_mut(&command.session_id)
                .ok_or_else(|| {
                    SessionStoreError::NotFound(command.session_id.as_str().to_string())
                })?;
            if session.revision != command.expected_revision {
                return Err(SessionStoreError::Conflict(format!(
                    "expected revision {}, current {}",
                    command.expected_revision, session.revision
                )));
            }
            if session.deletion_fence.blocks_continuation()
                || session.status == SessionStatus::Deleted
            {
                return Err(SessionStoreError::Conflict(
                    "session is deleting or deleted".to_string(),
                ));
            }
            if let Some(title) = command.patch.title {
                session.title = title.map(|value| value.chars().take(256).collect());
            }
            if let Some(profile) = command.patch.profile {
                session.profile = profile;
            }
            if let Some(archived) = command.patch.archived {
                session.status = if archived {
                    SessionStatus::Archived
                } else {
                    SessionStatus::Active
                };
            }
            for (key, value) in command.patch.metadata {
                if value.is_null() {
                    session.metadata.remove(&key);
                } else {
                    session.metadata.insert(key, value);
                }
            }
            session.revision = session.revision.saturating_add(1);
            session.updated_at = session_mutation_time(&publications)?;
            let result = session.clone();
            staged.session_idempotency.insert(
                idempotency_key,
                (command_fingerprint.to_string(), result.clone()),
            );
            result
        };
        enqueue_host_event_publications_locked(&mut staged, &publications)?;
        *inner = staged;
        Ok(result)
    }

    async fn acquire_session_deletion_fence(
        &self,
        session_id: &SessionId,
        expected_revision: u64,
        fence_id: &str,
        requested_by: &str,
        idempotency_key: &str,
        command_fingerprint: &str,
    ) -> SessionStoreResult<SessionRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let namespace = inner
            .sessions
            .get(session_id)
            .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?
            .namespace_id
            .clone();
        let key = (namespace, idempotency_key.to_string());
        if let Some((fingerprint, existing)) = inner.session_idempotency.get(&key) {
            if fingerprint == command_fingerprint {
                return Ok(existing.clone());
            }
            return Err(SessionStoreError::IdempotencyConflict(
                idempotency_key.to_string(),
            ));
        }
        if inner
            .sessions
            .get(session_id)
            .is_some_and(|session| session.active_run_id.is_some())
            || inner
                .run_admissions
                .contains_key(&ManagedSessionTarget::new(&key.0, session_id.clone()))
        {
            return Err(SessionStoreError::RunConflict(
                "session still has an admitted active run".to_string(),
            ));
        }
        let now = chrono::Utc::now();
        if inner.background_subagents.values().any(|record| {
            record.namespace_id == key.0
                && &record.parent_session_id == session_id
                && !record.execution_status.is_terminal()
                && !record.owner_lease.expired_at(now)
        }) {
            return Err(SessionStoreError::RunConflict(
                "session still has active background-subagent ownership".to_string(),
            ));
        }
        let session = inner
            .sessions
            .get_mut(session_id)
            .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?;
        if session.revision != expected_revision {
            return Err(SessionStoreError::Conflict(format!(
                "expected revision {expected_revision}, current {}",
                session.revision
            )));
        }
        if !matches!(session.deletion_fence, SessionDeletionFence::Stable) {
            return Err(SessionStoreError::Conflict(
                "session already has a deletion fence".to_string(),
            ));
        }
        session.deletion_fence = SessionDeletionFence::Deleting {
            fence_id: fence_id.to_string(),
            expected_revision,
            requested_by: requested_by.to_string(),
            started_at: chrono::Utc::now(),
        };
        session.revision = session.revision.saturating_add(1);
        session.updated_at = chrono::Utc::now();
        let result = session.clone();
        inner
            .session_idempotency
            .insert(key, (command_fingerprint.to_string(), result.clone()));
        Ok(result)
    }

    async fn tombstone_session(
        &self,
        session_id: &SessionId,
        fence_id: &str,
    ) -> SessionStoreResult<SessionRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        if inner
            .runs
            .values()
            .any(|run| &run.session_id == session_id && run.status.is_active())
        {
            return Err(SessionStoreError::RunConflict(
                "session still has an active run".to_string(),
            ));
        }
        let now = chrono::Utc::now();
        if inner.background_subagents.values().any(|record| {
            &record.parent_session_id == session_id
                && !record.execution_status.is_terminal()
                && !record.owner_lease.expired_at(now)
        }) {
            return Err(SessionStoreError::RunConflict(
                "session still has active background-subagent ownership".to_string(),
            ));
        }
        let session = inner
            .sessions
            .get_mut(session_id)
            .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?;
        match &session.deletion_fence {
            SessionDeletionFence::Deleted {
                fence_id: current, ..
            } if current == fence_id => {
                return Ok(session.clone());
            }
            SessionDeletionFence::Deleting {
                fence_id: current, ..
            } if current == fence_id => {}
            _ => {
                return Err(SessionStoreError::Conflict(
                    "deletion fence mismatch".to_string(),
                ));
            }
        }
        session.status = SessionStatus::Deleted;
        session.active_run_id = None;
        session.deletion_fence = SessionDeletionFence::Deleted {
            fence_id: fence_id.to_string(),
            deleted_at: chrono::Utc::now(),
        };
        session.revision = session.revision.saturating_add(1);
        session.updated_at = chrono::Utc::now();
        Ok(session.clone())
    }

    async fn tombstone_session_idempotent_with_host_events(
        &self,
        session_id: &SessionId,
        fence_id: &str,
        idempotency_key: &str,
        command_fingerprint: &str,
        publications: Vec<PendingHostEventPublication>,
    ) -> SessionStoreResult<SessionRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut staged = inner.clone();
        let namespace = staged
            .sessions
            .get(session_id)
            .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?
            .namespace_id
            .clone();
        let receipt_key = (namespace, idempotency_key.to_string());
        let (fingerprint, receipt_session) = staged
            .session_idempotency
            .get(&receipt_key)
            .ok_or_else(|| SessionStoreError::NotFound(idempotency_key.to_string()))?;
        if fingerprint != command_fingerprint {
            return Err(SessionStoreError::IdempotencyConflict(
                idempotency_key.to_string(),
            ));
        }
        if receipt_session.session_id != *session_id {
            return Err(SessionStoreError::Conflict(
                "session deletion receipt target mismatch".to_string(),
            ));
        }
        let already_deleted = staged.sessions.get(session_id).is_some_and(|session| {
            matches!(
                &session.deletion_fence,
                SessionDeletionFence::Deleted {
                    fence_id: current,
                    ..
                } if current == fence_id
            )
        });
        if !already_deleted {
            if staged
                .runs
                .values()
                .any(|run| &run.session_id == session_id && run.status.is_active())
            {
                return Err(SessionStoreError::RunConflict(
                    "session still has an active run".to_string(),
                ));
            }
            let now = chrono::Utc::now();
            if staged.background_subagents.values().any(|record| {
                &record.parent_session_id == session_id
                    && !record.execution_status.is_terminal()
                    && !record.owner_lease.expired_at(now)
            }) {
                return Err(SessionStoreError::RunConflict(
                    "session still has active background-subagent ownership".to_string(),
                ));
            }
            let session = staged
                .sessions
                .get_mut(session_id)
                .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?;
            match &session.deletion_fence {
                SessionDeletionFence::Deleting {
                    fence_id: current, ..
                } if current == fence_id => {}
                _ => {
                    return Err(SessionStoreError::Conflict(
                        "deletion fence mismatch".to_string(),
                    ));
                }
            }
            let deleted_at = session_mutation_time(&publications)?;
            session.status = SessionStatus::Deleted;
            session.active_run_id = None;
            session.deletion_fence = SessionDeletionFence::Deleted {
                fence_id: fence_id.to_string(),
                deleted_at,
            };
            session.revision = session.revision.saturating_add(1);
            session.updated_at = deleted_at;
        }
        let result = staged
            .sessions
            .get(session_id)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?;
        staged.session_idempotency.insert(
            receipt_key,
            (command_fingerprint.to_string(), result.clone()),
        );
        enqueue_host_event_publications_locked(&mut staged, &publications)?;
        *inner = staged;
        Ok(result)
    }

    async fn session_continuation_fence(
        &self,
        namespace_id: &str,
        session_id: &SessionId,
    ) -> SessionStoreResult<SessionContinuationFence> {
        let inner = self.inner.lock().map_err(store_failed)?;
        let session = inner
            .sessions
            .get(session_id)
            .filter(|session| session.namespace_id == namespace_id)
            .ok_or_else(|| SessionStoreError::NotFound(session_id.as_str().to_string()))?;
        let fence_id = match &session.deletion_fence {
            SessionDeletionFence::Stable => None,
            SessionDeletionFence::Deleting { fence_id, .. }
            | SessionDeletionFence::Deleted { fence_id, .. } => Some(fence_id.clone()),
        };
        Ok(SessionContinuationFence {
            target: ManagedSessionTarget::new(namespace_id, session_id.clone()),
            revision: session.revision,
            continuation_allowed: !session.deletion_fence.blocks_continuation()
                && session.status != SessionStatus::Deleted,
            fence_id,
        })
    }

    async fn acquire_run_admission(
        &self,
        request: AcquireRunAdmission,
    ) -> SessionStoreResult<RunAdmissionReceipt> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut staged = inner.clone();
        let receipt = acquire_run_admission_locked(&mut staged, request)?;
        *inner = staged;
        Ok(receipt)
    }

    async fn load_run_admission_receipt(
        &self,
        namespace_id: &str,
        idempotency_key: &str,
        command_fingerprint: &str,
    ) -> SessionStoreResult<Option<RunAdmissionReceipt>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        let Some((fingerprint, receipt)) = inner
            .run_admission_idempotency
            .get(&(namespace_id.to_string(), idempotency_key.to_string()))
        else {
            return Ok(None);
        };
        if fingerprint != command_fingerprint {
            return Err(SessionStoreError::IdempotencyConflict(
                idempotency_key.to_string(),
            ));
        }
        let mut receipt = receipt.clone();
        receipt.idempotent_replay = true;
        Ok(Some(receipt))
    }

    async fn heartbeat_run_admission(
        &self,
        lease: &RunAdmissionLease,
        lease_expires_at: chrono::DateTime<chrono::Utc>,
    ) -> SessionStoreResult<RunAdmissionLease> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let key = ManagedSessionTarget::new(
            lease.target.namespace_id.clone(),
            lease.target.session_id.clone(),
        );
        let current = inner
            .run_admissions
            .get_mut(&key)
            .ok_or_else(|| SessionStoreError::NotFound(lease.admission_id.clone()))?;
        if current.admission_id != lease.admission_id
            || current.host_instance_id != lease.host_instance_id
            || current.fencing_generation != lease.fencing_generation
            || current.target != lease.target
            || current.expired_at(chrono::Utc::now())
        {
            return Err(SessionStoreError::Conflict(
                "stale admission owner".to_string(),
            ));
        }
        current.heartbeat_at = chrono::Utc::now();
        current.lease_expires_at = lease_expires_at;
        Ok(current.clone())
    }

    async fn release_run_admission(&self, lease: &RunAdmissionLease) -> SessionStoreResult<()> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let key = ManagedSessionTarget::new(
            lease.target.namespace_id.clone(),
            lease.target.session_id.clone(),
        );
        if let Some(current) = inner.run_admissions.get(&key) {
            if current.admission_id != lease.admission_id
                || current.host_instance_id != lease.host_instance_id
                || current.fencing_generation != lease.fencing_generation
                || current.target != lease.target
                || current.expired_at(chrono::Utc::now())
            {
                return Err(SessionStoreError::Conflict(
                    "stale admission owner".to_string(),
                ));
            }
            inner.run_admissions.remove(&key);
        }
        Ok(())
    }

    async fn update_run_status_fenced(
        &self,
        lease: &RunAdmissionLease,
        status: RunStatus,
        output_preview: Option<String>,
    ) -> SessionStoreResult<RunRecord> {
        if !status.is_active() {
            return Err(SessionStoreError::Conflict(
                "fenced status updates are non-terminal; use finalize_run_admission".to_string(),
            ));
        }
        let mut inner = self.inner.lock().map_err(store_failed)?;
        ensure_active_admission_locked(&inner, lease, chrono::Utc::now())?;
        apply_run_status_locked(
            &mut inner,
            &lease.target.session_id,
            &lease.target.run_id,
            status,
            output_preview,
            None,
            chrono::Utc::now(),
        )
    }

    async fn finalize_run_admission(
        &self,
        lease: &RunAdmissionLease,
        terminal: RunTerminalProjection,
    ) -> SessionStoreResult<RunRecord> {
        if terminal.status.is_active() {
            return Err(SessionStoreError::Conflict(
                "run admission can only finalize to a non-active status".to_string(),
            ));
        }
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let session_key = ManagedSessionTarget::new(
            lease.target.namespace_id.clone(),
            lease.target.session_id.clone(),
        );
        if !inner.run_admissions.contains_key(&session_key) {
            let run = inner
                .runs
                .get(&run_key(&lease.target.session_id, &lease.target.run_id))
                .cloned()
                .ok_or_else(|| {
                    SessionStoreError::NotFound(run_key_label(
                        &lease.target.session_id,
                        &lease.target.run_id,
                    ))
                })?;
            if terminal.matches(&run) {
                return Ok(run);
            }
            return Err(SessionStoreError::Conflict(
                "stale admission owner".to_string(),
            ));
        }
        ensure_active_admission_locked(&inner, lease, chrono::Utc::now())?;
        let mut staged = inner.clone();
        let target_key = run_key(&lease.target.session_id, &lease.target.run_id);
        let committed = staged.runs.get(&target_key).cloned().ok_or_else(|| {
            SessionStoreError::NotFound(run_key_label(
                &lease.target.session_id,
                &lease.target.run_id,
            ))
        })?;
        let (run, changed) = if committed.status.is_terminal() {
            // Complete run evidence may be committed before its admission lease is released.
            // Cleanup owns only the matching lease and must never replace that evidence with a
            // process-local fallback outcome.
            (committed, false)
        } else {
            terminal
                .validate()
                .map_err(|error| SessionStoreError::Conflict(error.to_string()))?;
            (
                apply_run_status_locked(
                    &mut staged,
                    &lease.target.session_id,
                    &lease.target.run_id,
                    terminal.status,
                    terminal.output_preview,
                    terminal.error,
                    chrono::Utc::now(),
                )?,
                true,
            )
        };
        if changed {
            let mut publications = Vec::new();
            append_authoritative_run_publications(
                &mut publications,
                &format!(
                    "run-admission-finalize:{}:{}:{}",
                    lease.admission_id, lease.fencing_generation, run.revision
                ),
                std::iter::once(&run),
            )?;
            enqueue_host_event_publications_locked(&mut staged, &publications)?;
        }
        reconcile_run_control_intents_locked(&mut staged, lease, chrono::Utc::now())?;
        staged.run_admissions.remove(&session_key);
        *inner = staged;
        Ok(run)
    }

    async fn load_run_admission(
        &self,
        target: &ManagedRunTarget,
    ) -> SessionStoreResult<Option<RunAdmissionLease>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        Ok(inner
            .run_admissions
            .get(&ManagedSessionTarget::new(
                target.namespace_id.clone(),
                target.session_id.clone(),
            ))
            .filter(|lease| &lease.target == target)
            .cloned())
    }

    async fn reconcile_expired_run_admissions(
        &self,
        namespace_id: &str,
        now: chrono::DateTime<chrono::Utc>,
    ) -> SessionStoreResult<Vec<ManagedRunTarget>> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut staged = inner.clone();
        let expired = staged
            .run_admissions
            .iter()
            .filter(|(session, lease)| {
                session.namespace_id == namespace_id && lease.expired_at(now)
            })
            .map(|(session, lease)| (session.clone(), lease.clone()))
            .collect::<Vec<_>>();
        for (session_target, lease) in &expired {
            let target = &lease.target;
            let replacement_key = run_key(&target.session_id, &target.run_id);
            let replacement = staged.runs.get(&replacement_key).cloned().ok_or_else(|| {
                SessionStoreError::NotFound(run_key_label(&target.session_id, &target.run_id))
            })?;
            if replacement.status.is_active() {
                let effect_started =
                    terminalize_started_hitl_source_locked(&mut staged, &replacement, now)?;
                let mut authoritative_runs = Vec::with_capacity(2);
                if effect_started
                    && let Some(source_run_id) = replacement.restore_from_run_id.as_ref()
                    && let Some(source) = staged
                        .runs
                        .get(&run_key(&target.session_id, source_run_id))
                        .cloned()
                {
                    authoritative_runs.push(source);
                }
                let run = staged.runs.get_mut(&replacement_key).ok_or_else(|| {
                    SessionStoreError::NotFound(run_key_label(&target.session_id, &target.run_id))
                })?;
                run.status = RunStatus::Cancelled;
                run.output_preview = Some("interrupted after host lease expired".to_string());
                run.terminal_error = Some(RunTerminalError::new(
                    "admission_lease_expired",
                    "interrupted after host lease expired",
                ));
                advance_run_revision(run)?;
                run.updated_at = now;
                if effect_started {
                    ContinuationEffectState::indeterminate()
                        .insert_into(&mut run.metadata)
                        .map_err(|error| SessionStoreError::Failed(error.to_string()))?;
                }
                authoritative_runs.push(run.clone());
                let mut publications = Vec::new();
                append_authoritative_run_publications(
                    &mut publications,
                    &format!(
                        "run-admission-expired:{}:{}",
                        lease.admission_id, lease.fencing_generation
                    ),
                    authoritative_runs.iter(),
                )?;
                enqueue_host_event_publications_locked(&mut staged, &publications)?;
            }
            if let Some(session) = staged.sessions.get_mut(&target.session_id) {
                if session.active_run_id.as_ref() == Some(&target.run_id) {
                    session.active_run_id = None;
                }
                session.revision = session.revision.saturating_add(1);
                session.updated_at = now;
            }
            reconcile_run_control_intents_locked(&mut staged, lease, now)?;
            staged.run_admissions.remove(session_target);
        }
        *inner = staged;
        Ok(expired.into_iter().map(|(_, lease)| lease.target).collect())
    }

    async fn admit_run_control(
        &self,
        request: AdmitRunControl,
    ) -> SessionStoreResult<DurableRunControlIntent> {
        if request.authority_binding.is_empty()
            || request.operation_id.is_empty()
            || request.receipt_id.is_empty()
            || request.idempotency_key.is_empty()
            || request.command_fingerprint.is_empty()
        {
            return Err(SessionStoreError::Conflict(
                "durable run control identity fields cannot be empty".to_string(),
            ));
        }
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let authority_key = (
            request.authority_binding.clone(),
            request.idempotency_key.clone(),
        );
        if let Some(intent_key) = inner.run_control_authority_keys.get(&authority_key)
            && let Some(existing) = inner.run_control_intents.get(intent_key)
        {
            return if existing.matches_admission(&request) {
                Ok(existing.clone())
            } else {
                Err(SessionStoreError::IdempotencyConflict(
                    request.idempotency_key,
                ))
            };
        }
        let intent_key = (request.lease.target.clone(), request.operation_id.clone());
        if let Some(existing) = inner.run_control_intents.get(&intent_key) {
            return if existing.matches_admission(&request) {
                Ok(existing.clone())
            } else {
                Err(SessionStoreError::Conflict(format!(
                    "run control operation {} already has different evidence",
                    request.operation_id
                )))
            };
        }
        ensure_active_admission_locked(&inner, &request.lease, chrono::Utc::now())?;
        let receipt_key = (
            request.lease.target.clone(),
            request.idempotency_key.clone(),
        );
        if let Some(existing_id) = inner.control_idempotency.get(&receipt_key) {
            return Err(SessionStoreError::IdempotencyConflict(existing_id.clone()));
        }
        if inner.control_receipts.contains_key(&request.receipt_id) {
            return Err(SessionStoreError::Conflict(format!(
                "control receipt {} already exists",
                request.receipt_id
            )));
        }
        let intent = request.into_intent();
        inner
            .control_idempotency
            .insert(receipt_key, intent.receipt.receipt_id.clone());
        inner
            .control_receipts
            .insert(intent.receipt.receipt_id.clone(), intent.receipt.clone());
        inner
            .run_control_authority_keys
            .insert(authority_key, intent_key.clone());
        inner.run_control_intents.insert(intent_key, intent.clone());
        Ok(intent)
    }

    async fn load_run_control_intent(
        &self,
        target: &ManagedRunTarget,
        operation_id: &str,
    ) -> SessionStoreResult<Option<DurableRunControlIntent>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        Ok(inner
            .run_control_intents
            .get(&(target.clone(), operation_id.to_string()))
            .cloned())
    }

    async fn list_run_control_intents(
        &self,
        target: &ManagedRunTarget,
        statuses: &[DurableRunControlStatus],
        limit: usize,
    ) -> SessionStoreResult<Vec<DurableRunControlIntent>> {
        if limit == 0 || limit > super::MAX_STABLE_PAGE_SIZE {
            return Err(SessionStoreError::Conflict(format!(
                "run control page limit must be between 1 and {}",
                super::MAX_STABLE_PAGE_SIZE
            )));
        }
        let inner = self.inner.lock().map_err(store_failed)?;
        let mut intents = inner
            .run_control_intents
            .values()
            .filter(|intent| {
                intent.target == *target
                    && (statuses.is_empty() || statuses.contains(&intent.status))
            })
            .cloned()
            .collect::<Vec<_>>();
        intents.sort_by(|left, right| {
            left.created_at
                .cmp(&right.created_at)
                .then_with(|| left.operation_id.cmp(&right.operation_id))
        });
        intents.truncate(limit);
        Ok(intents)
    }

    async fn advance_run_control_intent(
        &self,
        lease: &RunAdmissionLease,
        operation_id: &str,
        expected: DurableRunControlStatus,
        next: DurableRunControlStatus,
        occurred_at: chrono::DateTime<chrono::Utc>,
    ) -> SessionStoreResult<DurableRunControlIntent> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        ensure_active_admission_locked(&inner, lease, chrono::Utc::now())?;
        let key = (lease.target.clone(), operation_id.to_string());
        let mut intent = inner
            .run_control_intents
            .get(&key)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(operation_id.to_string()))?;
        if intent.admission_id != lease.admission_id
            || intent.host_instance_id != lease.host_instance_id
            || intent.fencing_generation != lease.fencing_generation
        {
            return Err(SessionStoreError::StaleFence(
                "run control intent belongs to a stale admission".to_string(),
            ));
        }
        if intent.status != expected && intent.status != next {
            return Err(SessionStoreError::Conflict(format!(
                "run control operation {operation_id} is {}, expected {}",
                intent.status.as_str(),
                expected.as_str()
            )));
        }
        intent
            .advance(next, occurred_at)
            .map_err(|error| SessionStoreError::Conflict(error.to_string()))?;
        inner
            .control_receipts
            .insert(intent.receipt.receipt_id.clone(), intent.receipt.clone());
        inner.run_control_intents.insert(key, intent.clone());
        Ok(intent)
    }

    async fn reconcile_run_control_intent(
        &self,
        target: &ManagedRunTarget,
        operation_id: &str,
        occurred_at: chrono::DateTime<chrono::Utc>,
    ) -> SessionStoreResult<DurableRunControlIntent> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let key = (target.clone(), operation_id.to_string());
        let mut intent = inner
            .run_control_intents
            .get(&key)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(operation_id.to_string()))?;
        intent
            .advance(DurableRunControlStatus::Reconciled, occurred_at)
            .map_err(|error| SessionStoreError::Conflict(error.to_string()))?;
        inner
            .control_receipts
            .insert(intent.receipt.receipt_id.clone(), intent.receipt.clone());
        inner.run_control_intents.insert(key, intent.clone());
        Ok(intent)
    }

    async fn load_control_receipt(
        &self,
        target: &ManagedRunTarget,
        idempotency_key: &str,
    ) -> SessionStoreResult<Option<DurableControlReceipt>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        let key = (target.clone(), idempotency_key.to_string());
        Ok(inner
            .control_idempotency
            .get(&key)
            .and_then(|receipt_id| inner.control_receipts.get(receipt_id))
            .cloned())
    }

    async fn reserve_control_receipt(
        &self,
        receipt: DurableControlReceipt,
    ) -> SessionStoreResult<DurableControlReceipt> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let key = (receipt.target.clone(), receipt.idempotency_key.clone());
        if let Some(receipt_id) = inner.control_idempotency.get(&key)
            && let Some(existing) = inner.control_receipts.get(receipt_id)
        {
            if existing.command_fingerprint == receipt.command_fingerprint {
                return Ok(existing.clone());
            }
            return Err(SessionStoreError::IdempotencyConflict(
                receipt.idempotency_key,
            ));
        }
        let session_key = ManagedSessionTarget::new(
            receipt.target.namespace_id.clone(),
            receipt.target.session_id.clone(),
        );
        let lease = inner.run_admissions.get(&session_key).ok_or_else(|| {
            SessionStoreError::Conflict("run has no active owner lease".to_string())
        })?;
        if lease.target != receipt.target || lease.fencing_generation != receipt.fencing_generation
        {
            return Err(SessionStoreError::Conflict(
                "stale control generation".to_string(),
            ));
        }
        inner
            .control_idempotency
            .insert(key, receipt.receipt_id.clone());
        inner
            .control_receipts
            .insert(receipt.receipt_id.clone(), receipt.clone());
        Ok(receipt)
    }

    async fn update_control_receipt_state(
        &self,
        receipt_id: &str,
        state: &str,
    ) -> SessionStoreResult<DurableControlReceipt> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let receipt = inner
            .control_receipts
            .get_mut(receipt_id)
            .ok_or_else(|| SessionStoreError::NotFound(receipt_id.to_string()))?;
        receipt.state = state.to_string();
        Ok(receipt.clone())
    }

    async fn drain_background_subagent_operations(&self) -> SessionStoreResult<()> {
        Ok(())
    }

    async fn record_background_subagent_acceptance(
        &self,
        record: BackgroundSubagentRecord,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        if !record.is_valid_acceptance() {
            return Err(SessionStoreError::Conflict(
                "invalid background-subagent acceptance record".to_string(),
            ));
        }
        let mut inner = self.inner.lock().map_err(store_failed)?;
        if let Some(existing) = inner.background_subagents.get(&record.attempt_id) {
            return if same_background_identity(existing, &record) {
                Ok(existing.clone())
            } else {
                Err(SessionStoreError::Conflict(format!(
                    "background attempt {} already exists with different identity",
                    record.attempt_id.as_str()
                )))
            };
        }
        if record.owner_lease.expired_at(chrono::Utc::now()) {
            return Err(SessionStoreError::Conflict(
                "background-subagent acceptance owner lease is already expired".to_string(),
            ));
        }
        let session = inner
            .sessions
            .get(&record.parent_session_id)
            .filter(|session| session.namespace_id == record.namespace_id)
            .ok_or_else(|| {
                SessionStoreError::NotFound(record.parent_session_id.as_str().to_string())
            })?;
        if session.status != SessionStatus::Active || session.deletion_fence.blocks_continuation() {
            return Err(SessionStoreError::Conflict(
                "session cannot admit background delegation".to_string(),
            ));
        }
        if !inner
            .runs
            .contains_key(&run_key(&record.parent_session_id, &record.parent_run_id))
        {
            return Err(SessionStoreError::NotFound(format!(
                "{}:{}",
                record.parent_session_id.as_str(),
                record.parent_run_id.as_str()
            )));
        }
        if inner.background_subagents.values().any(|existing| {
            existing.namespace_id == record.namespace_id
                && existing.parent_session_id == record.parent_session_id
                && existing.agent_id == record.agent_id
                && !existing.execution_status.is_terminal()
        }) {
            return Err(SessionStoreError::Conflict(format!(
                "background agent {} already has an active durable attempt",
                record.agent_id
            )));
        }
        inner
            .background_subagents
            .insert(record.attempt_id.clone(), record.clone());
        Ok(record)
    }

    async fn update_background_subagent_execution(
        &self,
        mut record: BackgroundSubagentRecord,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let current = inner
            .background_subagents
            .get(&record.attempt_id)
            .ok_or_else(|| SessionStoreError::NotFound(record.attempt_id.as_str().to_string()))?;
        ensure_background_parent_writable(&inner, current)?;
        if current.owner_lease.expired_at(chrono::Utc::now())
            || !same_background_identity(current, &record)
            || !same_background_owner(current, &record)
            || current.execution_status.is_terminal()
            || record.execution_status.is_terminal()
            || !valid_background_transition(current.execution_status, record.execution_status)
            || !same_background_non_execution_state(current, &record)
        {
            return Err(SessionStoreError::Conflict(format!(
                "invalid background execution transition for {}",
                record.attempt_id.as_str()
            )));
        }
        record.owner_lease = current.owner_lease.clone();
        inner
            .background_subagents
            .insert(record.attempt_id.clone(), record.clone());
        Ok(record)
    }

    async fn heartbeat_background_subagent(
        &self,
        attempt_id: &starweaver_core::SubagentAttemptId,
        host_instance_id: &str,
        fencing_generation: u64,
        lease_expires_at: chrono::DateTime<chrono::Utc>,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let now = chrono::Utc::now();
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let identity = inner
            .background_subagents
            .get(attempt_id)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(attempt_id.as_str().to_string()))?;
        ensure_background_parent_writable(&inner, &identity)?;
        let record = inner
            .background_subagents
            .get_mut(attempt_id)
            .ok_or_else(|| SessionStoreError::NotFound(attempt_id.as_str().to_string()))?;
        if record.execution_status.is_terminal()
            || record.owner_lease.expired_at(now)
            || record.owner_lease.host_instance_id != host_instance_id
            || record.owner_lease.fencing_generation != fencing_generation
            || lease_expires_at <= now
        {
            return Err(SessionStoreError::Conflict(
                "stale or invalid background-subagent owner heartbeat".to_string(),
            ));
        }
        record.owner_lease.heartbeat_at = now;
        record.owner_lease.lease_expires_at = lease_expires_at;
        Ok(record.clone())
    }

    async fn commit_background_subagent_terminal(
        &self,
        commit: BackgroundSubagentTerminalCommit,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        commit_background_terminal(
            &mut inner,
            commit.record,
            commit.artifact,
            commit.artifact_limits,
        )
    }

    async fn load_background_subagent_artifact(
        &self,
        artifact_ref: &str,
    ) -> SessionStoreResult<BackgroundSubagentArtifact> {
        let artifact = self
            .inner
            .lock()
            .map_err(store_failed)?
            .background_artifacts
            .get(artifact_ref)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(artifact_ref.to_string()))?;
        if artifact.expires_at <= chrono::Utc::now() {
            return Err(SessionStoreError::NotFound(artifact_ref.to_string()));
        }
        if !artifact.is_valid() {
            return Err(SessionStoreError::Conflict(
                "background-subagent artifact failed integrity validation".to_string(),
            ));
        }
        Ok(artifact)
    }

    async fn expire_background_subagent_retention(
        &self,
        namespace_id: &str,
        now: chrono::DateTime<chrono::Utc>,
        limit: usize,
    ) -> SessionStoreResult<Vec<BackgroundSubagentRecord>> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut attempt_ids = inner
            .background_subagents
            .values()
            .filter(|record| {
                record.namespace_id == namespace_id
                    && record.execution_status.is_terminal()
                    && record.retention_status
                        != crate::DurableBackgroundSubagentRetentionStatus::Expired
                    && record
                        .retention_expires_at
                        .is_some_and(|deadline| deadline <= now)
            })
            .map(|record| (record.retention_expires_at, record.attempt_id.clone()))
            .collect::<Vec<_>>();
        attempt_ids.sort();
        attempt_ids.truncate(limit);
        let mut expired = Vec::with_capacity(attempt_ids.len());
        let mut artifact_refs = Vec::new();
        for (_, attempt_id) in attempt_ids {
            if !inner
                .background_terminal_fingerprints
                .contains_key(&attempt_id)
                && let Some(record) = inner.background_subagents.get(&attempt_id).cloned()
                && let Some(fingerprint) =
                    reconstruct_background_terminal_fingerprint(&inner, &record)?
            {
                inner
                    .background_terminal_fingerprints
                    .insert(attempt_id.clone(), fingerprint);
            }
            let Some(record) = inner.background_subagents.get_mut(&attempt_id) else {
                continue;
            };
            if let Some(result_ref) = record.result_ref.as_mut() {
                if let Some(artifact_ref) = result_ref.artifact_ref.take() {
                    artifact_refs.push(artifact_ref);
                }
                result_ref.content = None;
                result_ref.error = None;
            }
            record.retention_status = crate::DurableBackgroundSubagentRetentionStatus::Expired;
            record.retention_expires_at = None;
            expired.push(record.clone());
        }
        for artifact_ref in artifact_refs {
            inner.background_artifacts.remove(&artifact_ref);
        }
        Ok(expired)
    }

    async fn record_background_subagent_terminal(
        &self,
        record: BackgroundSubagentRecord,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        commit_background_terminal(&mut inner, record, None, None)
    }

    async fn load_background_subagent(
        &self,
        attempt_id: &starweaver_core::SubagentAttemptId,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        self.inner
            .lock()
            .map_err(store_failed)?
            .background_subagents
            .get(attempt_id)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(attempt_id.as_str().to_string()))
    }

    async fn list_background_subagents(
        &self,
        namespace_id: &str,
        session_id: Option<&SessionId>,
        limit: usize,
    ) -> SessionStoreResult<Vec<BackgroundSubagentRecord>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        let mut records = inner
            .background_subagents
            .values()
            .filter(|record| {
                record.namespace_id == namespace_id
                    && session_id.is_none_or(|session_id| &record.parent_session_id == session_id)
            })
            .cloned()
            .collect::<Vec<_>>();
        records.sort_by(|left, right| {
            right
                .updated_at
                .cmp(&left.updated_at)
                .then_with(|| left.attempt_id.cmp(&right.attempt_id))
        });
        records.truncate(limit);
        Ok(records)
    }

    async fn list_pending_background_subagents(
        &self,
        namespace_id: &str,
        session_id: Option<&SessionId>,
        limit: usize,
    ) -> SessionStoreResult<Vec<BackgroundSubagentRecord>> {
        let inner = self.inner.lock().map_err(store_failed)?;
        let mut records = inner
            .background_subagents
            .values()
            .filter(|record| {
                record.namespace_id == namespace_id
                    && session_id.is_none_or(|session_id| &record.parent_session_id == session_id)
                    && record.execution_status.is_terminal()
                    && record.delivery_status != DurableBackgroundSubagentDeliveryStatus::Delivered
            })
            .cloned()
            .collect::<Vec<_>>();
        records.sort_by(|left, right| {
            left.updated_at
                .cmp(&right.updated_at)
                .then_with(|| left.attempt_id.cmp(&right.attempt_id))
        });
        records.truncate(limit);
        Ok(records)
    }

    async fn claim_background_subagent_delivery(
        &self,
        attempt_id: &starweaver_core::SubagentAttemptId,
        claim: DurableBackgroundSubagentDeliveryClaim,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let now = chrono::Utc::now();
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut record = inner
            .background_subagents
            .get(attempt_id)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(attempt_id.as_str().to_string()))?;
        if record.delivery_status == DurableBackgroundSubagentDeliveryStatus::Claimed
            && record.delivery_claim.as_ref() == Some(&claim)
        {
            return Ok(record);
        }
        if let Some(current_claim) = record.delivery_claim.clone()
            && record.delivery_status == DurableBackgroundSubagentDeliveryStatus::Claimed
            && current_claim.deadline <= now
        {
            match background_claim_consumer_state(&inner, &record, &current_claim, now) {
                BackgroundClaimConsumerState::Live => {
                    return Err(SessionStoreError::Conflict(
                        "live admitted consumer still owns the background delivery claim"
                            .to_string(),
                    ));
                }
                BackgroundClaimConsumerState::Completed(run_id) => {
                    record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Delivered;
                    record.delivery_claim = None;
                    record.delivered_claim_id = Some(current_claim.claim_id);
                    record.continuation_run_id = Some(run_id);
                    record.automatic_continuation_suppressed_by_run_id = None;
                    record.updated_at = now;
                    inner
                        .background_subagents
                        .insert(attempt_id.clone(), record);
                    return Err(SessionStoreError::Conflict(
                        "completed consumer already delivered the background result".to_string(),
                    ));
                }
                BackgroundClaimConsumerState::Terminated(run_id) => {
                    record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Undelivered;
                    record.delivery_claim = None;
                    record.automatic_continuation_suppressed_by_run_id = Some(run_id);
                    record.updated_at = now;
                    inner
                        .background_subagents
                        .insert(attempt_id.clone(), record);
                    return Err(SessionStoreError::Conflict(
                        "terminated consumer released the background delivery claim".to_string(),
                    ));
                }
                BackgroundClaimConsumerState::Reclaimable => {}
            }
        }
        if !record.delivery_claimable_at(now) {
            return Err(SessionStoreError::Conflict(
                "background result delivery is not claimable".to_string(),
            ));
        }
        record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Claimed;
        record.delivery_claim = Some(claim);
        record.updated_at = now;
        inner
            .background_subagents
            .insert(attempt_id.clone(), record.clone());
        Ok(record)
    }

    async fn acknowledge_background_subagent_delivery(
        &self,
        attempt_id: &starweaver_core::SubagentAttemptId,
        claim_id: &str,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let record = inner
            .background_subagents
            .get_mut(attempt_id)
            .ok_or_else(|| SessionStoreError::NotFound(attempt_id.as_str().to_string()))?;
        if record.delivery_status == DurableBackgroundSubagentDeliveryStatus::Delivered {
            return if record.delivered_claim_id.as_deref() == Some(claim_id) {
                Ok(record.clone())
            } else {
                Err(SessionStoreError::Conflict(
                    "background result was delivered by another claim".to_string(),
                ))
            };
        }
        if record.delivery_status != DurableBackgroundSubagentDeliveryStatus::Claimed
            || record
                .delivery_claim
                .as_ref()
                .is_none_or(|claim| claim.claim_id != claim_id)
        {
            return Err(SessionStoreError::Conflict(
                "background delivery claim mismatch".to_string(),
            ));
        }
        record.continuation_run_id = record
            .delivery_claim
            .as_ref()
            .and_then(|claim| claim.continuation_run_id.clone());
        record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Delivered;
        record.delivery_claim = None;
        record.delivered_claim_id = Some(claim_id.to_string());
        record.automatic_continuation_suppressed_by_run_id = None;
        record.updated_at = chrono::Utc::now();
        Ok(record.clone())
    }

    async fn release_background_subagent_delivery(
        &self,
        attempt_id: &starweaver_core::SubagentAttemptId,
        claim_id: &str,
        release: DurableBackgroundSubagentDeliveryRelease,
    ) -> SessionStoreResult<BackgroundSubagentRecord> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut record = inner
            .background_subagents
            .get(attempt_id)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(attempt_id.as_str().to_string()))?;
        if record.delivery_status == DurableBackgroundSubagentDeliveryStatus::Undelivered {
            return match release {
                DurableBackgroundSubagentDeliveryRelease::Retryable => Ok(record),
                DurableBackgroundSubagentDeliveryRelease::ConsumerTerminated { .. } => {
                    Err(SessionStoreError::Conflict(
                        "terminated consumer has no matching background delivery claim".to_string(),
                    ))
                }
            };
        }
        if record.delivery_status != DurableBackgroundSubagentDeliveryStatus::Claimed
            || record
                .delivery_claim
                .as_ref()
                .is_none_or(|claim| claim.claim_id != claim_id)
        {
            return Err(SessionStoreError::Conflict(
                "background delivery claim mismatch".to_string(),
            ));
        }
        if let DurableBackgroundSubagentDeliveryRelease::ConsumerTerminated { run_id } = release {
            if record
                .delivery_claim
                .as_ref()
                .and_then(|claim| claim.continuation_run_id.as_ref())
                != Some(&run_id)
                || inner
                    .runs
                    .get(&run_key(&record.parent_session_id, &run_id))
                    .is_none_or(|run| {
                        !matches!(run.status, RunStatus::Failed | RunStatus::Cancelled)
                    })
            {
                return Err(SessionStoreError::Conflict(
                    "terminated consumer does not own the claim or is not terminal".to_string(),
                ));
            }
            record.automatic_continuation_suppressed_by_run_id = Some(run_id);
        }
        record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Undelivered;
        record.delivery_claim = None;
        record.updated_at = chrono::Utc::now();
        inner
            .background_subagents
            .insert(attempt_id.clone(), record.clone());
        Ok(record)
    }

    async fn acquire_background_subagent_continuation(
        &self,
        request: AcquireBackgroundSubagentContinuation,
    ) -> SessionStoreResult<BackgroundSubagentContinuationReceipt> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let mut background = inner
            .background_subagents
            .get(&request.attempt_id)
            .cloned()
            .ok_or_else(|| SessionStoreError::NotFound(request.attempt_id.as_str().to_string()))?;
        let continuation_run_id = request.admission.run.run_id.clone();
        if request.attempt_id != request.cause.attempt_id
            || background
                .automatic_continuation_suppressed_by_run_id
                .is_some()
            || !background
                .validates_continuation_cause_envelope(&request.cause, &request.admission.run)
        {
            return Err(SessionStoreError::Conflict(
                "background continuation cause does not match its durable result".to_string(),
            ));
        }
        if background.delivery_status == DurableBackgroundSubagentDeliveryStatus::Delivered
            || background.delivery_status == DurableBackgroundSubagentDeliveryStatus::Claimed
        {
            let same_claim = background.continuation_run_id.as_ref() == Some(&continuation_run_id)
                && (background.delivered_claim_id.as_deref() == Some(&request.claim_id)
                    || background
                        .delivery_claim
                        .as_ref()
                        .is_some_and(|claim| claim.claim_id == request.claim_id));
            if !same_claim {
                return Err(SessionStoreError::Conflict(
                    "background result was already claimed or delivered".to_string(),
                ));
            }
            let key = (
                request.admission.namespace_id.clone(),
                request.admission.idempotency_key.clone(),
            );
            let (fingerprint, admission) = inner
                .run_admission_idempotency
                .get(&key)
                .ok_or_else(|| SessionStoreError::NotFound(request.claim_id.clone()))?;
            if fingerprint != &request.admission.command_fingerprint {
                return Err(SessionStoreError::IdempotencyConflict(
                    request.admission.idempotency_key.clone(),
                ));
            }
            let mut admission = admission.clone();
            admission.idempotent_replay = true;
            if !continuation_receipt_matches_request(&background, &request, &admission) {
                return Err(SessionStoreError::Conflict(
                    "stored continuation receipt does not match the causal request".to_string(),
                ));
            }
            let cause =
                crate::BackgroundSubagentContinuationCause::new(&background, &admission.run.input)
                    .map_err(|error| SessionStoreError::Failed(error.to_string()))?;
            return Ok(BackgroundSubagentContinuationReceipt {
                cause,
                background,
                admission,
            });
        }
        let now = chrono::Utc::now();
        let artifact_content = continuation_artifact_content(&inner, &background, now)?;
        if background.parent_session_id != request.admission.run.session_id
            || background.namespace_id != request.admission.namespace_id
            || !background.validates_continuation_cause(
                &request.cause,
                &request.admission.run,
                artifact_content.as_deref(),
            )
            || request.claim_id.is_empty()
            || request.claim_deadline <= now
            || !background.delivery_claimable_at(now)
        {
            return Err(SessionStoreError::Conflict(
                "background result cannot admit this continuation".to_string(),
            ));
        }
        let session = inner
            .sessions
            .get(&background.parent_session_id)
            .ok_or_else(|| {
                SessionStoreError::NotFound(background.parent_session_id.as_str().to_string())
            })?;
        if request.admission.run.restore_from_run_id != session.head_run_id {
            return Err(SessionStoreError::Conflict(
                "background continuation source no longer matches the session head".to_string(),
            ));
        }
        let admission_request = request.clone();
        let mut staged = inner.clone();
        let admission = acquire_run_admission_locked(&mut staged, request.admission.clone())?;
        if !continuation_receipt_matches_request(&background, &admission_request, &admission) {
            return Err(SessionStoreError::Conflict(
                "admitted continuation receipt lost causal input binding".to_string(),
            ));
        }
        background.delivery_status = DurableBackgroundSubagentDeliveryStatus::Delivered;
        background.delivery_claim = None;
        background.delivered_claim_id = Some(request.claim_id);
        background.continuation_run_id = Some(admission.run.run_id.clone());
        background.updated_at = chrono::Utc::now();
        staged
            .background_subagents
            .insert(background.attempt_id.clone(), background.clone());
        let cause =
            crate::BackgroundSubagentContinuationCause::new(&background, &admission.run.input)
                .map_err(|error| SessionStoreError::Failed(error.to_string()))?;
        *inner = staged;
        Ok(BackgroundSubagentContinuationReceipt {
            cause,
            background,
            admission,
        })
    }

    async fn reconcile_background_subagents(
        &self,
        namespace_id: &str,
        now: chrono::DateTime<chrono::Utc>,
    ) -> SessionStoreResult<Vec<BackgroundSubagentRecord>> {
        let mut inner = self.inner.lock().map_err(store_failed)?;
        let attempt_ids = inner
            .background_subagents
            .values()
            .filter(|record| record.namespace_id == namespace_id)
            .map(|record| record.attempt_id.clone())
            .collect::<Vec<_>>();
        let mut changed = Vec::new();
        for attempt_id in attempt_ids {
            let Some(mut record) = inner.background_subagents.get(&attempt_id).cloned() else {
                continue;
            };
            let mut terminal_fingerprint = None;
            if !record.execution_status.is_terminal() && record.owner_lease.expired_at(now) {
                let error = "in-process background execution was interrupted by host restart";
                record.execution_status = DurableBackgroundSubagentExecutionStatus::Failed;
                record.failure_category = Some("host_process_lost".to_string());
                record.result_ref = Some(DurableBackgroundSubagentResultRef {
                    error: Some(error.to_string()),
                    size_bytes: u64::try_from(error.len()).unwrap_or(u64::MAX),
                    ..DurableBackgroundSubagentResultRef::default()
                });
                record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Undelivered;
                record.delivery_claim = None;
                record.retention_expires_at = Some(
                    now + chrono::Duration::seconds(
                        crate::DEFAULT_BACKGROUND_RESULT_RETENTION_SECS,
                    ),
                );
                record.terminal_at = Some(now);
                record.updated_at = now;
                terminal_fingerprint = Some(background_terminal_fingerprint(&record, None)?);
            } else if record.delivery_status == DurableBackgroundSubagentDeliveryStatus::Claimed
                && record
                    .delivery_claim
                    .as_ref()
                    .is_some_and(|claim| claim.deadline <= now)
            {
                let claim = record.delivery_claim.clone().ok_or_else(|| {
                    SessionStoreError::Conflict(
                        "claimed background result is missing its claim".to_string(),
                    )
                })?;
                let consumer = claim.continuation_run_id.as_ref().and_then(|run_id| {
                    inner
                        .runs
                        .get(&run_key(&record.parent_session_id, run_id))
                        .map(|run| (run_id, run.status))
                });
                let consumer_has_live_admission = consumer.is_some_and(|(run_id, status)| {
                    status.is_active()
                        && inner
                            .run_admissions
                            .get(&ManagedSessionTarget::new(
                                record.namespace_id.clone(),
                                record.parent_session_id.clone(),
                            ))
                            .is_some_and(|lease| {
                                lease.target.run_id == *run_id && !lease.expired_at(now)
                            })
                });
                if consumer_has_live_admission {
                    continue;
                }
                if consumer.is_some_and(|(_, status)| status == RunStatus::Completed) {
                    record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Delivered;
                    record
                        .continuation_run_id
                        .clone_from(&claim.continuation_run_id);
                    record.delivered_claim_id = Some(claim.claim_id);
                    record.automatic_continuation_suppressed_by_run_id = None;
                } else {
                    record.delivery_status = DurableBackgroundSubagentDeliveryStatus::Undelivered;
                    if let Some((run_id, status)) = consumer
                        && matches!(status, RunStatus::Failed | RunStatus::Cancelled)
                    {
                        record.automatic_continuation_suppressed_by_run_id = Some(run_id.clone());
                    }
                }
                record.delivery_claim = None;
                record.updated_at = now;
            } else {
                continue;
            }
            if let Some(fingerprint) = terminal_fingerprint {
                inner
                    .background_terminal_fingerprints
                    .insert(attempt_id.clone(), fingerprint);
            }
            inner
                .background_subagents
                .insert(attempt_id, record.clone());
            changed.push(record);
        }
        Ok(changed)
    }

    async fn save_session(&self, session: SessionRecord) -> SessionStoreResult<()> {
        self.save_session_record(session)
    }

    async fn load_session(&self, session_id: &SessionId) -> SessionStoreResult<SessionRecord> {
        self.load_session_record(session_id)
    }

    async fn list_sessions(&self, filter: SessionFilter) -> SessionStoreResult<Vec<SessionRecord>> {
        self.list_session_records(filter)
    }

    async fn list_session_page(&self, query: SessionPageQuery) -> SessionStoreResult<SessionPage> {
        self.list_session_record_page(&query)
    }

    async fn update_session_status(
        &self,
        session_id: &SessionId,
        status: SessionStatus,
    ) -> SessionStoreResult<()> {
        self.set_session_status(session_id, status)
    }

    async fn save_context_state(
        &self,
        session_id: &SessionId,
        state: ResumableState,
    ) -> SessionStoreResult<()> {
        self.save_context_state_snapshot(session_id, state)
    }

    async fn save_environment_state(
        &self,
        session_id: &SessionId,
        environment_state: EnvironmentStateRef,
    ) -> SessionStoreResult<()> {
        self.save_environment_state_ref(session_id, environment_state)
    }

    async fn append_run(&self, run: RunRecord) -> SessionStoreResult<()> {
        self.append_run_record(run)
    }

    async fn load_run(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<RunRecord> {
        self.load_run_record(session_id, run_id)
    }

    async fn list_runs(&self, session_id: &SessionId) -> SessionStoreResult<Vec<RunRecord>> {
        self.list_run_records(session_id)
    }

    async fn update_run_status(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
        status: RunStatus,
        output_preview: Option<String>,
    ) -> SessionStoreResult<()> {
        self.set_legacy_run_status(session_id, run_id, status, output_preview)
    }

    async fn append_checkpoint(
        &self,
        session_id: &SessionId,
        checkpoint: AgentCheckpoint,
    ) -> SessionStoreResult<()> {
        self.append_checkpoint_record(session_id, checkpoint)
    }

    async fn load_checkpoints(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<Vec<AgentCheckpoint>> {
        self.load_checkpoint_records(session_id, run_id)
    }

    async fn append_stream_records(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
        records: Vec<AgentStreamRecord>,
    ) -> SessionStoreResult<()> {
        self.append_stream_record_batch(session_id, run_id, records)
    }

    async fn replay_stream_records(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<Vec<AgentStreamRecord>> {
        self.replay_stream_record_batch(session_id, run_id)
    }

    async fn save_stream_cursor(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
        cursor: StreamCursorRef,
    ) -> SessionStoreResult<()> {
        self.save_stream_cursor_ref(session_id, run_id, cursor)
    }

    async fn append_approval(&self, approval: ApprovalRecord) -> SessionStoreResult<()> {
        self.append_approval_record(approval)
    }

    async fn load_approvals(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<Vec<ApprovalRecord>> {
        self.load_approval_records(session_id, run_id)
    }

    async fn append_deferred_tool(&self, record: DeferredToolRecord) -> SessionStoreResult<()> {
        self.append_deferred_tool_record(record)
    }

    async fn load_deferred_tools(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<Vec<DeferredToolRecord>> {
        self.load_deferred_tool_records(session_id, run_id)
    }

    async fn resume_snapshot(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<SessionResumeSnapshot> {
        let session = self.load_session(session_id).await?;
        let run = self.load_run(session_id, run_id).await?;
        let state = {
            let inner = self.inner.lock().map_err(store_failed)?;
            inner
                .evidence_commits
                .get(&run_key(session_id, run_id))
                .map_or_else(
                    || session.state.clone(),
                    |commit| commit.context_state.clone(),
                )
        };
        let latest_checkpoint = self.latest_checkpoint(session_id, run_id).await?;
        let after_sequence = latest_checkpoint
            .as_ref()
            .and_then(|checkpoint| checkpoint.resume.cursor.stream_cursor);
        let stream_records = self
            .replay_stream_records_after(session_id, run_id, after_sequence)
            .await?;
        let approvals = self.load_approvals(session_id, run_id).await?;
        let deferred_tools = self.load_deferred_tools(session_id, run_id).await?;
        let environment_state = run
            .environment_state
            .clone()
            .or_else(|| session.environment_state.clone());
        let mut stream_cursors = session.stream_cursors.clone();
        stream_cursors.extend(run.stream_cursors.clone());
        Ok(SessionResumeSnapshot {
            session,
            run,
            state,
            environment_state,
            latest_checkpoint,
            stream_records,
            approvals,
            deferred_tools,
            stream_cursors,
        })
    }

    async fn compact_run_trace(
        &self,
        session_id: &SessionId,
        run_id: &RunId,
    ) -> SessionStoreResult<CompactRunTrace> {
        self.compact_run_trace_projection(session_id, run_id)
    }

    async fn compact_session_trace(
        &self,
        session_id: &SessionId,
    ) -> SessionStoreResult<CompactSessionTrace> {
        self.compact_session_trace_projection(session_id)
    }
}