bamboo-storage 2026.10.21

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
//! SessionStoreV2's durable per-Session actor activation authority.
//!
//! The ordinary Session remains the identity/transcript source of truth. This
//! small sidecar is a versioned, serialized CAS record for execution attempts.
//! It is never derived from a physical worker or broker mailbox.

use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;
use bamboo_domain::{
    ActorActivation, ActorActivationClaim, ActorActivationFence, ActorActivationFinish,
    ActorActivationStatus, ActorAncestorObservation, ActorControlPlaneBinding, ActorDirectoryEntry,
    ActorDirectoryError, ActorDirectoryPort, ActorLogicalState, ActorSession, ProjectId, Session,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::fs;
use uuid::Uuid;

use super::{
    durable_atomic_write_blocking, validate_session_id, ActorTreeWriteGuard,
    RuntimeTaskTransactionReadGuard, SessionLifecycleReadGuard, SessionStoreV2, SessionWriteGuard,
};

/// Every started filesystem job keeps the same physical and in-process locks
/// alive, even when its async caller or Tokio runtime stops waiting. Field
/// order releases the locks in reverse acquisition order.
struct ActorAuthorityGuards {
    _tree: std::sync::Mutex<Option<ActorTreeWriteGuard>>,
    tree_root: std::sync::Mutex<Option<bamboo_domain::Session>>,
    tree_bumped: std::sync::atomic::AtomicBool,
    _session: SessionWriteGuard,
    _task: RuntimeTaskTransactionReadGuard,
    _lifecycle: SessionLifecycleReadGuard,
}

const ACTOR_AUTHORITY_FILE: &str = "actor-authority.json";
const ACTOR_INITIALIZED_FILE: &str = "actor-authority.initialized.json";

/// Independent evidence that an authority record was fully initialized before
/// the first claim. Losing the mutable sidecar must never restart attempt 0.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ActorInitializedMarker {
    schema_version: u32,
    actor_id: String,
    session_created_at: DateTime<Utc>,
}

/// Pure census validation only; never initialize, refresh or claim an Actor.
pub(super) fn validate_census_witnesses(
    record: &[u8],
    marker: &[u8],
    session: &Session,
    project: Option<&ProjectId>,
) -> io::Result<()> {
    let invalid = || io::Error::new(io::ErrorKind::InvalidData, "invalid census Actor witness");
    let record: ActorDirectoryEntry = serde_json::from_slice(record).map_err(|_| invalid())?;
    let marker: ActorInitializedMarker = serde_json::from_slice(marker).map_err(|_| invalid())?;
    if record.validate().is_err()
        || !record.actor.matches_session(session)
        || record.actor.project_id.as_deref() != project.map(ProjectId::as_str)
        || marker.schema_version != bamboo_domain::ACTOR_DIRECTORY_SCHEMA_VERSION
        || marker.actor_id != session.id
        || marker.session_created_at != session.created_at
    {
        return Err(invalid());
    }
    Ok(())
}

fn storage(error: io::Error) -> ActorDirectoryError {
    ActorDirectoryError::Storage(error.to_string())
}

fn checked_next(value: u64) -> Result<u64, ActorDirectoryError> {
    value
        .checked_add(1)
        .ok_or(ActorDirectoryError::CounterOverflow)
}

pub(super) fn current_live<'a>(
    entry: &'a ActorDirectoryEntry,
    fence: &ActorActivationFence,
    now: DateTime<Utc>,
) -> Result<&'a ActorActivation, ActorDirectoryError> {
    let activation = entry
        .activation
        .as_ref()
        .ok_or(ActorDirectoryError::StaleFence)?;
    if entry.actor.state != ActorLogicalState::Active
        || !activation.status.is_live()
        || activation.lease_expires_at <= now
        || !activation.matches_fence(fence)
    {
        return Err(ActorDirectoryError::StaleFence);
    }
    Ok(activation)
}

struct Mutation<T> {
    value: T,
    changed: bool,
}

impl<T> Mutation<T> {
    fn changed(value: T) -> Self {
        Self {
            value,
            changed: true,
        }
    }

    fn unchanged(value: T) -> Self {
        Self {
            value,
            changed: false,
        }
    }
}

impl SessionStoreV2 {
    async fn regular_actor_directory(path: &Path) -> Result<bool, ActorDirectoryError> {
        match fs::symlink_metadata(path).await {
            Ok(metadata) if metadata.file_type().is_dir() => Ok(true),
            Ok(_) => Err(ActorDirectoryError::Corrupt),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
            Err(error) => Err(storage(error)),
        }
    }

    async fn regular_actor_file(path: &Path) -> Result<bool, ActorDirectoryError> {
        match fs::symlink_metadata(path).await {
            Ok(metadata) if metadata.file_type().is_file() => Ok(true),
            Ok(_) => Err(ActorDirectoryError::Corrupt),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
            Err(error) => Err(storage(error)),
        }
    }

    /// Verify each path component before trusting an index hint. A missing
    /// main file may be a stale rebuildable index entry; a symlink is corrupt.
    async fn indexed_actor_rel_path(
        &self,
        actor_id: &str,
        rel: &str,
    ) -> Result<Option<String>, ActorDirectoryError> {
        let (kind, root_id) =
            Self::copy_source_identity_from_rel(actor_id, rel).map_err(storage)?;
        if !Self::regular_actor_directory(&self.sessions_dir).await?
            || !Self::regular_actor_directory(&self.sessions_dir.join(&root_id)).await?
        {
            return Ok(None);
        }
        if kind == bamboo_domain::SessionKind::Child
            && (!Self::regular_actor_directory(&self.sessions_dir.join(&root_id).join("children"))
                .await?
                || !Self::regular_actor_directory(&self.abs_path_from_rel(rel)).await?)
        {
            return Ok(None);
        }
        let main = self.abs_path_from_rel(rel).join("session.json");
        if !Self::regular_actor_file(&main).await? {
            return Ok(None);
        }
        Ok(Some(rel.to_string()))
    }

    async fn scan_actor_rel_path(&self, actor_id: &str) -> Result<String, ActorDirectoryError> {
        if !Self::regular_actor_directory(&self.sessions_dir).await? {
            return Err(ActorDirectoryError::NotFound(actor_id.to_string()));
        }
        let mut candidates = Vec::new();
        let root_rel = Self::root_rel_path(actor_id);
        if self
            .indexed_actor_rel_path(actor_id, &root_rel)
            .await?
            .is_some()
        {
            candidates.push(root_rel);
        }
        let mut roots = fs::read_dir(&self.sessions_dir).await.map_err(storage)?;
        while let Some(root) = roots.next_entry().await.map_err(storage)? {
            if !root.file_type().await.map_err(storage)?.is_dir() {
                continue;
            }
            let Some(root_id) = root.file_name().to_str().map(str::to_string) else {
                continue;
            };
            if validate_session_id(&root_id).is_err() {
                continue;
            }
            let child_rel = Self::child_rel_path(&root_id, actor_id);
            if self
                .indexed_actor_rel_path(actor_id, &child_rel)
                .await?
                .is_some()
            {
                candidates.push(child_rel);
                if candidates.len() > 1 {
                    return Err(ActorDirectoryError::Corrupt);
                }
            }
        }
        match candidates.pop() {
            Some(rel) => Ok(rel),
            None => Err(ActorDirectoryError::NotFound(actor_id.to_string())),
        }
    }

    /// Resolve every valid on-disk candidate while holding the actor's file
    /// lock. Cached and global indexes can each point to one of two physical
    /// Sessions with the same id; trusting either would split activation
    /// authority between Store instances. The scan rejects that ambiguity.
    pub(super) async fn actor_authority_location(
        &self,
        actor_id: &str,
    ) -> Result<(String, PathBuf), ActorDirectoryError> {
        validate_session_id(actor_id).map_err(storage)?;
        let rel = self.scan_actor_rel_path(actor_id).await?;
        let path = self.abs_path_from_rel(&rel).join(ACTOR_AUTHORITY_FILE);
        Ok((rel, path))
    }

    /// A Child's own Session file is insufficient authority: deleting a
    /// middle Child currently leaves its nested descendants on disk. Verify
    /// the complete parent chain, root identity, depth and Project before
    /// publishing or accepting any activation sidecar for the descendant.
    pub(super) async fn validate_actor_lineage(
        &self,
        actor: &ActorSession,
    ) -> Result<Vec<ActorAncestorObservation>, ActorDirectoryError> {
        self.validate_actor_lineage_with_record(actor, Some(actor))
            .await
    }

