bamboo-storage 2026.8.1

Session storage backends for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
//! Merge-aware session save helper.
//!
//! Provides [`merge_save_session`], which preserves any concurrent UI edits to
//! the authoritative metadata group (`title`, `title_version`, `pinned`,
//! `metadata_version`) before writing the runtime-modified session to storage.
//! Re-reads the latest persisted copy and only takes in-memory values when the
//! caller's `metadata_version` strictly exceeds disk's.
//!
//! ## Field-by-field merge policy
//!
//! All authoritative metadata fields are grouped under `metadata_version`:
//! when `disk.metadata_version >= session.metadata_version`, the on-disk
//! `title`, `title_version`, `pinned`, and `metadata_version` overwrite the
//! in-memory values before writing. Authoritative writers bump
//! `metadata_version` (and `title_version` for title edits) before calling so
//! their values survive the merge; non-authoritative writers don't bump and so
//! are overwritten by any later disk changes.
//!
//! ## Two save primitives
//!
//! - **`merge_save_session`** — stateless merge+save. Still works for
//!   non-authoritative writers that hold `Arc<dyn Storage>` directly.
//! - **`LockedSessionStore::merge_save_runtime`** — per-session-locked variant
//!   that additionally serializes writes for the same session. Prefer this for
//!   server-side paths where an authoritative writer may race with a runtime
//!   save.
//! - **`LockedSessionStore::commit_metadata`** — plain save inside a per-session
//!   lock. For authoritative writers that have already performed
//!   load→mutate→bump inside the lock; no merge needed (they hold the latest).
//!
//! Bare [`Storage::save_session`] is reserved for first-write paths (e.g. new
//! session creation) where there is no prior on-disk copy to merge against.

use std::sync::Arc;

use bamboo_domain::session::types::Session;
use bamboo_domain::storage::Storage;
use bamboo_domain::{PermissionAuditSeed, PermissionAuditSnapshot, RuntimeSessionPersistence};
use dashmap::DashMap;
use tokio::sync::{Mutex, OwnedMutexGuard};

const AUTHORITATIVE_METADATA_KEYS: &[&str] = &["gold_config", "workflow.run_ids.v1"];

// ── LockedSessionStore ────────────────────────────────────────────────

/// Wraps a [`Storage`] implementation with per-session write serialization.
///
/// Under the hood it maintains a `DashMap<String, Arc<Mutex<()>>>` so that
/// only writes targeting the *same* session are serialised; different
/// sessions proceed concurrently.
pub struct LockedSessionStore {
    storage: Arc<dyn Storage>,
    locks: Arc<DashMap<String, Arc<Mutex<()>>>>,
}

/// Self-cleaning guard returned by [`LockedSessionStore::acquire_lock`].
///
/// Holds the `OwnedMutexGuard` for the session's serialization mutex. On drop it
/// releases the mutex **first** (so this guard's `Arc` clone is gone before the
/// count is read) and then removes the map entry iff `Arc::strong_count == 1` —
/// i.e. only the map's own reference remains, no other task holds or is waiting
/// on this session's lock.
///
/// ## Race freedom
///
/// The strong-count check and the removal execute atomically under DashMap's
/// per-shard lock via [`DashMap::remove_if`]. A waiter that clones the `Arc`
/// (through `acquire_lock`'s `entry()`) does so under the same shard lock, so it
/// either:
/// - clones **before** our `remove_if` → `strong_count >= 2` → we skip removal,
///   the waiter keeps a live, map-resident lock; or
/// - clones **after** our `remove_if` → the entry is gone → it inserts a fresh
///   `Arc<Mutex<()>>`; since our guard had already been released, the two tasks
///   never overlapped and needed no mutual exclusion.
///
/// There is therefore no interleaving in which a waiter observes a lock that we
/// then delete out from under it.
pub struct SessionLockGuard {
    /// `Option` so `Drop` can release the mutex before evaluating strong-count.
    guard: Option<OwnedMutexGuard<()>>,
    locks: Arc<DashMap<String, Arc<Mutex<()>>>>,
    session_id: String,
}

impl Drop for SessionLockGuard {
    fn drop(&mut self) {
        // Release the mutex (drops this guard's `Arc` clone) BEFORE reading the
        // strong count, otherwise the count can never reach 1.
        self.guard.take();
        self.locks
            .remove_if(&self.session_id, |_, arc| Arc::strong_count(arc) == 1);
    }
}

impl LockedSessionStore {
    /// Wrap an existing storage backend.
    pub fn new(storage: Arc<dyn Storage>) -> Self {
        Self {
            storage,
            locks: Arc::new(DashMap::new()),
        }
    }

    /// Borrow the inner storage for read-only access.
    pub fn storage(&self) -> &Arc<dyn Storage> {
        &self.storage
    }

    /// Acquire a per-session serialization guard.
    ///
    /// Only writes for the **same** session are serialised; writes for
    /// different sessions can proceed concurrently.
    ///
    /// The returned [`SessionLockGuard`] is **self-cleaning**: when it drops it
    /// releases the mutex and then removes the map entry iff no other holder
    /// remains. Without this the `locks` map grew by one entry for every session
    /// id ever written and never shrank (issue #346), so a long-lived server
    /// leaked one `Arc<Mutex<()>>` per session-ever-persisted. See
    /// [`SessionLockGuard`] for the race-freedom argument.
    pub async fn acquire_lock(&self, session_id: &str) -> SessionLockGuard {
        // `entry().or_insert_with().clone()` releases the DashMap shard lock at
        // the end of THIS statement, before the `.await` below — never hold a
        // shard lock across the async lock acquisition (it would deadlock the
        // self-cleaning `remove_if` on drop, which also takes the shard lock).
        let lock = self
            .locks
            .entry(session_id.to_string())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .clone();
        let guard = lock.lock_owned().await;
        SessionLockGuard {
            guard: Some(guard),
            locks: self.locks.clone(),
            session_id: session_id.to_string(),
        }
    }

    /// Runtime-only save: persist the control-plane (`agent_runtime_state`,
    /// metadata, …) without rewriting the message history.
    ///
    /// This is the fast path for runtime-state mutations that do NOT change
    /// `messages` — e.g. registering a parent's wait for spawned children. It
    /// delegates to [`Storage::save_runtime_state`], which writes a small
    /// sidecar (or falls back to a full save on backends without one).
    ///
    /// Like [`Self::merge_save_runtime`], it merges newer authoritative metadata
    /// from disk so a concurrent UI title/pin edit is never clobbered — but it
    /// reads only the lightweight control-plane snapshot (no message history) to
    /// do so.
    ///
    /// Callers MUST NOT use this when they have appended messages: the in-memory
    /// `messages` are ignored by the sidecar and would not be persisted.
    pub async fn save_runtime_only(&self, session: &mut Session) -> std::io::Result<()> {
        self.save_runtime_only_and_publish(session, |_| {}).await
    }

    /// Save the runtime control-plane and synchronously publish the committed
    /// snapshot before releasing this session's serialization lock.
    ///
    /// `publish` must remain a short, non-blocking operation. Its synchronous
    /// shape intentionally prevents callers from holding an in-memory cache
    /// guard across an await. The callback also runs when the durable save
    /// fails, preserving [`RuntimeSessionPersistence::save_runtime_control_plane`]
    /// implementations that publish current runtime authorization state while
    /// still returning the storage error.
    pub async fn save_runtime_only_and_publish<F>(
        &self,
        session: &mut Session,
        publish: F,
    ) -> std::io::Result<()>
    where
        F: FnOnce(&Session) + Send,
    {
        let _guard = self.acquire_lock(&session.id).await;
        if let Ok(Some(latest)) = self.storage.load_runtime_control_plane(&session.id).await {
            apply_authoritative_metadata(session, &latest);
            // The control-plane sidecar carries `agent_runtime_state`, so a
            // concurrent mid-run bypass flip is here too — don't revert it. #540.
            adopt_fresher_disk_permission_posture(session, &latest);
        }
        let result = self.storage.save_runtime_state(session).await;
        publish(session);
        result
    }

    /// Atomically patch Task-owned control-plane fields and publish the saved
    /// value before releasing this session's serialization lock.
    ///
    /// This couples durable commit order to cache publication order for
    /// repository callers. The synchronous callback may take a cache guard but
    /// cannot hold one across an await.
    pub async fn update_task_list_control_plane_and_publish<F>(
        &self,
        session_id: &str,
        task_list: &bamboo_domain::TaskList,
        version: &str,
        publish: F,
    ) -> std::io::Result<bool>
    where
        F: FnOnce(&Session) + Send,
    {
        let _guard = self.acquire_lock(session_id).await;
        let Some(mut latest) = self.storage.load_runtime_control_plane(session_id).await? else {
            return Ok(false);
        };
        latest.set_task_list(task_list.clone());
        latest.set_task_list_version_meta(version.to_string());
        self.storage.save_runtime_state(&latest).await?;
        publish(&latest);
        Ok(true)
    }

    /// Authoritative metadata commit.
    ///
    /// The caller must have already loaded the latest session, mutated the
    /// metadata fields, and bumped `metadata_version` (and `title_version` if
    /// applicable).  This method simply acquires the per-session lock and
    /// performs a plain `storage.save_session`.
    ///
    /// The lock guarantees that no other write for this session interleaves
    /// between the caller's load and this save, so merge is unnecessary.
    pub async fn commit_metadata(&self, session: &Session) -> std::io::Result<()> {
        let _guard = self.acquire_lock(&session.id).await;
        self.storage.save_session(session).await
    }

