starweaver-session 0.9.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
//! In-memory session store implementation.

mod approvals;
mod checkpoints;
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;

use crate::{
    AcquireBackgroundSubagentContinuation, AcquireRunAdmission, BackgroundSubagentArtifact,
    BackgroundSubagentArtifactLimits, BackgroundSubagentContinuationReceipt,
    BackgroundSubagentRecord, BackgroundSubagentTerminalCommit,
    DurableBackgroundSubagentDeliveryClaim, DurableBackgroundSubagentDeliveryRelease,
    DurableBackgroundSubagentDeliveryStatus, DurableBackgroundSubagentExecutionStatus,
    DurableBackgroundSubagentResultRef, DurableControlReceipt, ManagedRunTarget,
    ManagedSessionTarget, RunAdmissionLease, RunAdmissionReceipt, SessionContinuationFence,
    SessionDeletionFence, UpdateManagedSession,
    approval::{ApprovalRecord, ApprovalStatus, DeferredToolRecord},
    claim::{HitlResumeClaim, HitlResumeClaimState},
    error::{SessionStoreError, SessionStoreResult},
    evidence::RunEvidenceCommit,
    publication::{PendingStreamPublication, StreamPublicationTarget},
    records::{
        EnvironmentStateRef, ExecutionStatus, RunRecord, RunStatus, SessionRecord, SessionStatus,
        StreamCursorRef,
    },
    resume::SessionResumeSnapshot,
    trace::{CompactRunTrace, CompactSessionTrace},
};

use super::{SessionFilter, 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>>,
    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>,
    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>,
    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 validate_approval_transition(
    existing: &ApprovalRecord,
    resolved: &ApprovalRecord,
) -> SessionStoreResult<()> {
    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.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 validate_deferred_transition(
    existing: &DeferredToolRecord,
    resolved: &DeferredToolRecord,
) -> SessionStoreResult<()> {
    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 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(),
        )?;
        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(&commit.run.session_id, checkpoint)?;
    }
    staged.append_stream_record_batch(
        &commit.run.session_id,
        &commit.run.run_id,
        commit.stream_records.clone(),
    )?;
    for cursor in commit.stream_cursors.clone() {
        staged.save_stream_cursor_ref(&commit.run.session_id, &commit.run.run_id, cursor)?;
    }
    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,
    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))
    })?;
    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);
    }
    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,
        ));
    }
    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()
            )));
        }
        if let Some(run) = inner
            .runs
            .get_mut(&run_key(&active.target.session_id, &active.target.run_id))
        {
            run.status = RunStatus::Cancelled;
            run.updated_at = now;
        }
        inner.run_admissions.remove(&session_target);
    }
    {
        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(),
            ));
        }
    }
    let mut run = request.run;
    run.status = RunStatus::Queued;
    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 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()))?;
    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()?;
        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);
        }
        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_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()))?;
        }
        if staged
            .load_run_record(session_id, &checkpoint.run_id)
            .is_err()
        {
            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.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(session_id, checkpoint)?;
        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 {
                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 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 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 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 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(),
            ));
        }
        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 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 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)?;
        acquire_run_admission_locked(&mut inner, request)
    }

    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.host_instance_id != lease.host_instance_id
            || current.fencing_generation != lease.fencing_generation
            || current.target != lease.target
        {
            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.host_instance_id != lease.host_instance_id
                || current.fencing_generation != lease.fencing_generation
                || current.target != lease.target
            {
                return Err(SessionStoreError::Conflict(
                    "stale admission owner".to_string(),
                ));
            }
            inner.run_admissions.remove(&key);
        }
        Ok(())
    }

    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 expired = inner
            .run_admissions
            .iter()
            .filter(|(session, lease)| {
                session.namespace_id == namespace_id && lease.expired_at(now)
            })
            .map(|(session, lease)| (session.clone(), lease.target.clone()))
            .collect::<Vec<_>>();
        for (session_target, target) in &expired {
            if let Some(run) = inner
                .runs
                .get_mut(&run_key(&target.session_id, &target.run_id))
                && run.status.is_active()
            {
                run.status = RunStatus::Cancelled;
                run.output_preview = Some("interrupted after host lease expired".to_string());
                run.updated_at = now;
            }
            if let Some(session) = inner.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;
            }
            inner.run_admissions.remove(session_target);
        }
        Ok(expired.into_iter().map(|(_, target)| target).collect())
    }

    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()))?;
        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 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,
        mut 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())
            })?;
        request
            .admission
            .run
            .restore_from_run_id
            .clone_from(&session.head_run_id);
        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 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_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)
    }
}