    pub(super) async fn validate_actor_lineage_with_record(
        &self,
        actor: &ActorSession,
        recorded: Option<&ActorSession>,
    ) -> Result<Vec<ActorAncestorObservation>, ActorDirectoryError> {
        self.validate_actor_lineage_view(actor, recorded, false)
            .await
    }

    pub(super) async fn validate_actor_control_lineage(
        &self,
        actor: &ActorSession,
    ) -> Result<Vec<ActorAncestorObservation>, ActorDirectoryError> {
        self.validate_actor_lineage_view(actor, Some(actor), true)
            .await
    }

    async fn validate_actor_lineage_view(
        &self,
        actor: &ActorSession,
        recorded: Option<&ActorSession>,
        control_only: bool,
    ) -> Result<Vec<ActorAncestorObservation>, ActorDirectoryError> {
        let own_rel = if actor.parent_actor_id.is_some() {
            Self::child_rel_path(&actor.root_actor_id, &actor.actor_id)
        } else {
            Self::root_rel_path(&actor.actor_id)
        };
        let own_kind = if actor.parent_actor_id.is_some() {
            bamboo_domain::SessionKind::Child
        } else {
            bamboo_domain::SessionKind::Root
        };
        let mut current_session = self
            .load_session_from_dir_strict_view(
                &self.abs_path_from_rel(&own_rel),
                &actor.actor_id,
                own_kind,
                &actor.root_actor_id,
                control_only,
            )
            .await
            .map_err(storage)?
            .ok_or_else(|| ActorDirectoryError::NotFound(actor.actor_id.clone()))?;
        if !actor.matches_session(&current_session) {
            return Err(ActorDirectoryError::InvalidIdentity);
        }
        let mut current = actor.clone();
        let mut lineage = Vec::new();
        while let Some(parent_id) = current.parent_actor_id.clone() {
            let root_id = &current.root_actor_id;
            let (expected_rel, kind) = if parent_id == *root_id {
                (
                    Self::root_rel_path(&parent_id),
                    bamboo_domain::SessionKind::Root,
                )
            } else {
                (
                    Self::child_rel_path(root_id, &parent_id),
                    bamboo_domain::SessionKind::Child,
                )
            };
            let actual_rel = self.scan_actor_rel_path(&parent_id).await?;
            if actual_rel != expected_rel {
                return Err(ActorDirectoryError::InvalidIdentity);
            }
            let parent = self
                .load_session_from_dir_strict_view(
                    &self.abs_path_from_rel(&expected_rel),
                    &parent_id,
                    kind,
                    root_id,
                    control_only,
                )
                .await
                .map_err(storage)?
                .ok_or_else(|| ActorDirectoryError::NotFound(parent_id.clone()))?;
            // Missing creation proof is readable, but never permits a first
            // activation. A legacy Actor already activated before this upgrade
            // may continue only against its original complete ancestor births.
            match current_session.parent_created_at {
                Some(birth) if birth == parent.created_at => {}
                None if recorded.is_some_and(|record| {
                    record.current_attempt > 0
                        && record
                            .ancestor_observations
                            .get(lineage.len())
                            .is_some_and(|old| {
                                old.actor_id == parent.id
                                    && old.session_created_at == parent.created_at
                            })
                }) => {}
                _ => return Err(ActorDirectoryError::InvalidIdentity),
            }
            current_session = parent;
            let parent = ActorSession::from_session(&current_session)?;
            if parent.root_actor_id != *root_id
                || parent.spawn_depth.checked_add(1) != Some(current.spawn_depth)
                || parent.project_id != current.project_id
                || parent.session_created_at > current.session_created_at
            {
                return Err(ActorDirectoryError::InvalidIdentity);
            }
            lineage.push(ActorAncestorObservation {
                actor_id: parent.actor_id.clone(),
                session_created_at: parent.session_created_at,
                metadata_version: parent.observed_metadata_version,
            });
            current = parent;
        }
        if current.actor_id != actor.root_actor_id || current.spawn_depth != 0 {
            return Err(ActorDirectoryError::InvalidIdentity);
        }
        Ok(lineage)
    }

    async fn read_or_create_actor_entry(
        &self,
        actor_id: &str,
        rel: &str,
        path: &Path,
        guards: &Arc<ActorAuthorityGuards>,
    ) -> Result<ActorDirectoryEntry, ActorDirectoryError> {
        let (kind, root_id) =
            Self::copy_source_identity_from_rel(actor_id, rel).map_err(storage)?;
        let directory = self.abs_path_from_rel(rel);
        let session = self
            .load_session_from_dir_strict(&directory, actor_id, kind, &root_id)
            .await
            .map_err(storage)?
            .ok_or_else(|| ActorDirectoryError::NotFound(actor_id.to_string()))?;
        if session.id != actor_id {
            return Err(ActorDirectoryError::InvalidIdentity);
        }
        let existing = if Self::regular_actor_file(path).await? {
            let raw = fs::read(path).await.map_err(storage)?;
            let entry: ActorDirectoryEntry =
                serde_json::from_slice(&raw).map_err(|_| ActorDirectoryError::Corrupt)?;
            entry.validate()?;
            if !entry.actor.matches_session(&session) {
                return Err(ActorDirectoryError::InvalidIdentity);
            }
            Some(entry)
        } else {
            None
        };
        let mut expected = ActorSession::from_session(&session)?;
        expected.ancestor_observations = self
            .validate_actor_lineage_with_record(
                &expected,
                existing.as_ref().map(|entry| &entry.actor),
            )
            .await?;
        let marker_path = directory.join(ACTOR_INITIALIZED_FILE);
        let marker = match Self::regular_actor_file(&marker_path).await? {
            true => {
                let bytes = fs::read(&marker_path).await.map_err(storage)?;
                let marker: ActorInitializedMarker =
                    serde_json::from_slice(&bytes).map_err(|_| ActorDirectoryError::Corrupt)?;
                if marker.schema_version != bamboo_domain::ACTOR_DIRECTORY_SCHEMA_VERSION
                    || marker.actor_id != actor_id
                    || marker.session_created_at != expected.session_created_at
                {
                    return Err(ActorDirectoryError::Corrupt);
                }
                Some(marker)
            }
            false => None,
        };
        let mut entry = match existing {
            Some(entry) => {
                if marker.is_none() {
                    // Only the fully inert first publication can survive a
                    // crash before marker durability. A prior claim without
                    // independent evidence must never be silently adopted.
                    if entry.actor.current_attempt != 0
                        || entry.actor.state != ActorLogicalState::Cold
                        || entry.activation.is_some()
                    {
                        return Err(ActorDirectoryError::Corrupt);
                    }
                    self.write_actor_marker(&marker_path, &expected, guards)
                        .await?;
                }
                entry
            }
            None if marker.is_none() => {
                // The Session was durably visible before this publication. A
                // crash before the marker leaves an inert Cold actor. No claim
                // is returned until BOTH files have been durably published.
                let entry = ActorDirectoryEntry::new(expected.clone());
                self.write_actor_entry(path, &entry, guards).await?;
                self.write_actor_marker(&marker_path, &expected, guards)
                    .await?;
                entry
            }
            None => return Err(ActorDirectoryError::Corrupt),
        };
        let project_changed = entry.actor.project_id != expected.project_id;
        if kind == bamboo_domain::SessionKind::Child && project_changed {
            // Unlike a Root, a saved Child cannot be rebound to another
            // Project after its identity was first published.
            return Err(ActorDirectoryError::InvalidIdentity);
        }
        let observed = entry.actor.observed_metadata_version;
        let current = expected.observed_metadata_version;
        if current < observed
            || entry.actor.ancestor_observations.len() != expected.ancestor_observations.len()
        {
            return Err(ActorDirectoryError::InvalidIdentity);
        }
        let mut lineage_changed = false;
        let mut lineage_gap = false;
        for (previous, latest) in entry
            .actor
            .ancestor_observations
            .iter()
            .zip(&expected.ancestor_observations)
        {
            if previous.actor_id != latest.actor_id
                || previous.session_created_at != latest.session_created_at
                || latest.metadata_version < previous.metadata_version
            {
                return Err(ActorDirectoryError::InvalidIdentity);
            }
            let delta = latest.metadata_version - previous.metadata_version;
            lineage_changed |= delta > 0;
            lineage_gap |= delta >= 2;
        }
        if entry.actor.state == ActorLogicalState::Active
            && (project_changed || current - observed >= 2 || lineage_gap)
        {
            // A same-Project gap of two revisions could conceal an A→B→A
            // rebind in this Actor or any ancestor. One unseen revision
            // cannot conceal that round trip when save boundaries enforce
            // version increments for Project changes.
            return Err(ActorDirectoryError::ProjectTransitionBlocked);
        }
        if project_changed || current != observed || lineage_changed {
            entry.actor.project_id = expected.project_id;
            entry.actor.observed_metadata_version = current;
            entry.actor.ancestor_observations = expected.ancestor_observations;
            entry.revision = checked_next(entry.revision)?;
            self.write_actor_entry(path, &entry, guards).await?;
        }
        Ok(entry)
    }