    /// Runtime / non-authoritative save with per-session lock.
    ///
    /// Inside the lock: reload disk, merge the authoritative metadata group
    /// (`title`, `title_version`, `pinned`, `metadata_version`) from disk into
    /// the in-memory copy if disk's `metadata_version >= session.metadata_version`,
    /// then save.
    ///
    /// This is the locked equivalent of [`merge_save_session`]; prefer it for
    /// server-side paths where an authoritative write may race with this save.
    ///
    /// Adopts the on-disk typed permission mode so a running loop's save can't
    /// revert a concurrent `PATCH /sessions` transition (#540/#770). Callers
    /// that are themselves the authoritative writer of that posture — the
    /// parent seeding a child's mode (#74) — must use
    /// [`Self::save_runtime_authoritative_flags`] instead, which persists the
    /// in-memory mode as-is.
    pub async fn merge_save_runtime(&self, session: &mut Session) -> std::io::Result<()> {
        self.merge_save_runtime_and_publish(session, |_, _| {})
            .await
    }

    /// Merge-save a runtime session and synchronously publish the resulting
    /// snapshot before releasing its per-session serialization lock.
    ///
    /// The callback receives whether the durable save committed. It always runs
    /// after the save attempt so repository callers can preserve their existing
    /// cache-on-failure policy without reopening a durable-to-cache race.
    pub async fn merge_save_runtime_and_publish<F>(
        &self,
        session: &mut Session,
        publish: F,
    ) -> std::io::Result<()>
    where
        F: FnOnce(&Session, bool) + Send,
    {
        self.merge_save_runtime_inner_and_publish(session, true, publish)
            .await
    }

    /// Persist an execute-boundary transcript checkpoint without allowing a
    /// stale runner snapshot to shrink or rewrite the durable message log.
    ///
    /// The latest load, append-only message reconciliation, metadata merge and
    /// save all happen while holding the same per-session lock.  Loading is
    /// deliberately fail-closed: falling back to a blind full save when the
    /// latest transcript cannot be read would reintroduce the SHRINK hazard
    /// this checkpoint exists to prevent.
    pub async fn checkpoint_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
        self.checkpoint_runtime_session_and_publish(session, |_, _| {})
            .await
    }

    /// Checkpoint a runtime session and publish its reconciled snapshot before
    /// releasing the same per-session serialization lock.
    ///
    /// The callback runs after the durable save attempt and receives its commit
    /// status. A load failure returns before publication, matching the
    /// checkpoint's fail-closed behavior.
    pub async fn checkpoint_runtime_session_and_publish<F>(
        &self,
        session: &mut Session,
        publish: F,
    ) -> std::io::Result<()>
    where
        F: FnOnce(&Session, bool) + Send,
    {
        let _guard = self.acquire_lock(&session.id).await;
        let latest = self.storage.load_session(&session.id).await?;

        if let Some(latest) = latest.as_ref() {
            let incoming_count = session.messages.len();
            let durable_count = latest.messages.len();
            let appended = bamboo_domain::append_missing_runtime_messages(session, latest);
            bamboo_domain::merge_session_inbox_admission(session, latest);
            tracing::debug!(
                "[{}] append-safe runtime checkpoint: durable={}, incoming={}, appended={}, saved={}",
                session.id,
                durable_count,
                incoming_count,
                appended,
                session.messages.len(),
            );
            apply_authoritative_metadata(session, latest);
            adopt_fresher_disk_permission_posture(session, latest);
        }

        let result = self.storage.save_session(session).await;
        publish(session, result.is_ok());
        result
    }

    /// Like [`Self::merge_save_runtime`] but does NOT adopt the on-disk
    /// permission mode — the caller's in-memory value is authoritative and
    /// persists as-is.
    ///
    /// For parent-side control writes to a child session (e.g. the #74
    /// resident-reuse posture re-seed), which set the flag deliberately and must
    /// not be reverted by the disk-wins protection meant for a running loop's
    /// own stale saves. Still merges the authoritative metadata group.
    pub async fn save_runtime_authoritative_flags(
        &self,
        session: &mut Session,
    ) -> std::io::Result<()> {
        self.merge_save_runtime_inner_and_publish(session, false, |_, _| {})
            .await
    }

    async fn merge_save_runtime_inner_and_publish<F>(
        &self,
        session: &mut Session,
        adopt_bypass: bool,
        publish: F,
    ) -> std::io::Result<()>
    where
        F: FnOnce(&Session, bool) + Send,
    {
        let _guard = self.acquire_lock(&session.id).await;

        // Single disk read serves BOTH the SHRINK diagnostic and the
        // authoritative-metadata merge below. Previously this path loaded the
        // session twice (once here, once inside the merge helper); on a parent
        // session carrying the full conversation history that doubled the
        // deserialization cost of every runtime save, which is the hot path
        // during sub-agent spawn.
        let latest = self.storage.load_session(&session.id).await.ok().flatten();

        // DIAGNOSTIC: merge_save_runtime overwrites the whole `messages` array
        // (it only merges authoritative metadata, not messages). If the incoming
        // session is stale (fewer messages than what is already on disk), this save
        // silently reverts a concurrent append (e.g. a just-persisted user message).
        // Log a SHRINK warning so we can identify the stale writer.
        let existing_message_count = latest.as_ref().map(|s| s.messages.len());
        let incoming_message_count = session.messages.len();
        if existing_message_count.is_some_and(|existing| existing > incoming_message_count) {
            tracing::warn!(
                "[{}] merge_save_runtime SHRINK: disk has {:?} messages, saving {} (last_role={:?}, updated_at={}); a stale writer is reverting a concurrent append",
                session.id,
                existing_message_count,
                incoming_message_count,
                session.messages.last().map(|m| format!("{:?}", m.role)),
                session.updated_at,
            );
        } else {
            tracing::debug!(
                "[{}] merge_save_runtime: disk={:?} messages, saving {} (updated_at={})",
                session.id,
                existing_message_count,
                incoming_message_count,
                session.updated_at,
            );
        }

        if let Some(latest) = latest.as_ref() {
            apply_authoritative_metadata(session, latest);
            let restored = bamboo_domain::restore_missing_admitted_inbox_messages(session, latest);
            if restored > 0 {
                tracing::warn!(
                    session_id = %session.id,
                    restored,
                    "restored durable SessionInbox transcript messages into stale runtime save"
                );
            }
            bamboo_domain::merge_session_inbox_admission(session, latest);
            // Never let a running loop's save revert a concurrent mid-run
            // `PATCH /sessions {permission_mode|bypass_permissions}` transition.
            // #540/#770. Skipped for
            // authoritative flag writers (`save_runtime_authoritative_flags`).
            if adopt_bypass {
                adopt_fresher_disk_permission_posture(session, latest);
            }
        }
        let result = self.storage.save_session(session).await;
        publish(session, result.is_ok());
        result
    }

    /// Persist one validated RunSpec activation as the exact authority for the
    /// worker's requested posture and complete audit record.
    ///
    /// Warm workers reuse a durable session id. An ordinary runtime save is
    /// intentionally disk-adopting, so using it here would let the previous
    /// activation's posture stick. This dedicated transaction preserves only
    /// durable UI metadata and SessionInbox admission/transcript proof, then
    /// writes the incoming posture with an audit revision above the durable
    /// floor while holding the same per-session lock.
    pub async fn seed_runtime_activation_and_publish<F>(
        &self,
        session: &mut Session,
        publish: F,
    ) -> std::io::Result<()>
    where
        F: FnOnce(&Session, bool) + Send,
    {
        let _guard = self.acquire_lock(&session.id).await;
        let mut incoming_audit = PermissionAuditSnapshot::from_metadata(&session.metadata)
            .ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "activation seed requires a complete permission audit record",
                )
            })?;

        if let Some(latest) = self.storage.load_session(&session.id).await? {
            apply_authoritative_metadata(session, &latest);
            bamboo_domain::restore_missing_admitted_inbox_messages(session, &latest);
            bamboo_domain::merge_session_inbox_admission(session, &latest);

            let durable_audit = PermissionAuditSnapshot::from_metadata(&latest.metadata);
            let durable_floor = durable_audit
                .as_ref()
                .map(|snapshot| snapshot.audit_revision)
                .unwrap_or_default();
            if let Some(durable_audit) = durable_audit {
                if durable_audit.resolution == incoming_audit.resolution {
                    incoming_audit.transitioned_at = durable_audit.transitioned_at;
                }
            }
            incoming_audit.audit_revision = bamboo_domain::next_permission_audit_revision_after(
                durable_floor.max(incoming_audit.audit_revision),
            )
            .map_err(|error| {
                std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string())
            })?;
        }

        session
            .agent_runtime_state
            .get_or_insert_with(bamboo_domain::AgentRuntimeState::default)
            .set_permission_mode(incoming_audit.resolution.requested);
        incoming_audit.write_to(&mut session.metadata);

        let result = self.storage.save_session(session).await;
        publish(session, result.is_ok());
        result
    }

    /// Atomically re-seed a resident child from its parent posture.
    ///
    /// The latest session load, typed-mode comparison, complete audit refresh,
    /// metadata CAS bump (only for a true typed transition), narrow companion
    /// mutation, save, and cache publication share one session lock.
    pub async fn update_authoritative_permission_posture_and_publish<M, P>(
        &self,
        session_id: &str,
        seed: &PermissionAuditSeed,
        mutate: M,
        publish: P,
    ) -> std::io::Result<Option<Session>>
    where
        M: FnOnce(&mut Session),
        P: FnOnce(&Session),
    {
        let _guard = self.acquire_lock(session_id).await;
        let Some(mut latest) = self.storage.load_session(session_id).await? else {
            return Ok(None);
        };
        let previous_mode = latest
            .agent_runtime_state
            .as_ref()
            .map(|state| state.effective_permission_mode())
            .unwrap_or_default();
        let previous_resolution = PermissionAuditSnapshot::from_metadata(&latest.metadata)
            .map(|snapshot| snapshot.resolution);
        mutate(&mut latest);
        latest
            .agent_runtime_state
            .get_or_insert_with(bamboo_domain::AgentRuntimeState::default)
            .set_permission_mode(seed.resolution.requested);
        let mode_changed = previous_mode != seed.resolution.requested;
        let posture_changed = previous_resolution != Some(seed.resolution);
        let transitioned_at = posture_changed.then(|| chrono::Utc::now().to_rfc3339());
        bamboo_domain::record_permission_audit(
            &mut latest.metadata,
            seed,
            transitioned_at.as_deref(),
        )
        .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
        if mode_changed {
            latest.metadata_version = latest.metadata_version.saturating_add(1);
        }
        self.storage.save_session(&latest).await?;
        publish(&latest);
        Ok(Some(latest))
    }

    /// Persist a worker's bounded executor mapping only when the exact host
    /// posture observed before dispatch is still current. The remote event does
    /// not contribute an audit revision or transition timestamp: both are
    /// allocated from the latest durable record while this session lock is held.
    pub async fn record_permission_posture_activation_and_publish<P>(
        &self,
        session_id: &str,
        expected_audit_revision: Option<u64>,
        seed: &PermissionAuditSeed,
        publish: P,
    ) -> std::io::Result<Option<Session>>
    where
        P: FnOnce(&Session),
    {
        let _guard = self.acquire_lock(session_id).await;
        let Some(mut latest) = self.storage.load_session(session_id).await? else {
            return Ok(None);
        };
        let durable_audit = PermissionAuditSnapshot::from_metadata(&latest.metadata);
        let durable_revision = durable_audit
            .as_ref()
            .map(|snapshot| snapshot.audit_revision);
        if durable_revision != expected_audit_revision {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "stale permission posture activation: durable audit changed after dispatch",
            ));
        }
        let durable_requested = latest
            .agent_runtime_state
            .as_ref()
            .map(|state| state.effective_permission_mode())
            .unwrap_or_default();
        if durable_requested != seed.resolution.requested || !seed.resolution.is_consistent() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "stale or inconsistent permission posture activation",
            ));
        }
        bamboo_domain::record_permission_audit(&mut latest.metadata, seed, None).map_err(
            |error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()),
        )?;
        self.storage.save_session(&latest).await?;
        publish(&latest);
        Ok(Some(latest))
    }

    /// Apply a config-only mutation to a session without ever clobbering its
    /// `messages` (or other concurrently-written state).
    ///
    /// Unlike [`Self::merge_save_runtime`], the caller does NOT pass a session
    /// snapshot. Instead this loads the **latest** session from storage *inside*
    /// the per-session lock, applies `mutate` (intended for small config fields
    /// like `model_ref` / `reasoning_effort`), and saves. Because the load and
    /// save both happen under the lock, a concurrent append (e.g. `POST /chat`
    /// adding a user message) can never be reverted by this write.
    ///
    /// Returns the saved session, or `None` if it does not exist.
    pub async fn update_runtime_config<F>(
        &self,
        session_id: &str,
        mutate: F,
    ) -> std::io::Result<Option<Session>>
    where
        F: FnOnce(&mut Session),
    {
        self.update_runtime_config_and_publish(session_id, mutate, |_| {})
            .await
    }

    /// Apply a config-only mutation and synchronously publish the saved
    /// snapshot before releasing the session lock.
    pub async fn update_runtime_config_and_publish<M, P>(
        &self,
        session_id: &str,
        mutate: M,
        publish: P,
    ) -> std::io::Result<Option<Session>>
    where
        M: FnOnce(&mut Session),
        P: FnOnce(&Session),
    {
        let _guard = self.acquire_lock(session_id).await;
        let Some(mut session) = self.storage.load_session(session_id).await? else {
            return Ok(None);
        };
        mutate(&mut session);
        self.storage.save_session(&session).await?;
        publish(&session);
        Ok(Some(session))
    }

    /// Clear the legacy compatibility queue using durable CAS and publish the
    /// saved full snapshot before releasing the same session lock.
    pub async fn clear_legacy_pending_messages_and_publish<F>(
        &self,
        session_id: &str,
        expected: &[serde_json::Value],
        publish: F,
    ) -> std::io::Result<bool>
    where
        F: FnOnce(&Session) + Send,
    {
        let _guard = self.acquire_lock(session_id).await;
        let Some(mut latest) = self.storage.load_session(session_id).await? else {
            return Ok(false);
        };
        if latest.pending_injected_messages().as_deref() != Some(expected) {
            return Ok(false);
        }
        latest.clear_pending_injected_messages();
        self.storage.save_runtime_state(&latest).await?;
        publish(&latest);
        Ok(true)
    }
}