    async fn write_actor_marker(
        &self,
        path: &Path,
        actor: &ActorSession,
        guards: &Arc<ActorAuthorityGuards>,
    ) -> Result<(), ActorDirectoryError> {
        let marker = ActorInitializedMarker {
            schema_version: bamboo_domain::ACTOR_DIRECTORY_SCHEMA_VERSION,
            actor_id: actor.actor_id.clone(),
            session_created_at: actor.session_created_at,
        };
        let bytes = serde_json::to_vec(&marker).map_err(|_| ActorDirectoryError::Corrupt)?;
        self.write_actor_bytes(path, bytes, guards).await
    }

    async fn write_actor_entry(
        &self,
        path: &Path,
        entry: &ActorDirectoryEntry,
        guards: &Arc<ActorAuthorityGuards>,
    ) -> Result<(), ActorDirectoryError> {
        entry.validate()?;
        let bytes = serde_json::to_vec_pretty(entry).map_err(|_| ActorDirectoryError::Corrupt)?;
        self.write_actor_bytes(path, bytes, guards).await
    }

    async fn write_actor_bytes(
        &self,
        path: &Path,
        bytes: Vec<u8>,
        guards: &Arc<ActorAuthorityGuards>,
    ) -> Result<(), ActorDirectoryError> {
        if !guards
            .tree_bumped
            .load(std::sync::atomic::Ordering::Acquire)
        {
            let root = guards
                .tree_root
                .lock()
                .expect("Actor tree Root")
                .clone()
                .ok_or(ActorDirectoryError::Corrupt)?;
            self.bump_actor_tree_revision(&root)
                .await
                .map_err(storage)?;
            guards
                .tree_bumped
                .store(true, std::sync::atomic::Ordering::Release);
        }
        let path = path.to_path_buf();
        let guards = Arc::clone(guards);
        #[cfg(test)]
        let hook = self.actor_write_hook.lock().unwrap().clone();
        #[cfg(test)]
        let transcript_hook = self.transcript_write_hook.lock().unwrap().clone();
        tokio::task::spawn_blocking(move || {
            let _guards = guards;
            durable_atomic_write_blocking(&path, &bytes, |phase| {
                #[cfg(test)]
                if let Some(hook) = &hook {
                    return hook.visit(&path, phase);
                }
                #[cfg(test)]
                if let Some(hook) = &transcript_hook {
                    hook.visit(phase)?;
                }
                let _ = phase;
                Ok(())
            })
        })
        .await
        .map_err(|error| storage(io::Error::other(format!("join actor write: {error}"))))?
        .map_err(storage)
    }

    async fn actor_transaction<T, F>(
        &self,
        actor_id: &str,
        operation: F,
    ) -> Result<T, ActorDirectoryError>
    where
        F: FnOnce(&mut ActorDirectoryEntry) -> Result<Mutation<T>, ActorDirectoryError> + Send,
        T: Send,
    {
        // Same lock order as strict Session control-plane writes: lifecycle,
        // Task sidecar, then the exact Session maintenance/file lock. The last
        // lock spans read/CAS/durable rename, including independent processes.
        let lifecycle = self
            .lock_session_lifecycle_shared()
            .await
            .map_err(storage)?;
        let task = self
            .lock_runtime_task_sidecar_shared()
            .await
            .map_err(storage)?;
        let session = self
            .acquire_session_maintenance_lock(actor_id)
            .await
            .map_err(storage)?;
        let guards = Arc::new(ActorAuthorityGuards {
            _tree: std::sync::Mutex::new(None),
            tree_root: std::sync::Mutex::new(None),
            tree_bumped: std::sync::atomic::AtomicBool::new(false),
            _session: session,
            _task: task,
            _lifecycle: lifecycle,
        });
        let (rel, path) = self.actor_authority_location(actor_id).await?;
        let (_, root_id) = Self::copy_source_identity_from_rel(actor_id, &rel).map_err(storage)?;
        let tree = self
            .acquire_actor_tree_write_guard(&root_id)
            .await
            .map_err(storage)?;
        *guards._tree.lock().expect("Actor tree writer guard") = Some(tree);
        let root = self
            .canonical_actor_tree_root(&root_id)
            .await
            .map_err(storage)?;
        *guards.tree_root.lock().expect("Actor tree Root") = Some(root);
        let mut entry = self
            .read_or_create_actor_entry(actor_id, &rel, &path, &guards)
            .await?;
        let Mutation { value, changed } = operation(&mut entry)?;
        if changed {
            entry.revision = checked_next(entry.revision)?;
            self.write_actor_entry(&path, &entry, &guards).await?;
        }
        Ok(value)
    }

    /// The caller owns lifecycle/Task exclusivity and this Root's tree guard.
    /// Cancel only already-published live descendants; never initialize an Actor.
    /// A cancelled attempt remains recorded so same-birth ancestor restoration
    /// can permit a fresh claim without ever making the old fence live again.
    pub(super) async fn cancel_descendant_activations_before_child_delete(
        &self,
        root_id: &str,
        child_id: &str,
        guards: &Arc<super::SessionDeletionGuards>,
        tree: &Arc<ActorTreeWriteGuard>,
    ) -> io::Result<()> {
        let directory = self.sessions_dir.join(root_id).join("children");
        let root_id = root_id.to_owned();
        let child_id = child_id.to_owned();
        let guards = Arc::clone(guards);
        let tree = Arc::clone(tree);
        #[cfg(test)]
        let hook = self.actor_write_hook.lock().unwrap().clone();
        tokio::task::spawn_blocking(move || {
            // The original acquired guards cover the actual scan and every
            // durable row replacement, including caller/runtime cancellation.
            let _guards = guards;
            let _tree = tree;
            let invalid = || {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid descendant Actor authority during Child deletion",
                )
            };
            match std::fs::symlink_metadata(&directory) {
                Ok(metadata) if metadata.file_type().is_dir() => {}
                Ok(_) => return Err(invalid()),
                Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
                Err(error) => return Err(error),
            }
            let entries = std::fs::read_dir(&directory)?;
            let read = |path: &Path| -> io::Result<Option<Vec<u8>>> {
                match std::fs::symlink_metadata(path) {
                    Ok(metadata) if metadata.file_type().is_file() => std::fs::read(path).map(Some),
                    Ok(_) => Err(invalid()),
                    Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
                    Err(error) => Err(error),
                }
            };
            let now = Utc::now();
            let mut replacements = Vec::new();
            // Preflight the complete same-Root census before changing any row.
            // The persisted ancestor list covers indirect descendants too.
            for item in entries {
                let item = item?;
                if !item.file_type()?.is_dir() || item.file_name() == child_id.as_str() {
                    continue;
                }
                let path = item.path().join(ACTOR_AUTHORITY_FILE);
                let marker = read(&item.path().join(ACTOR_INITIALIZED_FILE))?;
                let row = read(&path)?;
                let Some(row) = row else {
                    // Two absent witnesses are ordinary historical Sessions.
                    if marker.is_some() {
                        return Err(invalid());
                    }
                    continue;
                };
                let mut entry: ActorDirectoryEntry =
                    serde_json::from_slice(&row).map_err(|_| invalid())?;
                entry.validate().map_err(|_| invalid())?;
                if item.file_name() != entry.actor.actor_id.as_str()
                    || entry.actor.root_actor_id != root_id
                    || entry.actor.parent_actor_id.is_none()
                {
                    return Err(invalid());
                }
                let Some(marker) = marker else {
                    // Reuse the first-publication crash rule: an inert Cold
                    // row has never issued a fence and needs no cancellation.
                    if entry.actor.current_attempt == 0
                        && entry.actor.state == ActorLogicalState::Cold
                        && entry.activation.is_none()
                    {
                        continue;
                    }
                    return Err(invalid());
                };
                let marker: ActorInitializedMarker =
                    serde_json::from_slice(&marker).map_err(|_| invalid())?;
                if marker.schema_version != bamboo_domain::ACTOR_DIRECTORY_SCHEMA_VERSION
                    || marker.actor_id != entry.actor.actor_id
                    || marker.session_created_at != entry.actor.session_created_at
                {
                    return Err(invalid());
                }
                if !entry
                    .actor
                    .ancestor_observations
                    .iter()
                    .any(|ancestor| ancestor.actor_id == child_id)
                {
                    continue;
                }
                let Some(activation) = entry
                    .activation
                    .as_mut()
                    .filter(|activation| activation.status.is_live())
                else {
                    continue;
                };
                activation.lease_epoch =
                    checked_next(activation.lease_epoch).map_err(|_| invalid())?;
                activation.status = ActorActivationStatus::Cancelled;
                activation.finished_at = Some(now);
                activation.lease_expires_at = now;
                entry.actor.state = ActorLogicalState::Cold;
                entry.revision = checked_next(entry.revision).map_err(|_| invalid())?;
                entry.validate().map_err(|_| invalid())?;
                let bytes = serde_json::to_vec_pretty(&entry).map_err(|_| invalid())?;
                replacements.push((path, bytes));
            }
            replacements.sort_by(|left, right| left.0.cmp(&right.0));
            for (path, bytes) in replacements {
                durable_atomic_write_blocking(&path, &bytes, |phase| {
                    #[cfg(test)]
                    if let Some(hook) = &hook {
                        return hook.visit(&path, phase);
                    }
                    let _ = phase;
                    Ok(())
                })?;
            }
            Ok(())
        })
        .await
        .map_err(|error| io::Error::other(format!("join descendant Actor cancellation: {error}")))?
    }

    /// Retire a resident only while its exact physical activation is still
    /// the Directory owner. A delayed launcher/renewal cleanup may run after
    /// expiry and replacement; it must not retire that successor by ActorId.
    pub async fn retire_actor_if_activation(
        &self,
        fence: &ActorActivationFence,
        now: DateTime<Utc>,
    ) -> Result<bool, ActorDirectoryError> {
        self.actor_transaction(&fence.actor_id, |entry| {
            if entry.actor.state == ActorLogicalState::Retired
                || !entry
                    .activation
                    .as_ref()
                    .is_some_and(|activation| activation.matches_fence(fence))
            {
                return Ok(Mutation::unchanged(false));
            }
            if let Some(activation) = entry.activation.as_mut() {
                if activation.status.is_live() {
                    activation.lease_epoch = checked_next(activation.lease_epoch)?;
                    activation.status = ActorActivationStatus::Cancelled;
                    activation.finished_at = Some(now);
                    activation.lease_expires_at = now;
                }
            }
            entry.actor.state = ActorLogicalState::Retired;
            Ok(Mutation::changed(true))
        })
        .await
    }
}

#[async_trait]
impl ActorDirectoryPort for SessionStoreV2 {
    async fn ensure_actor(
        &self,
        actor_id: &str,
    ) -> Result<ActorDirectoryEntry, ActorDirectoryError> {
        self.actor_transaction(actor_id, |entry| Ok(Mutation::unchanged(entry.clone())))
            .await
    }

    async fn inspect_actor(
        &self,
        actor_id: &str,
    ) -> Result<ActorDirectoryEntry, ActorDirectoryError> {
        self.ensure_actor(actor_id).await
    }

    async fn bind_control_plane(
        &self,
        actor_id: &str,
        binding: ActorControlPlaneBinding,
    ) -> Result<ActorDirectoryEntry, ActorDirectoryError> {
        if binding
            .placement_intent
            .as_ref()
            .is_some_and(|intent| !intent.is_valid())
        {
            return Err(ActorDirectoryError::InvalidTransition);
        }
        let ActorControlPlaneBinding {
            policy_revision,
            placement_intent,
        } = binding;
        self.actor_transaction(actor_id, |entry| {
            let policy_changed = policy_revision
                .is_some_and(|revision| entry.actor.policy_revision != Some(revision));
            let placement_changed = placement_intent
                .as_ref()
                .is_some_and(|intent| entry.actor.placement_intent.as_ref() != Some(intent));
            if !policy_changed && !placement_changed {
                return Ok(Mutation::unchanged(entry.clone()));
            }
            if placement_changed && entry.actor.placement_intent.is_some() {
                return Err(ActorDirectoryError::PlacementIntentConflict);
            }
            if policy_changed
                && entry.actor.policy_revision.is_some_and(|previous| {
                    policy_revision.is_none_or(|revision| revision <= previous)
                })
            {
                return Err(ActorDirectoryError::PolicyTransitionBlocked);
            }
            if matches!(
                entry.actor.state,
                ActorLogicalState::Active | ActorLogicalState::Retired
            ) {
                return Err(if policy_changed {
                    ActorDirectoryError::PolicyTransitionBlocked
                } else {
                    ActorDirectoryError::PlacementIntentConflict
                });
            }
            if let Some(revision) = policy_revision {
                entry.actor.policy_revision = Some(revision);
            }
            if let Some(intent) = placement_intent {
                entry.actor.placement_intent = Some(intent);
            }
            let mut returned = entry.clone();
            returned.revision = checked_next(entry.revision)?;
            Ok(Mutation::changed(returned))
        })
        .await
    }

    async fn claim_activation(
        &self,
        claim: &ActorActivationClaim,
    ) -> Result<ActorActivation, ActorDirectoryError> {
        if claim.run_id.trim().is_empty()
            || claim.lease_owner.trim().is_empty()
            || claim.lease_expires_at <= claim.now
        {
            return Err(ActorDirectoryError::InvalidTransition);
        }
        self.actor_transaction(&claim.actor_id, |entry| {
            if entry.actor.state == ActorLogicalState::Retired {
                return Err(ActorDirectoryError::InvalidTransition);
            }
            if let Some(active) = entry.activation.as_ref() {
                if active.status.is_live() && active.lease_expires_at > claim.now {
                    if active.run_id == claim.run_id
                        && active.lease_owner == claim.lease_owner
                        && active.lease_expires_at == claim.lease_expires_at
                        && active.inbox_generation == claim.inbox_generation
                        && active.placement_ref == claim.placement_ref
                    {
                        return Ok(Mutation::unchanged(active.clone()));
                    }
                    return Err(ActorDirectoryError::Busy);
                }
            }
            let attempt = checked_next(entry.actor.current_attempt)?;
            let lease_epoch = checked_next(
                entry
                    .activation
                    .as_ref()
                    .map_or(0, |previous| previous.lease_epoch),
            )?;
            let activation = ActorActivation {
                schema_version: bamboo_domain::ACTOR_DIRECTORY_SCHEMA_VERSION,
                actor_id: entry.actor.actor_id.clone(),
                activation_id: Uuid::new_v4().to_string(),
                attempt,
                run_id: claim.run_id.clone(),
                lease_owner: claim.lease_owner.clone(),
                lease_epoch,
                lease_expires_at: claim.lease_expires_at,
                project_id: entry.actor.project_id.clone(),
                inbox_generation: claim.inbox_generation,
                placement_ref: claim.placement_ref.clone(),
                status: ActorActivationStatus::Reserved,
                checkpoint_revision: 0,
                started_at: None,
                finished_at: None,
            };
            entry.actor.current_attempt = attempt;
            entry.actor.state = ActorLogicalState::Active;
            entry.activation = Some(activation.clone());
            Ok(Mutation::changed(activation))
        })
        .await
    }

    async fn start_activation(
        &self,
        fence: &ActorActivationFence,
        now: DateTime<Utc>,
    ) -> Result<ActorActivation, ActorDirectoryError> {
        self.actor_transaction(&fence.actor_id, |entry| {
            let status = current_live(entry, fence, now)?.status;
            let activation = entry
                .activation
                .as_mut()
                .ok_or(ActorDirectoryError::StaleFence)?;
            if status == ActorActivationStatus::Running {
                return Ok(Mutation::unchanged(activation.clone()));
            }
            activation.status = ActorActivationStatus::Running;
            activation.started_at = Some(now);
            Ok(Mutation::changed(activation.clone()))
        })
        .await
    }