/// Infrastructure implementation of the domain runtime-persistence port.
/// Server should assemble this as `Arc<dyn RuntimeSessionPersistence>` and must
/// not define a separate adapter layer for the same behavior.
#[async_trait::async_trait]
impl RuntimeSessionPersistence for LockedSessionStore {
    async fn save_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
        self.merge_save_runtime(session).await
    }

    async fn seed_runtime_activation(&self, session: &mut Session) -> std::io::Result<()> {
        self.seed_runtime_activation_and_publish(session, |_, _| {})
            .await
    }

    async fn record_permission_posture_activation(
        &self,
        session_id: &str,
        expected_audit_revision: Option<u64>,
        seed: &PermissionAuditSeed,
    ) -> std::io::Result<Option<Session>> {
        self.record_permission_posture_activation_and_publish(
            session_id,
            expected_audit_revision,
            seed,
            |_| {},
        )
        .await
    }

    async fn save_runtime_control_plane(&self, session: &mut Session) -> std::io::Result<()> {
        self.save_runtime_only(session).await
    }

    async fn load_runtime_control_plane(
        &self,
        session_id: &str,
    ) -> std::io::Result<Option<Session>> {
        self.storage.load_runtime_control_plane(session_id).await
    }

    async fn update_task_list_control_plane(
        &self,
        session_id: &str,
        task_list: &bamboo_domain::TaskList,
        version: &str,
    ) -> std::io::Result<bool> {
        self.update_task_list_control_plane_and_publish(session_id, task_list, version, |_| {})
            .await
    }

    async fn checkpoint_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
        LockedSessionStore::checkpoint_runtime_session(self, session).await
    }

    async fn load_runtime_session(&self, session_id: &str) -> std::io::Result<Option<Session>> {
        self.storage.load_session(session_id).await
    }

    async fn clear_legacy_pending_messages(
        &self,
        session_id: &str,
        expected: &[serde_json::Value],
    ) -> std::io::Result<bool> {
        self.clear_legacy_pending_messages_and_publish(session_id, expected, |_| {})
            .await
    }
}

// ── Internal merge helper ─────────────────────────────────────────────

/// Re-read the on-disk session and, when the disk copy carries a
/// `metadata_version >= session.metadata_version`, overwrite the in-memory
/// authoritative metadata fields with the disk values.
///
/// This is the core staleness-correction: non-authoritative writers call it
/// before saving so they don't accidentally revert a concurrent UI edit.
async fn merge_authoritative_metadata_into_stale(
    storage: &Arc<dyn Storage>,
    session: &mut Session,
) {
    if let Ok(Some(latest)) = storage.load_session(&session.id).await {
        apply_authoritative_metadata(session, &latest);
        bamboo_domain::restore_missing_admitted_inbox_messages(session, &latest);
        bamboo_domain::merge_session_inbox_admission(session, &latest);
        adopt_fresher_disk_permission_posture(session, &latest);
    }
}

/// Adopt the on-disk typed permission posture into the session about to be
/// saved when the durable posture is semantically fresher.
///
/// `PATCH /sessions {permission_mode|bypass_permissions}` is the authoritative
/// writer of this posture (a running loop only carries it forward from run
/// start). Without this, a runtime save from an in-flight run — which holds the
/// run-start value — silently reverts a concurrent mid-run transition on disk.
/// A true typed-mode difference always represents an authoritative durable
/// transition. When the modes are equal, the complete audit revision is the
/// ordering fence: an older/missing disk audit must never delete a newer
/// run-start policy/mapping refresh. #540/#770.
fn adopt_fresher_disk_permission_posture(session: &mut Session, latest: &Session) {
    // A disk copy with NO runtime state at all carries no authoritative mode
    // value — treat it as "unknown" and leave the in-memory flag untouched,
    // rather than forcing it OFF (which would silently disable a legitimately
    // bypassed run on any backend/path that doesn't round-trip the field). #540.
    let Some(disk_mode) = latest
        .agent_runtime_state
        .as_ref()
        .map(|state| state.effective_permission_mode())
    else {
        return;
    };
    let current_mode = session
        .agent_runtime_state
        .as_ref()
        .map(|state| state.effective_permission_mode())
        .unwrap_or_default();
    let Some(disk_audit) = bamboo_domain::fresher_disk_permission_audit(
        current_mode,
        &session.metadata,
        disk_mode,
        &latest.metadata,
    ) else {
        return;
    };

    match session.agent_runtime_state.as_mut() {
        Some(state) => state.set_permission_mode(disk_mode),
        // No runtime state in memory and disk says "off" → nothing to adopt;
        // avoid allocating a default state just to store `false`.
        None if disk_mode != bamboo_domain::SessionPermissionMode::Default => {
            let state = session
                .agent_runtime_state
                .get_or_insert_with(bamboo_domain::AgentRuntimeState::default);
            state.set_permission_mode(disk_mode);
        }
        None => {}
    }

    // The typed posture and its complete bounded audit record move together.
    disk_audit.write_to(&mut session.metadata);
}

/// Pure merge step: given a freshly-loaded on-disk copy, overwrite the
/// in-memory authoritative metadata group when disk's `metadata_version` is at
/// least the in-memory one. Split out so callers that have already loaded the
/// disk copy (e.g. [`LockedSessionStore::merge_save_runtime`]) don't pay for a
/// second read.
fn apply_authoritative_metadata(session: &mut Session, latest: &Session) {
    if latest.metadata_version >= session.metadata_version {
        session.title = latest.title.clone();
        session.title_version = latest.title_version;
        session.pinned = latest.pinned;
        for key in AUTHORITATIVE_METADATA_KEYS {
            if let Some(value) = latest.metadata.get(*key) {
                session.metadata.insert((*key).to_string(), value.clone());
            } else {
                session.metadata.remove(*key);
            }
        }
        session.metadata_version = latest.metadata_version;
    }
}