    async fn renew_activation(
        &self,
        fence: &ActorActivationFence,
        now: DateTime<Utc>,
        lease_expires_at: DateTime<Utc>,
    ) -> Result<ActorActivation, ActorDirectoryError> {
        self.actor_transaction(&fence.actor_id, |entry| {
            let old_expiry = current_live(entry, fence, now)?.lease_expires_at;
            if lease_expires_at <= old_expiry {
                return Err(ActorDirectoryError::InvalidTransition);
            }
            let activation = entry
                .activation
                .as_mut()
                .ok_or(ActorDirectoryError::StaleFence)?;
            activation.lease_expires_at = lease_expires_at;
            Ok(Mutation::changed(activation.clone()))
        })
        .await
    }

    async fn checkpoint_activation(
        &self,
        fence: &ActorActivationFence,
        now: DateTime<Utc>,
        expected_checkpoint_revision: u64,
    ) -> Result<ActorActivation, ActorDirectoryError> {
        self.actor_transaction(&fence.actor_id, |entry| {
            let active = current_live(entry, fence, now)?;
            if active.status != ActorActivationStatus::Running {
                return Err(ActorDirectoryError::InvalidTransition);
            }
            if active.checkpoint_revision != expected_checkpoint_revision {
                return Err(ActorDirectoryError::StaleFence);
            }
            let next = checked_next(expected_checkpoint_revision)?;
            let activation = entry
                .activation
                .as_mut()
                .ok_or(ActorDirectoryError::StaleFence)?;
            activation.checkpoint_revision = next;
            Ok(Mutation::changed(activation.clone()))
        })
        .await
    }

    async fn finish_activation(
        &self,
        fence: &ActorActivationFence,
        now: DateTime<Utc>,
        outcome: ActorActivationFinish,
    ) -> Result<ActorActivation, ActorDirectoryError> {
        self.actor_transaction(&fence.actor_id, |entry| {
            let current_status = current_live(entry, fence, now)?.status;
            if outcome == ActorActivationFinish::Succeeded
                && current_status != ActorActivationStatus::Running
            {
                return Err(ActorDirectoryError::InvalidTransition);
            }
            let activation = entry
                .activation
                .as_mut()
                .ok_or(ActorDirectoryError::StaleFence)?;
            activation.status = match outcome {
                ActorActivationFinish::Succeeded => ActorActivationStatus::Succeeded,
                ActorActivationFinish::Failed => ActorActivationStatus::Failed,
                ActorActivationFinish::Cancelled => ActorActivationStatus::Cancelled,
            };
            activation.finished_at = Some(now);
            entry.actor.state = if outcome == ActorActivationFinish::Failed {
                ActorLogicalState::Failed
            } else {
                ActorLogicalState::Cold
            };
            Ok(Mutation::changed(activation.clone()))
        })
        .await
    }

    async fn retire_actor(
        &self,
        actor_id: &str,
        now: DateTime<Utc>,
    ) -> Result<ActorDirectoryEntry, ActorDirectoryError> {
        self.actor_transaction(actor_id, |entry| {
            if entry.actor.state == ActorLogicalState::Retired {
                return Ok(Mutation::unchanged(entry.clone()));
            }
            if let Some(activation) = entry.activation.as_mut() {
                if activation.status.is_live() {
                    activation.lease_epoch = checked_next(activation.lease_epoch)?;
                    activation.status = ActorActivationStatus::Cancelled;
                    activation.finished_at = Some(now);
                    activation.lease_expires_at = now;
                }
            }
            entry.actor.state = ActorLogicalState::Retired;
            // The returned snapshot reflects the new persisted revision.
            let mut returned = entry.clone();
            returned.revision = checked_next(entry.revision)?;
            Ok(Mutation::changed(returned))
        })
        .await
    }

    async fn validate_fence(
        &self,
        fence: &ActorActivationFence,
        now: DateTime<Utc>,
    ) -> Result<(), ActorDirectoryError> {
        self.actor_transaction(&fence.actor_id, |entry| {
            current_live(entry, fence, now)?;
            Ok(Mutation::unchanged(()))
        })
        .await
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use bamboo_domain::{
        record_permission_audit, resolve_permission_mode, ActorControlPlaneBinding,
        ActorDirectoryPort, ActorPlacementClass, ActorPlacementIntent, ActorPlacementRef,
        PermissionAuditSeed, PermissionMode, Session, SessionPermissionMode, Storage,
    };
    use chrono::{Duration, Utc};

    use super::*;

    fn claim(
        actor_id: &str,
        run_id: &str,
        owner: &str,
        now: DateTime<Utc>,
    ) -> ActorActivationClaim {
        ActorActivationClaim {
            actor_id: actor_id.into(),
            run_id: run_id.into(),
            lease_owner: owner.into(),
            lease_expires_at: now + Duration::minutes(5),
            inbox_generation: 7,
            placement_ref: Some(ActorPlacementRef {
                class: ActorPlacementClass::Local,
                lease_id: "local-lease".into(),
                slot_epoch: None,
            }),
            now,
        }
    }

    fn stamp_policy(session: &mut Session, policy_revision: u64) {
        record_permission_audit(
            &mut session.metadata,
            &PermissionAuditSeed::bamboo_runtime(
                policy_revision,
                resolve_permission_mode(SessionPermissionMode::Default, PermissionMode::Default),
            ),
            None,
        )
        .unwrap();
    }

    #[tokio::test]
    async fn host_policy_and_intent_survive_reassignment_and_physical_replacement(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("actor-control-plane", "model");
        stamp_policy(&mut root, 7);
        store.save_session(&root).await?;
        let cold = store.ensure_actor(&root.id).await?;
        // Even a complete saved audit is not by itself proof that its revision
        // came from the Host's effective configuration.
        assert_eq!(cold.actor.policy_revision, None);
        assert_eq!(cold.actor.placement_intent, None);

        let intent = ActorPlacementIntent::Pool {
            pool_id: "workers".into(),
        };
        let binding = ActorControlPlaneBinding {
            policy_revision: Some(7),
            placement_intent: Some(intent.clone()),
        };
        let bound = store.bind_control_plane(&root.id, binding.clone()).await?;
        assert_eq!(bound.actor.policy_revision, Some(7));
        assert_eq!(bound.actor.placement_intent, Some(intent.clone()));
        assert_eq!(
            store.bind_control_plane(&root.id, binding).await?.revision,
            bound.revision
        );
        let now = Utc::now();
        let activation = store
            .claim_activation(&claim(&root.id, "run-1", "host-a", now))
            .await?;
        assert_eq!(
            activation.placement_ref.as_ref().unwrap().class,
            ActorPlacementClass::Local
        );
        assert_eq!(
            store.inspect_actor(&root.id).await?.actor.placement_intent,
            Some(intent.clone())
        );
        store.start_activation(&activation.fence(), now).await?;
        store
            .finish_activation(
                &activation.fence(),
                now + Duration::seconds(1),
                ActorActivationFinish::Succeeded,
            )
            .await?;

        root.set_project_id_meta("another-project");
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        let reopened = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let after = reopened.inspect_actor(&root.id).await?;
        assert_eq!(after.actor.project_id.as_deref(), Some("another-project"));
        assert_eq!(after.actor.policy_revision, Some(7));
        assert_eq!(after.actor.placement_intent, Some(intent));
        let sidecar = home
            .path()
            .join("sessions/actor-control-plane/actor-authority.json");
        let before_conflict = fs::read(&sidecar).await?;
        assert_eq!(
            reopened
                .bind_control_plane(
                    &root.id,
                    ActorControlPlaneBinding {
                        policy_revision: None,
                        placement_intent: Some(ActorPlacementIntent::Local),
                    }
                )
                .await
                .unwrap_err(),
            ActorDirectoryError::PlacementIntentConflict
        );
        assert_eq!(fs::read(&sidecar).await?, before_conflict);
        let advanced = reopened
            .bind_control_plane(
                &root.id,
                ActorControlPlaneBinding {
                    policy_revision: Some(8),
                    placement_intent: None,
                },
            )
            .await?;
        assert_eq!(advanced.actor.policy_revision, Some(8));
        assert_eq!(
            advanced.actor.placement_intent,
            after.actor.placement_intent
        );
        Ok(())
    }

    #[tokio::test]
    async fn only_host_binding_sets_policy_and_live_or_regressive_changes_are_rejected(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("policy-refresh", "model");
        stamp_policy(&mut root, 99);
        root.metadata.insert(
            "placement".into(),
            r#"{"kind":"remote","host":"other"}"#.into(),
        );
        store.save_session(&root).await?;
        assert_eq!(
            store.ensure_actor(&root.id).await?.actor.policy_revision,
            None
        );
        assert_eq!(
            store.inspect_actor(&root.id).await?.actor.placement_intent,
            None
        );

        let now = Utc::now();
        let active = store
            .claim_activation(&claim(&root.id, "run", "host", now))
            .await?;
        let sidecar = home
            .path()
            .join("sessions/policy-refresh/actor-authority.json");
        let before_conflict = fs::read(&sidecar).await?;
        assert_eq!(
            store.inspect_actor(&root.id).await?.actor.policy_revision,
            None
        );
        assert_eq!(
            store
                .bind_control_plane(
                    &root.id,
                    ActorControlPlaneBinding {
                        policy_revision: Some(4),
                        placement_intent: None,
                    }
                )
                .await
                .unwrap_err(),
            ActorDirectoryError::PolicyTransitionBlocked
        );
        assert_eq!(fs::read(&sidecar).await?, before_conflict);
        store.validate_fence(&active.fence(), now).await?;
        store.start_activation(&active.fence(), now).await?;
        store
            .finish_activation(
                &active.fence(),
                now + Duration::seconds(1),
                ActorActivationFinish::Succeeded,
            )
            .await?;
        let bound = store
            .bind_control_plane(
                &root.id,
                ActorControlPlaneBinding {
                    policy_revision: Some(4),
                    placement_intent: None,
                },
            )
            .await?;
        assert_eq!(bound.actor.policy_revision, Some(4));
        assert_eq!(bound.actor.placement_intent, None);

        stamp_policy(&mut root, 1000);
        store.save_runtime_state(&root).await?;
        assert_eq!(
            store.inspect_actor(&root.id).await?.actor.policy_revision,
            Some(4)
        );
        let before_conflict = fs::read(&sidecar).await?;
        assert_eq!(
            store
                .bind_control_plane(
                    &root.id,
                    ActorControlPlaneBinding {
                        policy_revision: Some(3),
                        placement_intent: None,
                    }
                )
                .await
                .unwrap_err(),
            ActorDirectoryError::PolicyTransitionBlocked
        );
        assert_eq!(fs::read(&sidecar).await?, before_conflict);
        Ok(())
    }

    #[tokio::test]
    async fn persisted_session_precedes_claim_and_attempt_survives_restart(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let now = Utc::now();
        assert_eq!(
            store
                .claim_activation(&claim("actor-root", "run-1", "host-a", now))
                .await
                .unwrap_err(),
            ActorDirectoryError::NotFound("actor-root".into())
        );
        assert!(!home.path().join("sessions/actor-root").exists());

        let root = Session::new("actor-root", "model");
        store.save_session(&root).await?;
        let cold = store.ensure_actor("actor-root").await?;
        assert_eq!(cold.actor.actor_id, root.id);
        assert_eq!(cold.actor.root_actor_id, root.id);
        assert_eq!(cold.actor.current_attempt, 0);
        assert!(home
            .path()
            .join("sessions/actor-root/actor-authority.json")
            .is_file());

        let first = store
            .claim_activation(&claim("actor-root", "run-1", "host-a", now))
            .await?;
        assert_eq!(first.attempt, 1);
        assert_eq!(first.lease_epoch, 1);
        assert_eq!(first.status, ActorActivationStatus::Reserved);
        assert_eq!(
            store
                .claim_activation(&claim("actor-root", "run-1", "host-a", now))
                .await?,
            first
        );
        assert_eq!(
            store
                .claim_activation(&claim("actor-root", "other-run", "host-b", now))
                .await
                .unwrap_err(),
            ActorDirectoryError::Busy
        );
        assert_eq!(
            store
                .finish_activation(
                    &first.fence(),
                    now + Duration::seconds(1),
                    ActorActivationFinish::Succeeded,
                )
                .await
                .unwrap_err(),
            ActorDirectoryError::InvalidTransition
        );
        let reopened = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let recovered = reopened.inspect_actor("actor-root").await?;
        assert_eq!(recovered.activation.as_ref(), Some(&first));

        let started = reopened
            .start_activation(&first.fence(), now + Duration::seconds(1))
            .await?;
        assert_eq!(started.status, ActorActivationStatus::Running);
        let renewed = reopened
            .renew_activation(
                &first.fence(),
                now + Duration::seconds(2),
                first.lease_expires_at + Duration::minutes(1),
            )
            .await?;
        assert_eq!(renewed.fence(), first.fence());
        assert!(renewed.lease_expires_at > first.lease_expires_at);
        let checkpoint = reopened
            .checkpoint_activation(&first.fence(), now + Duration::seconds(2), 0)
            .await?;
        assert_eq!(checkpoint.checkpoint_revision, 1);
        assert_eq!(
            reopened
                .checkpoint_activation(&first.fence(), now + Duration::seconds(3), 0)
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );
        reopened
            .finish_activation(
                &first.fence(),
                now + Duration::seconds(4),
                ActorActivationFinish::Succeeded,
            )
            .await?;
        assert_eq!(
            reopened
                .validate_fence(&first.fence(), now + Duration::seconds(5))
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );

        let retried = reopened
            .claim_activation(&claim(
                "actor-root",
                "run-2",
                "host-b",
                now + Duration::seconds(6),
            ))
            .await?;
        assert_eq!(retried.actor_id, first.actor_id);
        assert_eq!(retried.attempt, 2);
        assert_eq!(retried.lease_epoch, 2);
        assert_ne!(retried.activation_id, first.activation_id);
        assert_eq!(
            reopened
                .start_activation(&first.fence(), now + Duration::seconds(7))
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );
        Ok(())
    }

    #[tokio::test]
    async fn independent_stores_serialize_competing_owners(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let first = Arc::new(SessionStoreV2::new(home.path().to_path_buf()).await?);
        first
            .save_session(&Session::new("contended", "model"))
            .await?;
        let second = Arc::new(SessionStoreV2::new(home.path().to_path_buf()).await?);
        let now = Utc::now();
        let a = claim("contended", "run-a", "host-a", now);
        let b = claim("contended", "run-b", "host-b", now);
        let (left, right) = tokio::join!(first.claim_activation(&a), second.claim_activation(&b));
        let winners = usize::from(left.is_ok()) + usize::from(right.is_ok());
        assert_eq!(winners, 1);
        assert!(
            matches!(left, Err(ActorDirectoryError::Busy))
                || matches!(right, Err(ActorDirectoryError::Busy))
        );
        let recovered = second.inspect_actor("contended").await?;
        assert_eq!(recovered.actor.current_attempt, 1);
        assert_eq!(
            recovered.activation.unwrap().status,
            ActorActivationStatus::Reserved
        );
        Ok(())
    }

    #[tokio::test]
    async fn expired_owner_cannot_checkpoint_or_finish_new_attempt(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        store
            .save_session(&Session::new("expired", "model"))
            .await?;
        let now = Utc::now();
        let old = store
            .claim_activation(&claim("expired", "run-old", "host-old", now))
            .await?;
        let after_expiry = now + Duration::minutes(6);
        let next = store
            .claim_activation(&claim("expired", "run-next", "host-next", after_expiry))
            .await?;
        assert_eq!(next.attempt, old.attempt + 1);
        assert_eq!(next.lease_epoch, old.lease_epoch + 1);
        assert_eq!(
            store
                .finish_activation(&old.fence(), after_expiry, ActorActivationFinish::Failed)
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );
        assert_eq!(
            store
                .checkpoint_activation(&old.fence(), after_expiry, 0)
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );
        assert_eq!(
            store
                .validate_fence(&old.fence(), after_expiry)
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );
        Ok(())
    }

    #[tokio::test]
    async fn delayed_resident_cleanup_cannot_retire_replacement_activation(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let old_store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        old_store
            .save_session(&Session::new("resident-replacement", "model"))
            .await?;
        let now = Utc::now();
        let old = old_store
            .claim_activation(&claim("resident-replacement", "old", "old-host", now))
            .await?;
        old_store.start_activation(&old.fence(), now).await?;

        let replacement_store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let after_expiry = now + Duration::minutes(6);
        let replacement = replacement_store
            .claim_activation(&claim(
                "resident-replacement",
                "replacement",
                "new-host",
                after_expiry,
            ))
            .await?;
        replacement_store
            .start_activation(&replacement.fence(), after_expiry)
            .await?;

        assert!(
            !old_store
                .retire_actor_if_activation(&old.fence(), after_expiry)
                .await?
        );
        let current = old_store.inspect_actor("resident-replacement").await?;
        assert_eq!(current.actor.state, ActorLogicalState::Active);
        assert_eq!(current.activation.unwrap().fence(), replacement.fence());
        replacement_store
            .validate_fence(&replacement.fence(), after_expiry)
            .await?;

        assert!(
            old_store
                .retire_actor_if_activation(&replacement.fence(), after_expiry)
                .await?
        );
        let retired = replacement_store
            .inspect_actor("resident-replacement")
            .await?;
        assert_eq!(retired.actor.state, ActorLogicalState::Retired);
        assert_eq!(
            retired.activation.unwrap().status,
            ActorActivationStatus::Cancelled
        );
        Ok(())
    }

    #[tokio::test]
    async fn retirement_fences_owner_and_preserves_identity(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let root = Session::new("tree-root", "model");
        let child = Session::new_child_of("tree-child", &root, "model", "Child");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        let now = Utc::now();
        let active = store
            .claim_activation(&claim("tree-child", "child-run", "host-a", now))
            .await?;
        let retired = store
            .retire_actor("tree-child", now + Duration::seconds(1))
            .await?;
        assert_eq!(retired.actor.actor_id, child.id);
        assert_eq!(
            retired.actor.parent_actor_id.as_deref(),
            Some(root.id.as_str())
        );
        assert_eq!(retired.actor.root_actor_id, root.id);
        assert_eq!(retired.actor.state, ActorLogicalState::Retired);
        assert_eq!(
            retired.activation.as_ref().unwrap().status,
            ActorActivationStatus::Cancelled
        );
        assert_eq!(
            store
                .validate_fence(&active.fence(), now + Duration::seconds(1))
                .await
                .unwrap_err(),
            ActorDirectoryError::StaleFence
        );
        assert_eq!(
            store
                .claim_activation(&claim(
                    "tree-child",
                    "later",
                    "host-b",
                    now + Duration::seconds(2)
                ))
                .await
                .unwrap_err(),
            ActorDirectoryError::InvalidTransition
        );
        let reopened = SessionStoreV2::new(home.path().to_path_buf()).await?;
        assert_eq!(reopened.inspect_actor("tree-child").await?, retired);
        assert!(reopened.load_session("tree-child").await?.is_some());
        Ok(())
    }

    #[tokio::test]
    async fn corrupt_or_mismatched_authority_fails_closed_without_repair(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        store
            .save_session(&Session::new("damaged", "model"))
            .await?;
        let entry = store.ensure_actor("damaged").await?;
        let path = home.path().join("sessions/damaged/actor-authority.json");

        fs::write(&path, b"{invalid").await?;
        assert_eq!(
            store.inspect_actor("damaged").await.unwrap_err(),
            ActorDirectoryError::Corrupt
        );
        assert_eq!(fs::read(&path).await?, b"{invalid");

        let mut wrong_version = entry.clone();
        wrong_version.schema_version += 1;
        fs::write(&path, serde_json::to_vec(&wrong_version)?).await?;
        assert_eq!(
            store.inspect_actor("damaged").await.unwrap_err(),
            ActorDirectoryError::Corrupt
        );

        let mut wrong_identity = entry;
        wrong_identity.actor.session_created_at += Duration::seconds(1);
        fs::write(&path, serde_json::to_vec(&wrong_identity)?).await?;
        assert_eq!(
            store.inspect_actor("damaged").await.unwrap_err(),
            ActorDirectoryError::InvalidIdentity
        );
        assert_eq!(
            store
                .claim_activation(&claim("damaged", "run", "host", Utc::now()))
                .await
                .unwrap_err(),
            ActorDirectoryError::InvalidIdentity
        );
        Ok(())
    }

    #[tokio::test]
    async fn store_opened_before_creation_discovers_root_and_child_from_durable_files(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let writer = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let stale_reader = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let root = Session::new("late-root", "model");
        let child = Session::new_child_of("late-child", &root, "model", "Child");
        writer.save_session(&root).await?;
        writer.save_session(&child).await?;
        assert!(stale_reader.get_index_entry("late-child").await.is_none());
        assert_eq!(
            stale_reader.ensure_actor("late-root").await?.actor.actor_id,
            root.id
        );
        assert_eq!(
            stale_reader
                .ensure_actor("late-child")
                .await?
                .actor
                .parent_actor_id,
            Some(root.id.clone())
        );

        // Simulate a crash after a new Session's files became durable but
        // before the global rebuildable index was published.
        let orphan = Session::new_child_of("late-orphan", &root, "model", "Orphan");
        writer.save_session(&orphan).await?;
        let index_path = home.path().join("sessions.json");
        let mut index: serde_json::Value = serde_json::from_slice(&fs::read(&index_path).await?)?;
        index["sessions"]
            .as_object_mut()
            .unwrap()
            .remove(&orphan.id);
        fs::write(index_path, serde_json::to_vec(&index)?).await?;
        assert_eq!(
            stale_reader.ensure_actor(&orphan.id).await?.actor.actor_id,
            orphan.id
        );
        let activation = stale_reader
            .claim_activation(&claim(&orphan.id, "run", "host", Utc::now()))
            .await?;
        assert_eq!(activation.attempt, 1);
        Ok(())
    }

    #[tokio::test]
    async fn orphaned_nested_child_cannot_publish_activation_authority(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let root = Session::new("lineage-root", "model");
        let child = Session::new_child_of("lineage-child", &root, "model", "Child");
        let grandchild = Session::new_child_of("lineage-grandchild", &child, "model", "Grandchild");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        store.save_session(&grandchild).await?;

        assert!(store.delete_session(&child.id).await?);
        assert!(store.load_session(&child.id).await?.is_none());
        assert!(store.load_session(&grandchild.id).await?.is_some());
        assert_eq!(
            store
                .claim_activation(&claim(&grandchild.id, "run", "host", Utc::now()))
                .await
                .unwrap_err(),
            ActorDirectoryError::NotFound(child.id.clone())
        );
        assert!(!home
            .path()
            .join("sessions/lineage-root/children/lineage-grandchild/actor-authority.json")
            .exists());
        Ok(())
    }

    #[tokio::test]
    async fn duplicate_physical_actor_id_fails_closed_across_stale_stores(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let first = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let origin = Session::new("origin", "model");
        let child = Session::new_child_of("same", &origin, "model", "Child");
        first.save_session(&origin).await?;
        first.save_session(&child).await?;
        let stale = SessionStoreV2::new(home.path().to_path_buf()).await?;
        first.save_session(&Session::new("same", "model")).await?;

        for store in [&first, &stale] {
            assert_eq!(
                store
                    .claim_activation(&claim("same", "run", "host", Utc::now()))
                    .await
                    .unwrap_err(),
                ActorDirectoryError::Corrupt
            );
        }
        assert!(!home
            .path()
            .join("sessions/origin/children/same/actor-authority.json")
            .exists());
        assert!(!home
            .path()
            .join("sessions/same/actor-authority.json")
            .exists());
        Ok(())
    }

    #[tokio::test]
    async fn child_project_must_match_its_current_parent() -> Result<(), Box<dyn std::error::Error>>
    {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("project-lineage-root", "model");
        root.set_project_id_meta("project-a");
        let mut child = Session::new_child_of("project-lineage-child", &root, "model", "Child");
        child.set_project_id_meta("project-b");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        assert_eq!(
            store
                .claim_activation(&claim(&child.id, "run", "host", Utc::now()))
                .await
                .unwrap_err(),
            ActorDirectoryError::InvalidIdentity
        );
        Ok(())
    }

    #[tokio::test]
    async fn active_grandchild_cannot_observe_middle_parent_project_rebind(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("aba-root", "model");
        root.set_project_id_meta("project-a");
        let mut child = Session::new_child_of("aba-child", &root, "model", "Child");
        child.set_project_id_meta("project-a");
        let mut grandchild = Session::new_child_of("aba-grandchild", &child, "model", "Grandchild");
        grandchild.set_project_id_meta("project-a");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        store.save_session(&grandchild).await?;
        let stale_store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let now = Utc::now();
        let activation = store
            .claim_activation(&claim(&grandchild.id, "run", "host", now))
            .await?;
        child.set_project_id_meta("project-b");
        child.metadata_version += 1;
        assert_eq!(
            stale_store
                .save_runtime_state(&child)
                .await
                .unwrap_err()
                .kind(),
            io::ErrorKind::WouldBlock
        );
        assert_eq!(
            store.save_session(&child).await.unwrap_err().kind(),
            io::ErrorKind::WouldBlock
        );
        assert_eq!(
            store
                .load_session(&child.id)
                .await?
                .unwrap()
                .project_id_meta()
                .as_deref(),
            Some("project-a")
        );
        let restarted = SessionStoreV2::new(home.path().to_path_buf()).await?;
        restarted.validate_fence(&activation.fence(), now).await?;
        Ok(())
    }

    #[tokio::test]
    async fn active_child_cannot_rebind_its_own_project() -> Result<(), Box<dyn std::error::Error>>
    {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("own-aba-root", "model");
        root.set_project_id_meta("project-a");
        let mut child = Session::new_child_of("own-aba-child", &root, "model", "Child");
        child.set_project_id_meta("project-a");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        let now = Utc::now();
        let activation = store
            .claim_activation(&claim(&child.id, "run", "host", now))
            .await?;
        child.set_project_id_meta("project-b");
        child.metadata_version += 1;
        assert_eq!(
            store.save_runtime_state(&child).await.unwrap_err().kind(),
            io::ErrorKind::WouldBlock
        );
        store.validate_fence(&activation.fence(), now).await?;
        Ok(())
    }

    #[tokio::test]
    async fn recreated_middle_parent_cannot_revive_grandchild_fence(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let root = Session::new("birth-root", "model");
        let child = Session::new_child_of("birth-child", &root, "model", "Child");
        let grandchild = Session::new_child_of("birth-grandchild", &child, "model", "Grandchild");
        store.save_session(&root).await?;
        store.save_session(&child).await?;
        store.save_session(&grandchild).await?;
        let now = Utc::now();
        let activation = store
            .claim_activation(&claim(&grandchild.id, "run", "host", now))
            .await?;
        assert!(store.delete_session(&child.id).await?);
        let mut replacement = Session::new_child_of(&child.id, &root, "model", "Replacement");
        replacement.created_at = child.created_at + Duration::seconds(1);
        store.save_session(&replacement).await?;
        assert_eq!(
            store
                .validate_fence(&activation.fence(), now)
                .await
                .unwrap_err(),
            ActorDirectoryError::InvalidIdentity
        );
        Ok(())
    }

    #[tokio::test]
    async fn root_project_rebinds_only_when_no_activation_is_live(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("project-root", "model");
        store.save_session(&root).await?;
        let original = store.ensure_actor(&root.id).await?;
        root.set_project_id_meta(" project-first ");
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        let bound = store.inspect_actor(&root.id).await?;
        assert_eq!(bound.actor.project_id.as_deref(), Some("project-first"));
        assert_eq!(bound.revision, original.revision + 1);
        root.set_project_id_meta("project-second");
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        let reassigned = store.inspect_actor(&root.id).await?;
        assert_eq!(
            reassigned.actor.project_id.as_deref(),
            Some("project-second")
        );
        assert_eq!(reassigned.revision, bound.revision + 1);
        let now = Utc::now();
        let active = store
            .claim_activation(&claim(&root.id, "run", "host", now))
            .await?;
        assert_eq!(active.project_id.as_deref(), Some("project-second"));

        root.set_project_id_meta("project-third");
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        let sidecar = home
            .path()
            .join("sessions/project-root/actor-authority.json");
        let before = fs::read(&sidecar).await?;
        assert_eq!(
            store.inspect_actor(&root.id).await.unwrap_err(),
            ActorDirectoryError::ProjectTransitionBlocked
        );
        assert_eq!(
            store
                .validate_fence(&active.fence(), now)
                .await
                .unwrap_err(),
            ActorDirectoryError::ProjectTransitionBlocked
        );
        assert_eq!(fs::read(&sidecar).await?, before);
        let reopened = SessionStoreV2::new(home.path().to_path_buf()).await?;
        assert_eq!(
            reopened.inspect_actor(&root.id).await.unwrap_err(),
            ActorDirectoryError::ProjectTransitionBlocked
        );
        Ok(())
    }

    #[tokio::test]
    async fn root_project_aba_cannot_revive_an_old_active_fence(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("project-aba", "model");
        root.set_project_id_meta("project-a");
        store.save_session(&root).await?;
        let now = Utc::now();
        let activation = store
            .claim_activation(&claim(&root.id, "run", "host", now))
            .await?;
        let sidecar = home
            .path()
            .join("sessions/project-aba/actor-authority.json");
        let before = fs::read(&sidecar).await?;

        for project in ["project-b", "project-a"] {
            root.set_project_id_meta(project);
            root.metadata_version += 1;
            store.save_runtime_state(&root).await?;
        }
        assert_eq!(
            store
                .validate_fence(&activation.fence(), now)
                .await
                .unwrap_err(),
            ActorDirectoryError::ProjectTransitionBlocked
        );
        assert_eq!(fs::read(&sidecar).await?, before);
        let reopened = SessionStoreV2::new(home.path().to_path_buf()).await?;
        assert_eq!(
            reopened.inspect_actor(&root.id).await.unwrap_err(),
            ActorDirectoryError::ProjectTransitionBlocked
        );
        Ok(())
    }

    #[tokio::test]
    async fn active_root_allows_one_ui_revision_but_blocks_ambiguous_ui_gap(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        let mut root = Session::new("project-ui", "model");
        root.set_project_id_meta("project-a");
        store.save_session(&root).await?;
        let now = Utc::now();
        let activation = store
            .claim_activation(&claim(&root.id, "run", "host", now))
            .await?;

        root.title = "One title change".into();
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        store.validate_fence(&activation.fence(), now).await?;
        let observed = store.inspect_actor(&root.id).await?;
        assert_eq!(observed.actor.observed_metadata_version, 1);
        let sidecar = home.path().join("sessions/project-ui/actor-authority.json");
        let before = fs::read(&sidecar).await?;

        root.pinned = true;
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        root.title = "Another title change".into();
        root.metadata_version += 1;
        store.save_runtime_state(&root).await?;
        assert_eq!(
            store
                .validate_fence(&activation.fence(), now)
                .await
                .unwrap_err(),
            ActorDirectoryError::ProjectTransitionBlocked
        );
        assert_eq!(fs::read(&sidecar).await?, before);
        Ok(())
    }

    #[tokio::test]
    async fn initialized_marker_prevents_lost_sidecar_from_resetting_attempt(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let store = SessionStoreV2::new(home.path().to_path_buf()).await?;
        store
            .save_session(&Session::new("marker-root", "model"))
            .await?;
        let sidecar = home
            .path()
            .join("sessions/marker-root/actor-authority.json");
        let marker = home
            .path()
            .join("sessions/marker-root/actor-authority.initialized.json");
        store.ensure_actor("marker-root").await?;
        assert!(sidecar.is_file() && marker.is_file());

        // Interrupted initial publication may leave only an inert Cold file.
        fs::remove_file(&marker).await?;
        let reopened = SessionStoreV2::new(home.path().to_path_buf()).await?;
        assert_eq!(
            reopened
                .ensure_actor("marker-root")
                .await?
                .actor
                .current_attempt,
            0
        );
        assert!(marker.is_file());
        reopened
            .claim_activation(&claim("marker-root", "run", "host", Utc::now()))
            .await?;
        let marker_bytes = fs::read(&marker).await?;
        fs::remove_file(&marker).await?;
        assert_eq!(
            reopened.inspect_actor("marker-root").await.unwrap_err(),
            ActorDirectoryError::Corrupt
        );
        fs::write(&marker, marker_bytes).await?;
        fs::remove_file(&sidecar).await?;
        let lost = SessionStoreV2::new(home.path().to_path_buf()).await?;
        assert_eq!(
            lost.inspect_actor("marker-root").await.unwrap_err(),
            ActorDirectoryError::Corrupt
        );
        assert_eq!(
            lost.claim_activation(&claim("marker-root", "retry", "host", Utc::now()))
                .await
                .unwrap_err(),
            ActorDirectoryError::Corrupt
        );
        assert!(!sidecar.exists());

        store
            .save_session(&Session::new("direct-claim", "model"))
            .await?;
        let direct = store
            .claim_activation(&claim("direct-claim", "run", "host", Utc::now()))
            .await?;
        assert_eq!(direct.attempt, 1);
        assert!(home
            .path()
            .join("sessions/direct-claim/actor-authority.initialized.json")
            .is_file());
        Ok(())
    }
}