// ── Free merge-save function ──────────────────────────────────────────

/// Save a session while preserving any concurrent UI edits to the
/// authoritative metadata group.
///
/// Behaviour: if the on-disk session has `metadata_version >=
/// session.metadata_version`, the on-disk `title`, `title_version`, `pinned`
/// and `metadata_version` overwrite the in-memory values before writing.
///
/// This is the stateless variant (no per-session lock). Prefer
/// [`LockedSessionStore::merge_save_runtime`] for server-side paths where an
/// authoritative writer may race with this save.
pub async fn merge_save_session(
    storage: &Arc<dyn Storage>,
    session: &mut Session,
) -> std::io::Result<()> {
    merge_authoritative_metadata_into_stale(storage, session).await;
    storage.save_session(session).await
}

// ── Tests ─────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::v2::SessionStoreV2;
    use bamboo_domain::{session::types::Session, PermissionMode};
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct CountingControlPlaneStorage {
        inner: Arc<SessionStoreV2>,
        control_plane_loads: AtomicUsize,
    }

    #[async_trait::async_trait]
    impl Storage for CountingControlPlaneStorage {
        async fn save_session(&self, session: &Session) -> std::io::Result<()> {
            self.inner.save_session(session).await
        }

        async fn load_session(&self, session_id: &str) -> std::io::Result<Option<Session>> {
            self.inner.load_session(session_id).await
        }

        async fn delete_session(&self, session_id: &str) -> std::io::Result<bool> {
            self.inner.delete_session(session_id).await
        }

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

        async fn load_runtime_control_plane(
            &self,
            session_id: &str,
        ) -> std::io::Result<Option<Session>> {
            self.control_plane_loads.fetch_add(1, Ordering::SeqCst);
            self.inner.load_runtime_control_plane(session_id).await
        }
    }

    async fn make_storage() -> (tempfile::TempDir, Arc<dyn Storage>) {
        let temp = tempfile::tempdir().unwrap();
        let storage = SessionStoreV2::new(temp.path().to_path_buf())
            .await
            .expect("storage init");
        (temp, Arc::new(storage) as Arc<dyn Storage>)
    }

    fn fresh(id: &str) -> Session {
        Session::new(id.to_string(), "test-model".to_string())
    }

    fn set_permission_audit(
        session: &mut Session,
        requested: bamboo_domain::SessionPermissionMode,
        policy_revision: u64,
        mapping: &str,
        transitioned_at: &str,
    ) -> u64 {
        let resolution = bamboo_domain::resolve_permission_mode(requested, PermissionMode::Default);
        session
            .agent_runtime_state
            .get_or_insert_with(bamboo_domain::AgentRuntimeState::default)
            .set_permission_mode(requested);
        bamboo_domain::record_permission_audit(
            &mut session.metadata,
            &PermissionAuditSeed::new(policy_revision, resolution, mapping),
            Some(transitioned_at),
        )
        .unwrap()
    }

    #[tokio::test]
    async fn same_mode_newer_run_start_audit_survives_every_runtime_save_path() {
        for path in ["merge", "checkpoint", "control-plane"] {
            let (_temp, storage) = make_storage().await;
            let store = LockedSessionStore::new(storage.clone());
            let session_id = format!("same-mode-newer-{path}");
            let mut durable = fresh(&session_id);
            set_permission_audit(
                &mut durable,
                bamboo_domain::SessionPermissionMode::Default,
                1,
                "bamboo_runtime:old-policy",
                "2026-07-31T12:00:00Z",
            );
            storage.save_session(&durable).await.unwrap();

            let mut run_start = durable.clone();
            let old_revision = PermissionAuditSnapshot::from_metadata(&durable.metadata)
                .unwrap()
                .audit_revision;
            let new_revision = set_permission_audit(
                &mut run_start,
                bamboo_domain::SessionPermissionMode::Default,
                2,
                "bamboo_runtime:new-policy",
                "2026-07-31T12:00:00Z",
            );
            assert!(new_revision > old_revision);

            match path {
                "merge" => store.merge_save_runtime(&mut run_start).await.unwrap(),
                "checkpoint" => store
                    .checkpoint_runtime_session(&mut run_start)
                    .await
                    .unwrap(),
                "control-plane" => store.save_runtime_only(&mut run_start).await.unwrap(),
                _ => unreachable!(),
            }

            let saved = storage.load_session(&session_id).await.unwrap().unwrap();
            let audit = PermissionAuditSnapshot::from_metadata(&saved.metadata).unwrap();
            assert_eq!(audit.audit_revision, new_revision, "path={path}");
            assert_eq!(audit.policy_revision, 2, "path={path}");
            assert_eq!(audit.executor_mapping, "bamboo_runtime:new-policy");
        }
    }

    #[tokio::test]
    async fn newer_disk_transition_wins_after_mode_cycles_back() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "permission-cycle-back";
        let mut baseline = fresh(session_id);
        let stale_revision = set_permission_audit(
            &mut baseline,
            bamboo_domain::SessionPermissionMode::Default,
            1,
            "bamboo_runtime:initial",
            "2026-07-31T12:00:00Z",
        );
        storage.save_session(&baseline).await.unwrap();
        let mut stale_runtime = baseline.clone();

        let mut durable = baseline;
        set_permission_audit(
            &mut durable,
            bamboo_domain::SessionPermissionMode::Auto,
            2,
            "bamboo_runtime:auto",
            "2026-07-31T12:01:00Z",
        );
        let durable_revision = set_permission_audit(
            &mut durable,
            bamboo_domain::SessionPermissionMode::Default,
            3,
            "bamboo_runtime:cycled-default",
            "2026-07-31T12:02:00Z",
        );
        assert!(durable_revision > stale_revision);
        storage.save_session(&durable).await.unwrap();

        store.merge_save_runtime(&mut stale_runtime).await.unwrap();
        let saved = storage.load_session(session_id).await.unwrap().unwrap();
        let audit = PermissionAuditSnapshot::from_metadata(&saved.metadata).unwrap();
        assert_eq!(audit.audit_revision, durable_revision);
        assert_eq!(audit.policy_revision, 3);
        assert_eq!(audit.executor_mapping, "bamboo_runtime:cycled-default");
    }

    #[tokio::test]
    async fn authoritative_activation_seed_replaces_every_warm_worker_posture() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "warm-permission-matrix";
        let cases = [
            (
                bamboo_domain::SessionPermissionMode::Auto,
                PermissionMode::Default,
                PermissionMode::Auto,
            ),
            (
                bamboo_domain::SessionPermissionMode::Default,
                PermissionMode::Default,
                PermissionMode::Default,
            ),
            (
                bamboo_domain::SessionPermissionMode::Auto,
                PermissionMode::Default,
                PermissionMode::Auto,
            ),
            (
                bamboo_domain::SessionPermissionMode::Bypass,
                PermissionMode::Auto,
                PermissionMode::BypassPermissions,
            ),
        ];
        let mut previous_revision = 0;

        for (index, (requested, configured, expected_effective)) in cases.into_iter().enumerate() {
            let mut activation = fresh(session_id);
            activation
                .agent_runtime_state
                .get_or_insert_with(bamboo_domain::AgentRuntimeState::default)
                .set_permission_mode(requested);
            let resolution = bamboo_domain::resolve_permission_mode(requested, configured);
            bamboo_domain::record_permission_audit(
                &mut activation.metadata,
                &PermissionAuditSeed::new(
                    index as u64 + 1,
                    resolution,
                    format!("bamboo_worker:{}", resolution.effective.as_str()),
                ),
                Some("2026-07-31T12:00:00Z"),
            )
            .unwrap();

            RuntimeSessionPersistence::seed_runtime_activation(&store, &mut activation)
                .await
                .unwrap();
            let durable = storage.load_session(session_id).await.unwrap().unwrap();
            assert_eq!(
                durable
                    .agent_runtime_state
                    .as_ref()
                    .unwrap()
                    .effective_permission_mode(),
                requested,
                "activation {index}"
            );
            let audit = PermissionAuditSnapshot::from_metadata(&durable.metadata).unwrap();
            assert_eq!(audit.resolution.requested, requested);
            assert_eq!(audit.resolution.effective, expected_effective);
            assert!(audit.audit_revision > previous_revision);
            previous_revision = audit.audit_revision;
        }
    }

    #[tokio::test]
    async fn resident_reseed_bumps_etag_only_for_typed_transition() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "resident-atomic-permission";
        let mut baseline = fresh(session_id);
        baseline.metadata_version = 7;
        set_permission_audit(
            &mut baseline,
            bamboo_domain::SessionPermissionMode::Auto,
            1,
            "bamboo_runtime:auto",
            "2026-07-31T12:00:00Z",
        );
        storage.save_session(&baseline).await.unwrap();
        let initial_audit = PermissionAuditSnapshot::from_metadata(&baseline.metadata).unwrap();

        let same_mode_seed = PermissionAuditSeed::bamboo_runtime(
            2,
            bamboo_domain::resolve_permission_mode(
                bamboo_domain::SessionPermissionMode::Auto,
                PermissionMode::Default,
            ),
        );
        let refreshed = store
            .update_authoritative_permission_posture_and_publish(
                session_id,
                &same_mode_seed,
                |session| {
                    session
                        .metadata
                        .insert("resident.marker".to_string(), "same-mode".to_string());
                },
                |_| {},
            )
            .await
            .unwrap()
            .unwrap();
        let refreshed_audit = PermissionAuditSnapshot::from_metadata(&refreshed.metadata).unwrap();
        assert_eq!(refreshed.metadata_version, 7);
        assert!(refreshed_audit.audit_revision > initial_audit.audit_revision);
        assert_eq!(refreshed_audit.policy_revision, 2);

        let transition_seed = PermissionAuditSeed::bamboo_runtime(
            3,
            bamboo_domain::resolve_permission_mode(
                bamboo_domain::SessionPermissionMode::Default,
                PermissionMode::Default,
            ),
        );
        let transitioned = store
            .update_authoritative_permission_posture_and_publish(
                session_id,
                &transition_seed,
                |session| {
                    session
                        .metadata
                        .insert("resident.marker".to_string(), "transition".to_string());
                },
                |_| {},
            )
            .await
            .unwrap()
            .unwrap();
        let transitioned_audit =
            PermissionAuditSnapshot::from_metadata(&transitioned.metadata).unwrap();
        assert_eq!(transitioned.metadata_version, 8, "old ETag must be invalid");
        assert_eq!(
            transitioned
                .agent_runtime_state
                .as_ref()
                .unwrap()
                .effective_permission_mode(),
            bamboo_domain::SessionPermissionMode::Default
        );
        assert_eq!(
            transitioned_audit.resolution.requested,
            bamboo_domain::SessionPermissionMode::Default
        );
        assert!(transitioned_audit.audit_revision > refreshed_audit.audit_revision);
        assert_eq!(
            transitioned
                .metadata
                .get("resident.marker")
                .map(String::as_str),
            Some("transition")
        );
    }

    #[tokio::test]
    async fn worker_activation_cas_cannot_overwrite_concurrent_permission_patch() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "permission-activation-cas";
        let mut baseline = fresh(session_id);
        set_permission_audit(
            &mut baseline,
            bamboo_domain::SessionPermissionMode::Default,
            1,
            "bamboo_runtime:default",
            "2026-07-31T12:00:00Z",
        );
        storage.save_session(&baseline).await.unwrap();
        let dispatched_revision = PermissionAuditSnapshot::from_metadata(&baseline.metadata)
            .unwrap()
            .audit_revision;

        let patched_resolution = bamboo_domain::resolve_permission_mode(
            bamboo_domain::SessionPermissionMode::Auto,
            PermissionMode::Default,
        );
        let patched = store
            .update_authoritative_permission_posture_and_publish(
                session_id,
                &PermissionAuditSeed::new(2, patched_resolution, "patch:auto"),
                |_| {},
                |_| {},
            )
            .await
            .unwrap()
            .unwrap();
        let patched_audit = PermissionAuditSnapshot::from_metadata(&patched.metadata).unwrap();
        assert!(patched_audit.audit_revision > dispatched_revision);

        let stale_worker_seed = PermissionAuditSeed::new(
            1,
            bamboo_domain::resolve_permission_mode(
                bamboo_domain::SessionPermissionMode::Default,
                PermissionMode::Default,
            ),
            "worker:stale-default",
        );
        let error = store
            .record_permission_posture_activation_and_publish(
                session_id,
                Some(dispatched_revision),
                &stale_worker_seed,
                |_| {},
            )
            .await
            .unwrap_err();
        assert!(error.to_string().contains("durable audit changed"));

        let durable = storage.load_session(session_id).await.unwrap().unwrap();
        let durable_audit = PermissionAuditSnapshot::from_metadata(&durable.metadata).unwrap();
        assert_eq!(durable_audit, patched_audit);
        assert_eq!(durable_audit.executor_mapping, "patch:auto");
    }

    // ── update_runtime_config: config patches must never clobber messages ──

    #[tokio::test]
    async fn update_runtime_config_preserves_concurrently_appended_messages() {
        use bamboo_domain::session::types::Message;
        use bamboo_domain::ReasoningEffort;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "cfg-preserve";

        // Persisted baseline: one user + one assistant turn.
        let mut initial = fresh(session_id);
        initial.add_message(Message::user("hello"));
        initial.add_message(Message::assistant("hi", None));
        storage.save_session(&initial).await.unwrap();

        // Simulate `POST /chat` appending a new user message to disk.
        let mut after_chat = storage.load_session(session_id).await.unwrap().unwrap();
        after_chat.add_message(Message::user("second question"));
        storage.save_session(&after_chat).await.unwrap();
        assert_eq!(after_chat.messages.len(), 3);

        // A config-only patch must load the freshest session and preserve the
        // appended message (this is the regression that broke message sending on
        // existing sessions).
        let updated = store
            .update_runtime_config(session_id, |s| {
                s.reasoning_effort = Some(ReasoningEffort::Max);
            })
            .await
            .unwrap()
            .expect("session exists");

        assert_eq!(updated.reasoning_effort, Some(ReasoningEffort::Max));
        assert_eq!(
            updated.messages.len(),
            3,
            "config patch must not revert a concurrently-appended message"
        );

        let on_disk = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(on_disk.messages.len(), 3);
        assert_eq!(on_disk.reasoning_effort, Some(ReasoningEffort::Max));
    }

    #[tokio::test]
    async fn update_runtime_config_returns_none_for_missing_session() {
        use bamboo_domain::ReasoningEffort;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage);
        let result = store
            .update_runtime_config("does-not-exist", |s| {
                s.reasoning_effort = Some(ReasoningEffort::Low);
            })
            .await
            .unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn merge_save_runtime_overwrites_messages_from_stale_snapshot() {
        // Characterization of the bug that motivated `update_runtime_config`:
        // `merge_save_runtime` writes the caller's `messages` verbatim, so a
        // stale snapshot reverts a concurrent append. Config-only writers must
        // therefore use `update_runtime_config`, never `merge_save_runtime`.
        use bamboo_domain::session::types::Message;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "stale-clobber";

        // A handler loads the session (1 message) …
        let mut baseline = fresh(session_id);
        baseline.add_message(Message::user("hello"));
        storage.save_session(&baseline).await.unwrap();
        let mut stale_snapshot = storage.load_session(session_id).await.unwrap().unwrap();

        // … then `POST /chat` appends a second message to disk …
        let mut after_chat = storage.load_session(session_id).await.unwrap().unwrap();
        after_chat.add_message(Message::user("second"));
        storage.save_session(&after_chat).await.unwrap();
        assert_eq!(
            storage
                .load_session(session_id)
                .await
                .unwrap()
                .unwrap()
                .messages
                .len(),
            2
        );

        // … and the stale handler saves via merge_save_runtime -> append reverted.
        store.merge_save_runtime(&mut stale_snapshot).await.unwrap();
        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(
            after.messages.len(),
            1,
            "merge_save_runtime clobbers concurrent appends — this is why config patches must use update_runtime_config"
        );
    }

    #[tokio::test]
    async fn stale_runtime_save_cannot_remove_admitted_inbox_transcript() {
        use bamboo_domain::session::types::Message;
        use bamboo_domain::SessionMessageId;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "stale-inbox-preserve";

        let mut baseline = fresh(session_id);
        let mut base = Message::user("base");
        base.id = "base".to_string();
        baseline.add_message(base);
        storage.save_session(&baseline).await.unwrap();
        let mut stale = baseline.clone();
        let mut later_assistant = Message::assistant("runner output", None);
        later_assistant.id = "later-assistant".to_string();
        stale.add_message(later_assistant);

        let mut durable = baseline;
        let inbox_id = SessionMessageId::parse("durable-inbox-id").unwrap();
        let mut admitted = Message::user("durable inbox message");
        admitted.id = inbox_id.as_str().to_string();
        durable.add_message(admitted);
        durable
            .session_inbox_admission_mut()
            .record(inbox_id.clone(), 7);
        storage.save_session(&durable).await.unwrap();

        store.merge_save_runtime(&mut stale).await.unwrap();
        let saved = storage.load_session(session_id).await.unwrap().unwrap();
        let ids = saved
            .messages
            .iter()
            .map(|message| message.id.as_str())
            .collect::<Vec<_>>();
        assert_eq!(ids, vec!["base", "durable-inbox-id", "later-assistant"]);
        assert_eq!(ids.iter().filter(|id| **id == inbox_id.as_str()).count(), 1);
        assert!(saved
            .session_inbox_admission()
            .is_some_and(|state| state.contains(&inbox_id)));
    }

    #[tokio::test]
    async fn stale_runtime_save_preserves_typed_inbox_message_after_cursor_eviction() {
        use bamboo_domain::{
            SessionMessageEnvelope, SessionMessageId, SESSION_INBOX_ADMITTED_CAPACITY,
        };

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "evicted-inbox-preserve";
        let mut durable = fresh(session_id);
        let mut envelope = SessionMessageEnvelope::user_input(session_id, "old durable inbox");
        envelope.id = SessionMessageId::parse("old-inbox-id").unwrap();
        durable.add_message(envelope.to_provider_message().unwrap());
        durable
            .session_inbox_admission_mut()
            .record(envelope.id.clone(), 1);
        for sequence in 2..=(SESSION_INBOX_ADMITTED_CAPACITY as u64 + 1) {
            durable.session_inbox_admission_mut().record(
                SessionMessageId::parse(format!("newer-{sequence}")).unwrap(),
                sequence,
            );
        }
        assert!(!durable
            .session_inbox_admission()
            .unwrap()
            .contains(&envelope.id));
        storage.save_session(&durable).await.unwrap();

        let mut stale = fresh(session_id);
        store.merge_save_runtime(&mut stale).await.unwrap();
        let saved = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(
            saved
                .messages
                .iter()
                .filter(|message| message.id == envelope.id.as_str())
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn checkpoint_runtime_session_preserves_disk_suffix_and_appends_live_messages() {
        use bamboo_domain::session::types::Message;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "checkpoint-no-shrink";

        let mut baseline = fresh(session_id);
        baseline.add_message(Message::user("base"));
        storage.save_session(&baseline).await.unwrap();
        let mut runner_snapshot = baseline.clone();

        let mut durable = baseline;
        let mut disk_only = Message::user("concurrent injected message");
        disk_only.id = "disk-only".to_string();
        durable.add_message(disk_only);
        storage.save_session(&durable).await.unwrap();

        let mut live_only = Message::assistant("partial runner output", None);
        live_only.id = "live-only".to_string();
        runner_snapshot.add_message(live_only);

        store
            .checkpoint_runtime_session(&mut runner_snapshot)
            .await
            .unwrap();

        let saved = storage.load_session(session_id).await.unwrap().unwrap();
        let ids = saved
            .messages
            .iter()
            .map(|message| message.id.as_str())
            .collect::<Vec<_>>();
        assert_eq!(
            ids,
            vec![durable.messages[0].id.as_str(), "disk-only", "live-only"]
        );
        assert_eq!(runner_snapshot.messages.len(), saved.messages.len());
        assert_eq!(runner_snapshot.messages[1].id, saved.messages[1].id);
        assert_eq!(runner_snapshot.messages[2].id, saved.messages[2].id);
        assert_eq!(saved.messages[1].content, "concurrent injected message");
        assert_eq!(saved.messages[2].content, "partial runner output");
    }

    #[tokio::test]
    async fn activation_checkpoint_clears_presentation_without_shrinking_concurrent_turn() {
        use bamboo_domain::session::runtime_state::{
            AgentRuntimeState, AgentStatusState, WaitingForChildrenState,
        };
        use bamboo_domain::session::types::Message;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "activation-no-shrink";
        let mut baseline = fresh(session_id);
        baseline.add_message(Message::user("base"));
        let mut state = AgentRuntimeState::new("activation-run");
        state.status = AgentStatusState::Suspended;
        state.waiting_for_children = Some(WaitingForChildrenState::for_children(
            vec!["child-1".to_string()],
            bamboo_domain::session::runtime_state::ChildWaitPolicy::All,
            chrono::Utc::now(),
        ));
        baseline.agent_runtime_state = Some(state);
        baseline.metadata.insert(
            "runtime.suspend_reason".to_string(),
            "waiting_for_children".to_string(),
        );
        storage.save_session(&baseline).await.unwrap();
        let mut activation_snapshot = baseline.clone();

        let mut concurrent = baseline;
        let mut normal = Message::assistant("normal concurrent answer", None);
        normal.id = "normal-concurrent".to_string();
        concurrent.add_message(normal);
        storage.save_session(&concurrent).await.unwrap();

        let state = activation_snapshot.agent_runtime_state.as_mut().unwrap();
        state.status = AgentStatusState::Idle;
        state.suspension = None;
        activation_snapshot
            .metadata
            .remove("runtime.suspend_reason");
        store
            .checkpoint_runtime_session(&mut activation_snapshot)
            .await
            .unwrap();

        let saved = storage.load_session(session_id).await.unwrap().unwrap();
        assert!(saved
            .messages
            .iter()
            .any(|message| message.id == "normal-concurrent"));
        let state = saved.agent_runtime_state.unwrap();
        assert_eq!(state.status, AgentStatusState::Idle);
        assert!(state.waiting_for_children.is_some());
        assert!(!saved.metadata.contains_key("runtime.suspend_reason"));
    }

    #[tokio::test]
    async fn merge_save_runtime_preserves_disk_authoritative_metadata_with_single_load() {
        // Regression guard for the single-load refactor of `merge_save_runtime`:
        // it must STILL pull the authoritative metadata group (title / pinned /
        // metadata_version) from the freshest on-disk copy when disk's
        // metadata_version >= the in-memory one, even though it now reads disk
        // only once.
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "runtime-merge-meta";

        // Baseline persisted by a runtime writer (metadata_version 0).
        let mut baseline = fresh(session_id);
        baseline.title = "Auto Title".to_string();
        baseline.metadata_version = 0;
        storage.save_session(&baseline).await.unwrap();

        // A stale runtime snapshot (still metadata_version 0, old title).
        let mut stale_snapshot = storage.load_session(session_id).await.unwrap().unwrap();

        // An authoritative UI rename bumps metadata_version on disk.
        let mut renamed = storage.load_session(session_id).await.unwrap().unwrap();
        renamed.title = "User Renamed".to_string();
        renamed.title_version = 1;
        renamed.pinned = true;
        renamed.metadata_version = 1;
        store.commit_metadata(&renamed).await.unwrap();

        // The stale runtime writer saves: it must adopt the disk title/pinned.
        stale_snapshot.title = "Auto Title".to_string();
        store.merge_save_runtime(&mut stale_snapshot).await.unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(after.title, "User Renamed");
        assert!(after.pinned);
        assert_eq!(after.metadata_version, 1);
        // And the in-memory copy was corrected by the merge too.
        assert_eq!(stale_snapshot.title, "User Renamed");
        assert_eq!(stale_snapshot.metadata_version, 1);
    }

    #[tokio::test]
    async fn merge_save_runtime_preserves_durable_workflow_run_index_from_stale_runner() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "runtime-workflow-run-index";

        let baseline = fresh(session_id);
        storage.save_session(&baseline).await.unwrap();
        let mut stale_runner = storage.load_session(session_id).await.unwrap().unwrap();

        store
            .update_runtime_config(session_id, |session| {
                session.metadata.insert(
                    "workflow.run_ids.v1".to_string(),
                    r#"["http-started-run"]"#.to_string(),
                );
            })
            .await
            .unwrap()
            .expect("session exists");

        store.merge_save_runtime(&mut stale_runner).await.unwrap();

        assert_eq!(
            stale_runner
                .metadata
                .get("workflow.run_ids.v1")
                .map(String::as_str),
            Some(r#"["http-started-run"]"#)
        );
        let durable = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(
            durable
                .metadata
                .get("workflow.run_ids.v1")
                .map(String::as_str),
            Some(r#"["http-started-run"]"#)
        );
    }

    // #540: a running loop's `merge_save_runtime` (carrying the run-start bypass
    // value) must NOT revert a concurrent mid-run `PATCH /sessions
    // {bypass_permissions}` write on disk — disk is the authoritative writer.
    #[tokio::test]
    async fn merge_save_runtime_adopts_disk_bypass_permissions() {
        use bamboo_domain::AgentRuntimeState;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "runtime-bypass";

        // Baseline persisted with bypass OFF.
        let baseline = fresh(session_id);
        storage.save_session(&baseline).await.unwrap();

        // The running loop holds a snapshot with bypass OFF (run-start value).
        let mut loop_snapshot = storage.load_session(session_id).await.unwrap().unwrap();
        loop_snapshot.agent_runtime_state = Some(AgentRuntimeState::default());

        // A concurrent PATCH flips bypass ON on disk (via update_runtime_config).
        store
            .update_runtime_config(session_id, |s| {
                s.agent_runtime_state
                    .get_or_insert_with(AgentRuntimeState::default)
                    .bypass_permissions = true;
            })
            .await
            .unwrap()
            .expect("session exists");

        // The loop saves its stale snapshot: it must adopt disk's ON value, not
        // revert to OFF.
        store.merge_save_runtime(&mut loop_snapshot).await.unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert!(
            after
                .agent_runtime_state
                .as_ref()
                .is_some_and(|s| s.bypass_permissions),
            "disk bypass=ON must survive a stale runtime save (#540)"
        );
        // The in-memory copy is corrected too.
        assert!(loop_snapshot
            .agent_runtime_state
            .as_ref()
            .is_some_and(|s| s.bypass_permissions));
    }

    // #770: the generalized disk-wins path must preserve Auto as a distinct
    // typed mode rather than collapsing it into the legacy bypass boolean.
    #[tokio::test]
    async fn merge_save_runtime_adopts_disk_auto_permission_mode() {
        use bamboo_domain::{AgentRuntimeState, SessionPermissionMode};

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "runtime-auto";

        storage.save_session(&fresh(session_id)).await.unwrap();
        let mut loop_snapshot = storage.load_session(session_id).await.unwrap().unwrap();
        loop_snapshot.agent_runtime_state = Some(AgentRuntimeState::default());
        loop_snapshot.metadata.insert(
            "permission.requested_mode".to_string(),
            "default".to_string(),
        );
        loop_snapshot.metadata.insert(
            "permission.effective_mode".to_string(),
            "default".to_string(),
        );
        loop_snapshot.metadata.insert(
            "permission.executor_mapping".to_string(),
            "bamboo_runtime:default".to_string(),
        );

        store
            .update_runtime_config(session_id, |session| {
                session
                    .agent_runtime_state
                    .get_or_insert_with(AgentRuntimeState::default)
                    .set_permission_mode(SessionPermissionMode::Auto);
                session
                    .metadata
                    .insert("permission.policy_revision".to_string(), "12".to_string());
                session
                    .metadata
                    .insert("permission.requested_mode".to_string(), "auto".to_string());
                session
                    .metadata
                    .insert("permission.effective_mode".to_string(), "auto".to_string());
                session.metadata.insert(
                    "permission.executor_mapping".to_string(),
                    "bamboo_runtime:auto".to_string(),
                );
                session.metadata.insert(
                    "permission.transitioned_at".to_string(),
                    "2026-07-31T12:00:00Z".to_string(),
                );
                session.metadata_version = session.metadata_version.saturating_add(1);
            })
            .await
            .unwrap()
            .expect("session exists");

        store.merge_save_runtime(&mut loop_snapshot).await.unwrap();

        let durable = storage.load_session(session_id).await.unwrap().unwrap();
        for state in [
            durable.agent_runtime_state.as_ref(),
            loop_snapshot.agent_runtime_state.as_ref(),
        ] {
            assert_eq!(
                state.map(AgentRuntimeState::effective_permission_mode),
                Some(SessionPermissionMode::Auto)
            );
        }
        for session in [&durable, &loop_snapshot] {
            assert_eq!(
                session.metadata.get("permission.policy_revision"),
                Some(&"12".to_string())
            );
            assert_eq!(
                session.metadata.get("permission.requested_mode"),
                Some(&"auto".to_string())
            );
            assert_eq!(
                session.metadata.get("permission.effective_mode"),
                Some(&"auto".to_string())
            );
            assert_eq!(
                session.metadata.get("permission.executor_mapping"),
                Some(&"bamboo_runtime:auto".to_string())
            );
            assert_eq!(
                session.metadata.get("permission.transitioned_at"),
                Some(&"2026-07-31T12:00:00Z".to_string())
            );
        }
    }

    // The reverse direction: a PATCH turning bypass OFF must also stick against
    // a stale loop snapshot that still has it ON.
    #[tokio::test]
    async fn merge_save_runtime_adopts_disk_bypass_off() {
        use bamboo_domain::AgentRuntimeState;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "runtime-bypass-off";

        // Baseline persisted with bypass ON.
        let mut baseline = fresh(session_id);
        let on_state = AgentRuntimeState {
            bypass_permissions: true,
            ..AgentRuntimeState::default()
        };
        baseline.agent_runtime_state = Some(on_state);
        storage.save_session(&baseline).await.unwrap();

        // Loop snapshot still ON.
        let mut loop_snapshot = storage.load_session(session_id).await.unwrap().unwrap();

        // PATCH flips OFF on disk.
        store
            .update_runtime_config(session_id, |s| {
                s.agent_runtime_state
                    .get_or_insert_with(AgentRuntimeState::default)
                    .bypass_permissions = false;
            })
            .await
            .unwrap()
            .expect("session exists");

        store.merge_save_runtime(&mut loop_snapshot).await.unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert!(
            !after
                .agent_runtime_state
                .as_ref()
                .is_some_and(|s| s.bypass_permissions),
            "disk bypass=OFF must survive a stale runtime save (#540)"
        );
    }

    // #540 review: the authoritative flag writer (#74 child-reseed) must NOT be
    // reverted by the disk-wins protection — its in-memory value persists as-is.
    #[tokio::test]
    async fn save_runtime_authoritative_flags_persists_in_memory_posture_and_audit() {
        use bamboo_domain::AgentRuntimeState;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "child-reseed";

        // Child on disk has bypass ON (created under a bypassed parent).
        let mut baseline = fresh(session_id);
        let on_state = AgentRuntimeState {
            bypass_permissions: true,
            ..AgentRuntimeState::default()
        };
        baseline.agent_runtime_state = Some(on_state);
        for (key, value) in [
            ("permission.policy_revision", "12"),
            ("permission.requested_mode", "bypass"),
            ("permission.effective_mode", "bypass"),
            ("permission.executor_mapping", "bamboo_runtime:bypass"),
            ("permission.transitioned_at", "2026-07-31T12:00:00Z"),
        ] {
            baseline.metadata.insert(key.to_string(), value.to_string());
        }
        storage.save_session(&baseline).await.unwrap();

        // Parent re-seeds the reused child to OFF (parent flipped bypass off),
        // loading the child then setting the flag in memory.
        let mut child = storage.load_session(session_id).await.unwrap().unwrap();
        child
            .agent_runtime_state
            .get_or_insert_with(AgentRuntimeState::default)
            .bypass_permissions = false;
        for (key, value) in [
            ("permission.policy_revision", "13"),
            ("permission.requested_mode", "default"),
            ("permission.effective_mode", "default"),
            ("permission.executor_mapping", "bamboo_runtime:default"),
            ("permission.transitioned_at", "2026-07-31T12:01:00Z"),
        ] {
            child.metadata.insert(key.to_string(), value.to_string());
        }

        // Authoritative write must persist OFF, not adopt the disk's stale ON.
        store
            .save_runtime_authoritative_flags(&mut child)
            .await
            .unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert!(
            !after
                .agent_runtime_state
                .as_ref()
                .is_some_and(|s| s.bypass_permissions),
            "authoritative re-seed of bypass=OFF must persist, not be reverted (#540/#74)"
        );
        for (key, value) in [
            ("permission.policy_revision", "13"),
            ("permission.requested_mode", "default"),
            ("permission.effective_mode", "default"),
            ("permission.executor_mapping", "bamboo_runtime:default"),
            ("permission.transitioned_at", "2026-07-31T12:01:00Z"),
        ] {
            assert_eq!(after.metadata.get(key).map(String::as_str), Some(value));
        }
    }

    // A disk copy lacking runtime state must not force the in-memory bypass OFF.
    #[tokio::test]
    async fn merge_save_runtime_leaves_bypass_when_disk_has_no_runtime_state() {
        use bamboo_domain::AgentRuntimeState;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "no-runtime-state";

        // Disk copy with NO agent_runtime_state.
        let baseline = fresh(session_id);
        assert!(baseline.agent_runtime_state.is_none());
        storage.save_session(&baseline).await.unwrap();

        // A running loop legitimately carries bypass ON in memory.
        let mut running = storage.load_session(session_id).await.unwrap().unwrap();
        let on_state = AgentRuntimeState {
            bypass_permissions: true,
            ..AgentRuntimeState::default()
        };
        running.agent_runtime_state = Some(on_state);

        store.merge_save_runtime(&mut running).await.unwrap();

        assert!(
            running
                .agent_runtime_state
                .as_ref()
                .is_some_and(|s| s.bypass_permissions),
            "a runtime-state-less disk copy must not force bypass OFF (#540)"
        );
    }

    // ── Free-function merge tests (updated for metadata-group) ──────

    #[tokio::test]
    async fn merge_preserves_disk_title_when_versions_equal() {
        let (_temp, storage) = make_storage().await;
        let session_id = "merge-equal";

        let mut on_disk = fresh(session_id);
        on_disk.title = "User Set This".to_string();
        on_disk.title_version = 0;
        on_disk.metadata_version = 0;
        storage.save_session(&on_disk).await.unwrap();

        let mut runtime_copy = fresh(session_id);
        runtime_copy.title = "Stale Default".to_string();
        runtime_copy.title_version = 0;
        runtime_copy.metadata_version = 0;
        runtime_copy.messages = vec![];

        merge_save_session(&storage, &mut runtime_copy)
            .await
            .unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(after.title, "User Set This");
        assert_eq!(after.title_version, 0);
        assert_eq!(runtime_copy.title, "User Set This");
    }

    #[tokio::test]
    async fn merge_preserves_disk_when_disk_version_higher() {
        let (_temp, storage) = make_storage().await;
        let session_id = "merge-higher";

        let mut on_disk = fresh(session_id);
        on_disk.title = "User Title v3".to_string();
        on_disk.title_version = 3;
        on_disk.metadata_version = 5;
        storage.save_session(&on_disk).await.unwrap();

        let mut runtime_copy = fresh(session_id);
        runtime_copy.title = "Stale".to_string();
        runtime_copy.title_version = 1;
        runtime_copy.metadata_version = 0;

        merge_save_session(&storage, &mut runtime_copy)
            .await
            .unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(after.title, "User Title v3");
        assert_eq!(after.title_version, 3);
        assert_eq!(after.metadata_version, 5);
    }

    #[tokio::test]
    async fn merge_now_preserves_disk_pinned_in_metadata_group() {
        let (_temp, storage) = make_storage().await;
        let session_id = "pinned-merge";

        let mut on_disk = fresh(session_id);
        on_disk.pinned = true;
        on_disk.metadata_version = 2;
        storage.save_session(&on_disk).await.unwrap();

        let mut runtime_copy = fresh(session_id);
        runtime_copy.pinned = false;
        runtime_copy.metadata_version = 0;

        merge_save_session(&storage, &mut runtime_copy)
            .await
            .unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert!(
            after.pinned,
            "disk pinned=true should win over runtime false"
        );
        assert_eq!(after.metadata_version, 2);
    }

    #[tokio::test]
    async fn merge_keeps_in_memory_when_session_version_higher() {
        let (_temp, storage) = make_storage().await;
        let session_id = "merge-bumped";

        let mut on_disk = fresh(session_id);
        on_disk.title = "Old".to_string();
        on_disk.title_version = 1;
        on_disk.metadata_version = 3;
        storage.save_session(&on_disk).await.unwrap();

        let mut authoritative_copy = fresh(session_id);
        authoritative_copy.title = "New Authoritative".to_string();
        authoritative_copy.title_version = 2;
        authoritative_copy.metadata_version = 4;
        authoritative_copy.pinned = true;

        merge_save_session(&storage, &mut authoritative_copy)
            .await
            .unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(after.title, "New Authoritative");
        assert_eq!(after.title_version, 2);
        assert_eq!(after.metadata_version, 4);
        assert!(after.pinned);
    }

    #[tokio::test]
    async fn merge_keeps_runtime_messages_when_disk_only_changed_metadata() {
        let (_temp, storage) = make_storage().await;
        let session_id = "merge-messages";

        let mut on_disk = fresh(session_id);
        on_disk.title = "Fresh Title".to_string();
        on_disk.title_version = 2;
        on_disk.metadata_version = 5;
        storage.save_session(&on_disk).await.unwrap();

        let mut runtime_copy = fresh(session_id);
        runtime_copy.title = "Stale".to_string();
        runtime_copy.metadata_version = 0;
        runtime_copy.messages = vec![bamboo_domain::session::types::Message {
            role: bamboo_domain::session::types::Role::User,
            content: "keep me".to_string(),
            id: "msg-1".to_string(),
            created_at: chrono::Utc::now(),
            reasoning: None,
            reasoning_signature: None,
            content_parts: None,
            image_ocr: None,
            phase: None,
            tool_calls: None,
            tool_call_id: None,
            tool_success: None,
            compressed: false,
            compressed_by_event_id: None,
            never_compress: false,
            compression_level: 0,
            metadata: None,
        }];

        merge_save_session(&storage, &mut runtime_copy)
            .await
            .unwrap();

        let after = storage.load_session(session_id).await.unwrap().unwrap();
        assert_eq!(after.title, "Fresh Title");
        assert_eq!(after.metadata_version, 5);
        assert_eq!(after.messages.len(), 1);
        assert_eq!(after.messages[0].content, "keep me");
    }

    #[tokio::test]
    async fn runtime_control_plane_port_uses_sidecar_without_rewriting_messages() {
        use bamboo_domain::session::types::Message;

        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage.clone());
        let session_id = "runtime-control-plane";

        let mut durable = fresh(session_id);
        durable.add_message(Message::user("durable transcript"));
        storage.save_session(&durable).await.unwrap();

        let mut runtime = durable.clone();
        runtime.model = "updated-control-plane-model".to_string();
        runtime.add_message(Message::assistant("uncheckpointed runtime message", None));
        RuntimeSessionPersistence::save_runtime_control_plane(&store, &mut runtime)
            .await
            .unwrap();

        let control_plane =
            RuntimeSessionPersistence::load_runtime_control_plane(&store, session_id)
                .await
                .unwrap()
                .expect("control-plane exists");
        assert!(
            control_plane.messages.is_empty(),
            "LockedSessionStore must expose its message-free sidecar"
        );
        assert_eq!(control_plane.model, "updated-control-plane-model");

        let reloaded = storage
            .load_session(session_id)
            .await
            .unwrap()
            .expect("session exists");
        assert_eq!(reloaded.model, "updated-control-plane-model");
        assert_eq!(
            reloaded.messages.len(),
            1,
            "control-plane save must not write the uncheckpointed message"
        );
        assert_eq!(reloaded.messages[0].content, "durable transcript");
    }

    #[tokio::test]
    async fn atomic_task_patch_loads_inside_lock_and_preserves_interleaved_runtime_state() {
        let temp = tempfile::tempdir().unwrap();
        let inner = Arc::new(
            SessionStoreV2::new(temp.path().to_path_buf())
                .await
                .expect("storage init"),
        );
        let session_id = "atomic-task-patch";
        inner
            .save_session(&fresh(session_id))
            .await
            .expect("seed session");

        let counted = Arc::new(CountingControlPlaneStorage {
            inner: inner.clone(),
            control_plane_loads: AtomicUsize::new(0),
        });
        let storage: Arc<dyn Storage> = counted.clone();
        let store = Arc::new(LockedSessionStore::new(storage));
        let guard = store.acquire_lock(session_id).await;
        let now = chrono::Utc::now();
        let task_list = bamboo_domain::TaskList {
            session_id: session_id.to_string(),
            title: "Atomic Task patch".to_string(),
            items: Vec::new(),
            created_at: now,
            updated_at: now,
        };
        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
        let patch_store = store.clone();
        let patch = tokio::spawn(async move {
            let _ = started_tx.send(());
            RuntimeSessionPersistence::update_task_list_control_plane(
                patch_store.as_ref(),
                session_id,
                &task_list,
                "9",
            )
            .await
        });
        started_rx.await.expect("patch task started");
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        assert_eq!(
            counted.control_plane_loads.load(Ordering::SeqCst),
            0,
            "Task patch must acquire the session lock before loading its snapshot"
        );

        // Publish a newer unrelated runtime transition while the Task patch is
        // queued on the same session lock. Once the guard releases, the patch
        // must load this latest snapshot and change only Task-owned fields.
        let mut latest = inner
            .load_runtime_control_plane(session_id)
            .await
            .expect("load latest control-plane")
            .expect("control-plane exists");
        latest.agent_runtime_state = Some(bamboo_domain::AgentRuntimeState::new("latest-run"));
        latest
            .metadata
            .insert("concurrent.runtime".to_string(), "preserve".to_string());
        inner
            .save_runtime_state(&latest)
            .await
            .expect("publish concurrent runtime transition");
        drop(guard);

        assert!(
            patch.await.expect("patch join").expect("patch succeeds"),
            "existing root must be patched"
        );
        assert_eq!(counted.control_plane_loads.load(Ordering::SeqCst), 1);
        let reloaded = inner
            .load_session(session_id)
            .await
            .expect("reload")
            .expect("session exists");
        assert_eq!(
            reloaded
                .agent_runtime_state
                .as_ref()
                .map(|state| state.run_id.as_str()),
            Some("latest-run")
        );
        assert_eq!(
            reloaded
                .metadata
                .get("concurrent.runtime")
                .map(String::as_str),
            Some("preserve")
        );
        assert_eq!(reloaded.task_list_version_meta().as_deref(), Some("9"));
        assert_eq!(
            reloaded.task_list.as_ref().map(|list| list.title.as_str()),
            Some("Atomic Task patch")
        );
    }

    // ── LockedSessionStore tests ────────────────────────────────────

    #[tokio::test]
    async fn locked_merge_save_runtime_serialises_concurrent_writes() {
        let (_temp, storage) = make_storage().await;
        let store = Arc::new(LockedSessionStore::new(storage));
        let session_id = "lock-serial".to_string();

        // Seed with base version.
        let base = fresh(&session_id);
        store.storage().save_session(&base).await.unwrap();

        // Two concurrent authorised writers each bump and commit.
        // We'll simulate via clone-and-bump-then-commit.
        let store_a = store.clone();
        let store_b = store.clone();
        let sid_a = session_id.clone();
        let sid_b = session_id.clone();

        let a = tokio::spawn(async move {
            let _guard = store_a.acquire_lock(&sid_a).await;
            let mut s = store_a
                .storage()
                .load_session(&sid_a)
                .await
                .unwrap()
                .unwrap();
            s.title = "Writer A".to_string();
            s.title_version = s.title_version.saturating_add(1);
            s.metadata_version = s.metadata_version.saturating_add(1);
            s.updated_at = chrono::Utc::now();
            store_a.storage().save_session(&s).await.unwrap();
            s.title_version
        });

        // Tiny yield so A goes first.
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        let b = tokio::spawn(async move {
            let _guard = store_b.acquire_lock(&sid_b).await;
            let mut s = store_b
                .storage()
                .load_session(&sid_b)
                .await
                .unwrap()
                .unwrap();
            s.title = "Writer B".to_string();
            s.title_version = s.title_version.saturating_add(1);
            s.metadata_version = s.metadata_version.saturating_add(1);
            s.updated_at = chrono::Utc::now();
            store_b.storage().save_session(&s).await.unwrap();
            s.title_version
        });

        let (ver_a, ver_b) = tokio::join!(a, b);
        let final_s = store
            .storage()
            .load_session(&session_id)
            .await
            .unwrap()
            .unwrap();
        assert!(
            ver_a.unwrap() != ver_b.unwrap(),
            "concurrent writers must produce distinct versions"
        );
        assert_eq!(final_s.metadata_version, 2);
    }

    #[tokio::test]
    async fn commit_metadata_is_plain_save_inside_lock() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage);
        let session_id = "commit-plain";

        let mut s = fresh(session_id);
        s.title = "Committed".to_string();
        s.metadata_version = 1;
        s.title_version = 2;

        store.commit_metadata(&s).await.unwrap();

        let after = store
            .storage()
            .load_session(session_id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(after.title, "Committed");
        assert_eq!(after.metadata_version, 1);
        assert_eq!(after.title_version, 2);
    }

    // ── Self-cleaning per-session lock (issue #346) ─────────────────

    #[tokio::test]
    async fn acquire_lock_self_evicts_when_no_other_holder() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage);

        {
            let _guard = store.acquire_lock("solo").await;
            assert_eq!(store.locks.len(), 1, "entry present while the lock is held");
        }
        // Dropping the guard runs the self-cleaning `remove_if`. Without the
        // eviction logic this stays at 1 forever (the pre-#346 leak).
        assert_eq!(
            store.locks.len(),
            0,
            "lock entry must be evicted once released with no other holder"
        );
    }

    #[tokio::test]
    async fn acquire_lock_many_distinct_ids_do_not_accumulate() {
        let (_temp, storage) = make_storage().await;
        let store = LockedSessionStore::new(storage);

        // Serially acquire+release for 100 distinct session ids.
        for i in 0..100 {
            let _guard = store.acquire_lock(&format!("sess-{i}")).await;
        }
        assert_eq!(
            store.locks.len(),
            0,
            "acquiring locks for many distinct ids must not grow the map"
        );
    }

    #[tokio::test]
    async fn acquire_lock_concurrent_waiter_keeps_valid_lock_and_map_drains() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (_temp, storage) = make_storage().await;
        let store = Arc::new(LockedSessionStore::new(storage));

        // Tracks concurrent holders of the SAME session lock; must never exceed 1.
        let active = Arc::new(AtomicUsize::new(0));
        let max_seen = Arc::new(AtomicUsize::new(0));

        let mut handles = Vec::new();
        for _ in 0..8 {
            let store = store.clone();
            let active = active.clone();
            let max_seen = max_seen.clone();
            handles.push(tokio::spawn(async move {
                let _guard = store.acquire_lock("contended").await;
                let now = active.fetch_add(1, Ordering::SeqCst) + 1;
                max_seen.fetch_max(now, Ordering::SeqCst);
                // Hold briefly so the other tasks actually queue on the mutex.
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
                active.fetch_sub(1, Ordering::SeqCst);
            }));
        }
        for h in handles {
            h.await.unwrap();
        }

        // Mutual exclusion must hold: a self-cleaning removal that raced (removed
        // the entry a waiter had already cloned, letting a later task create and
        // lock a *second* mutex for the same id) would show 2 concurrent holders.
        // `remove_if`'s atomic strong-count check under the shard lock prevents it.
        assert_eq!(
            max_seen.load(Ordering::SeqCst),
            1,
            "at most one holder of a given session lock at a time"
        );
        assert_eq!(
            store.locks.len(),
            0,
            "after all holders release, the contended entry must be fully evicted"
        );
    }
}