liminal-protocol 0.2.1

Shared participant-lifecycle protocol types for liminal
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
//! Validated durable-state restoration for participant lifecycle typestates.
//!
//! Storage serialization necessarily crosses the crate's compile-time state
//! boundary. These capsules retain the predecessor data needed to rebuild
//! opaque authorities, then validate every identity, generation, epoch, and
//! paired-state invariant before returning executable lifecycle values.

use alloc::vec::Vec;

use crate::algebra::WideResourceVector;
use crate::outcome::ParticipantStateCorruptReason;
use crate::wire::{
    AttachSecret, BindingEpoch, CloseCause, ConversationId, DeliverySeq, DetachAttemptToken,
    Generation, LeaveAttemptToken, LeaveCommitted, ObserverEpoch, ParticipantId, TransactionOrder,
};

use super::{
    ActiveBinding, AdmissionOrder, BindingOrigin, BindingState, BoundParticipantCursor,
    ClaimFrontiers, ClaimFrontiersRestore, ClosureDebt, ClosureState, CommittedBindingTerminal,
    DebtCompletion, DetachCell, DetachedCredentialRecovery, DetachedMarkerRelease, EmptyDetach,
    EnrollmentFingerprint, Event, FencedAttachCommit, FrontierBinding, IdentityState,
    LeaveFingerprint, LiveMember, LiveMemberRestore, MarkerDelivery, NonzeroDebtCursorEpisode,
    ObserverProjection, OrderLedger, OrdinaryBindingAuthority, OrdinaryBindingFate,
    ParticipantCursorProgress, PendingFinalization, PendingRecoveredCursorRelease,
    PhysicalCompaction, RecoveredBindingFate, RecoveredBindingFateTransition, RetiredIdentity,
    SequenceLedger, StoredEdge,
    binding::{restore_committed_terminal, restore_pending_finalization},
    claim_frontier::{
        HistoricalCausalAuthority, MarkerRecordOccurrence, MarkerRecordRequest,
        ValidatedConversationHistory, ValidatedMarkerRecord,
    },
    cursor_facts::{CursorProgressFact, CursorProgressKey},
    detach::{
        restore_committed_detach, restore_pending_detach, restore_terminalized_detach,
        validate_pending_pair,
    },
};

/// A durable lifecycle capsule failed a protocol invariant.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StorageRestoreError {
    /// A raw committed binding terminal has an impossible cause or restart suffix.
    CommittedBindingTerminal,
    /// A pending terminal has an impossible cause or restart suffix.
    PendingFinalization,
    /// A binding slot names another live identity or generation.
    BindingAuthority,
    /// Live membership disagrees with its decoded terminal identity or generation.
    MembershipInvariant,
    /// A raw permanent Leave result is internally inconsistent.
    LeaveResult,
    /// A retired identity disagrees with its permanent Leave result.
    RetiredIdentity,
    /// A detach-cell variant is internally inconsistent.
    DetachCell,
    /// Binding, membership, terminal history, and detach cell do not form one state.
    DetachBindingPair,
    /// Cursor-episode floor, participant, or fact state is inconsistent.
    CursorEpisode,
    /// A closure state paired a zero debt vector with a stored edge.
    ClosureDebt,
    /// A stored edge disagrees with the predecessor provenance in its capsule.
    StoredEdgeProvenance,
}

/// Failure while jointly restoring claim frontiers and their current closure edge.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConversationStateRestoreError {
    /// Numeric, causal, or cross-counter claim-frontier validation failed.
    ClaimFrontier(ParticipantStateCorruptReason),
    /// Raw lifecycle storage disagreed with its typed predecessor authority.
    Storage(StorageRestoreError),
}

/// Crate-internal jointly restored claim frontiers and exact current closure state.
///
/// This value can execute restored edge authority. It is deliberately absent
/// from the public storage surface: external callers may deserialize inert
/// restore data, but only protocol-owned replay may promote it to executable
/// state.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct RestoredConversationState {
    frontiers: ClaimFrontiers,
    closure: ClosureState,
}

/// Complete raw participant-conversation snapshot for public cold restore.
///
/// Every field is inert storage data. The only consumer is [`Self::restore`],
/// which validates the whole snapshot as one unit: participant capsules first,
/// then the conversation history derived from those exact restored
/// participants (never an empty history), then frontiers and the closure edge
/// against that owned history. Components restored from different snapshots
/// are not independently combinable — [`ParticipantConversationState`] has no
/// public constructor, restored binding origins and marker-record authorities
/// are minted only inside this joint validation, and mixing capsules from
/// different histories fails the frontier-projection and provenance checks.
/// A valid producer proof therefore cannot be spliced into executable
/// authority it never had.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParticipantConversationRestore<EF, V, LF, D> {
    /// Complete live and retired participant states.
    pub participants: Vec<ParticipantLifecycleRestore<EF, V, LF, D>>,
    /// Coupled raw claim frontiers.
    pub frontiers: ClaimFrontiersRestore,
    /// Aggregate delivery-sequence ledger.
    pub sequence_ledger: SequenceLedger,
    /// Aggregate transaction-order ledger.
    pub order_ledger: OrderLedger,
    /// Current closure state.
    pub closure: ClosureStateRestore,
}

/// Fully validated whole-conversation participant state.
///
/// This state can execute restored edge authority. It has no public
/// constructor and its fields are private: the sole producer is
/// [`ParticipantConversationRestore::restore`], so possession of this value
/// proves the complete snapshot validated jointly.
///
/// ```compile_fail
/// use liminal_protocol::lifecycle::ParticipantConversationState;
///
/// fn fabricate() {
///     let _ = ParticipantConversationState::<[u8; 4], [u8; 4], [u8; 4], [u8; 4]> {
///         participants: unreachable!(),
///         frontiers: unreachable!(),
///         closure: unreachable!(),
///     };
/// }
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct ParticipantConversationState<EF, V, LF, D> {
    participants: Vec<RestoredParticipantLifecycle<EF, V, LF, D>>,
    frontiers: ClaimFrontiers,
    closure: ClosureState,
}

impl<EF, V, LF, D> ParticipantConversationState<EF, V, LF, D> {
    /// Borrows every restored participant and tombstone.
    #[must_use]
    pub fn participants(&self) -> &[RestoredParticipantLifecycle<EF, V, LF, D>] {
        &self.participants
    }

    /// Borrows the finalized claim frontiers.
    #[must_use]
    pub const fn frontiers(&self) -> &ClaimFrontiers {
        &self.frontiers
    }

    /// Returns the exact closure state.
    #[must_use]
    pub const fn closure(&self) -> ClosureState {
        self.closure
    }

    /// Consumes the validated state into its participant, frontier, and
    /// closure components.
    ///
    /// Decomposition is one-way: no public path recombines components into
    /// this validated form, so values split here cannot be spliced with
    /// components restored from another snapshot.
    #[must_use]
    #[allow(clippy::type_complexity)]
    pub fn into_parts(
        self,
    ) -> (
        Vec<RestoredParticipantLifecycle<EF, V, LF, D>>,
        ClaimFrontiers,
        ClosureState,
    ) {
        (self.participants, self.frontiers, self.closure)
    }
}

impl RestoredConversationState {
    /// Borrows the fully finalized coupled claim frontiers.
    #[must_use]
    #[cfg(test)]
    pub(crate) const fn frontiers(&self) -> &ClaimFrontiers {
        &self.frontiers
    }

    /// Returns the exact restored closure debt and stored edge.
    #[must_use]
    #[cfg(test)]
    pub(crate) const fn closure(&self) -> ClosureState {
        self.closure
    }

    /// Consumes the aggregate into the two values persisted by a server binding.
    #[must_use]
    pub(crate) fn into_parts(self) -> (ClaimFrontiers, ClosureState) {
        (self.frontiers, self.closure)
    }
}

/// Restores claim ownership and its marker-derived edge as one provenance unit.
///
/// Numeric/candidate validation runs first. At most one non-cloneable retained
/// marker token is then consumed to restore the raw closure edge, after which
/// frontier recovery claims are finalized against that exact typed edge.
/// This standalone form intentionally rejects raw compacted causal history and
/// ordinary-binding cursor authority; those require protocol-owned event replay
/// to establish owned lifecycle provenance first. It is crate-private because
/// accepting caller-authored snapshots here would upgrade inert storage bytes
/// into executable edge authority.
///
/// # Errors
///
/// Returns [`ConversationStateRestoreError::ClaimFrontier`] for malformed
/// numeric/candidate ownership or [`ConversationStateRestoreError::Storage`]
/// for a missing, ambiguous, cross-conversation, or context-mismatched marker
/// record and every other stored-edge provenance failure.
#[cfg(test)]
pub(super) fn restore_conversation_state(
    frontier_restore: ClaimFrontiersRestore,
    sequence_ledger: SequenceLedger,
    order_ledger: OrderLedger,
    closure_restore: &ClosureStateRestore,
) -> Result<RestoredConversationState, ConversationStateRestoreError> {
    let history = ValidatedConversationHistory::empty();
    restore_conversation_with_history(
        frontier_restore,
        sequence_ledger,
        order_ledger,
        closure_restore,
        &history,
    )
}

fn restore_conversation_with_history(
    frontier_restore: ClaimFrontiersRestore,
    sequence_ledger: SequenceLedger,
    order_ledger: OrderLedger,
    closure_restore: &ClosureStateRestore,
    history: &ValidatedConversationHistory,
) -> Result<RestoredConversationState, ConversationStateRestoreError> {
    let mut prevalidated = ClaimFrontiers::prevalidate_with_history(
        frontier_restore,
        sequence_ledger,
        order_ledger,
        history,
    )
    .map_err(ConversationStateRestoreError::ClaimFrontier)?;
    let marker_request = closure_restore.marker_record_request();
    let ordinary_request = closure_restore.ordinary_binding_request();
    let closure = match (marker_request, ordinary_request) {
        (Some(marker_request), None) => {
            let record = prevalidated.take_marker_record(marker_request).ok_or(
                ConversationStateRestoreError::Storage(StorageRestoreError::StoredEdgeProvenance),
            )?;
            (*closure_restore)
                .restore_with_marker_record(prevalidated.conversation_id(), record)
                .map_err(ConversationStateRestoreError::Storage)?
        }
        (None, Some(binding)) => {
            let origin = history
                .ordinary_origin(
                    binding.conversation_id,
                    binding.participant_id,
                    binding.binding_epoch,
                )
                .ok_or(ConversationStateRestoreError::Storage(
                    StorageRestoreError::StoredEdgeProvenance,
                ))?;
            (*closure_restore)
                .restore_with_binding_origin(origin)
                .map_err(ConversationStateRestoreError::Storage)?
        }
        (None, None) => (*closure_restore)
            .restore()
            .map_err(ConversationStateRestoreError::Storage)?,
        (Some(_), Some(_)) => {
            return Err(ConversationStateRestoreError::Storage(
                StorageRestoreError::StoredEdgeProvenance,
            ));
        }
    };
    let current_edge = match closure {
        ClosureState::Clear => None,
        ClosureState::Owed { edge, .. } => Some(edge),
    };
    let frontiers = prevalidated
        .finish(current_edge)
        .map_err(ConversationStateRestoreError::ClaimFrontier)?;
    Ok(RestoredConversationState { frontiers, closure })
}

/// Raw durable fields for one committed binding terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommittedBindingTerminalRestore {
    /// Binding authority that ended.
    pub binding: ActiveBinding,
    /// Cause stored with the terminal.
    pub cause: CloseCause,
    /// Immutable admission major.
    pub transaction_order: TransactionOrder,
    /// Durable lifecycle delivery sequence.
    pub delivery_seq: DeliverySeq,
}

impl CommittedBindingTerminalRestore {
    /// Validates and rebuilds the cause-partitioned committed terminal.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::CommittedBindingTerminal`] for an
    /// impossible cause/suffix combination.
    pub fn restore(self) -> Result<CommittedBindingTerminal, StorageRestoreError> {
        restore_committed_terminal(
            self.binding,
            self.cause,
            self.transaction_order,
            self.delivery_seq,
        )
        .ok_or(StorageRestoreError::CommittedBindingTerminal)
    }
}

/// Raw durable fields for one pending binding terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingFinalizationRestore {
    /// Binding authority that already ended.
    pub binding: ActiveBinding,
    /// Cause stored with the pending terminal.
    pub cause: CloseCause,
    /// Immutable reserved admission major.
    pub transaction_order: TransactionOrder,
}

impl PendingFinalizationRestore {
    /// Validates and rebuilds the cause-partitioned pending terminal.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::PendingFinalization`] when the cause
    /// cannot be pending or an unclean-restart suffix names another server.
    pub fn restore(self) -> Result<PendingFinalization, StorageRestoreError> {
        restore_pending_finalization(self.binding, self.cause, self.transaction_order)
            .ok_or(StorageRestoreError::PendingFinalization)
    }
}

/// Durable binding-fate terminal provenance, whether appended or still pending.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingFateTerminalRestore {
    /// Terminal appended in the binding-fate transaction.
    Committed(CommittedBindingTerminalRestore),
    /// Binding fate committed but its terminal append remains pending.
    Pending(PendingFinalizationRestore),
}

/// Validated binding-fate terminal provenance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RestoredBindingFateTerminal {
    /// Cause-partitioned committed terminal.
    Committed(CommittedBindingTerminal),
    /// Cause-partitioned pending terminal.
    Pending(PendingFinalization),
}

impl BindingFateTerminalRestore {
    /// Validates and rebuilds either durable terminal disposition.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError`] for an impossible cause or restart suffix.
    pub fn restore(self) -> Result<RestoredBindingFateTerminal, StorageRestoreError> {
        match self {
            Self::Committed(value) => value.restore().map(RestoredBindingFateTerminal::Committed),
            Self::Pending(value) => value.restore().map(RestoredBindingFateTerminal::Pending),
        }
    }
}

impl RestoredBindingFateTerminal {
    const fn participant_id(self) -> ParticipantId {
        match self {
            Self::Committed(value) => value.participant_id(),
            Self::Pending(value) => value.participant_id(),
        }
    }

    const fn conversation_id(self) -> ConversationId {
        match self {
            Self::Committed(value) => value.conversation_id(),
            Self::Pending(value) => value.conversation_id(),
        }
    }

    const fn binding_epoch(self) -> BindingEpoch {
        match self {
            Self::Committed(value) => value.binding_epoch(),
            Self::Pending(value) => value.binding_epoch(),
        }
    }
}

/// Durable binding-slot representation with raw pending-terminal fields.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingStateRestore {
    /// No binding authority or pending terminal.
    Detached,
    /// Live binding authority.
    Bound(ActiveBinding),
    /// Ended authority whose terminal append remains pending.
    PendingFinalization(PendingFinalizationRestore),
}

impl BindingStateRestore {
    fn restore_for<EF>(self, member: &LiveMember<EF>) -> Result<BindingState, StorageRestoreError> {
        let state = match self {
            Self::Detached => BindingState::Detached,
            Self::Bound(binding) => BindingState::Bound(binding),
            Self::PendingFinalization(raw) => BindingState::PendingFinalization(raw.restore()?),
        };
        let authority_matches = match state {
            BindingState::Detached => true,
            BindingState::Bound(binding) => {
                binding.participant_id == member.participant_id()
                    && binding.conversation_id == member.conversation_id()
                    && binding.binding_epoch.capability_generation == member.generation()
            }
            BindingState::PendingFinalization(pending) => {
                pending.participant_id() == member.participant_id()
                    && pending.conversation_id() == member.conversation_id()
                    && pending.binding_epoch().capability_generation == member.generation()
            }
        };
        if authority_matches {
            Ok(state)
        } else {
            Err(StorageRestoreError::BindingAuthority)
        }
    }
}

/// Raw durable fields for the latest committed terminal retained by membership.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiveIdentityRestore<EF> {
    /// Permanent participant identity/index.
    pub participant_id: ParticipantId,
    /// Owning conversation.
    pub conversation_id: ConversationId,
    /// Current credential generation.
    pub generation: Generation,
    /// Current attach secret.
    pub attach_secret: AttachSecret,
    /// Durable cumulative participant cursor.
    pub cursor: DeliverySeq,
    /// Permanent enrollment-token fingerprint.
    pub enrollment_fingerprint: EnrollmentFingerprint<EF>,
    /// Most recent committed binding terminal, if any.
    pub latest_terminal: Option<CommittedBindingTerminalRestore>,
}

impl<EF> LiveIdentityRestore<EF> {
    fn restore(self) -> Result<LiveMember<EF>, StorageRestoreError> {
        let latest_terminal = self
            .latest_terminal
            .map(CommittedBindingTerminalRestore::restore)
            .transpose()?;
        LiveMember::restore(LiveMemberRestore {
            participant_id: self.participant_id,
            conversation_id: self.conversation_id,
            generation: self.generation,
            attach_secret: self.attach_secret,
            cursor: self.cursor,
            enrollment_fingerprint: self.enrollment_fingerprint,
            latest_terminal,
        })
        .map_err(|_| StorageRestoreError::MembershipInvariant)
    }
}

/// Raw fields of the canonical permanent `LeaveCommitted` result.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LeaveCommittedRestore {
    /// Conversation containing the participant.
    pub conversation_id: ConversationId,
    /// Committing Leave token.
    pub leave_attempt_token: LeaveAttemptToken,
    /// Retired participant.
    pub participant_id: ParticipantId,
    /// Permanent retired generation.
    pub retired_generation: Generation,
    /// Active binding ended in the Leave transaction, if any.
    pub ended_binding_epoch: Option<BindingEpoch>,
    /// Earlier binding-terminal delivery sequence, if any.
    pub prior_terminal_delivery_seq: Option<DeliverySeq>,
    /// Durable `Left` delivery sequence.
    pub left_delivery_seq: DeliverySeq,
}

impl LeaveCommittedRestore {
    /// Rebuilds the canonical terminal Leave result.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::LeaveResult`] for an epoch-generation
    /// mismatch or a terminal sequence not strictly before `Left`.
    pub fn restore(self) -> Result<LeaveCommitted, StorageRestoreError> {
        LeaveCommitted::new(
            self.conversation_id,
            self.leave_attempt_token,
            self.participant_id,
            self.retired_generation,
            self.ended_binding_epoch,
            self.prior_terminal_delivery_seq,
            self.left_delivery_seq,
        )
        .ok_or(StorageRestoreError::LeaveResult)
    }
}

/// Complete raw durable tombstone fields.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RetiredIdentityRestore<EF, V, LF> {
    /// Permanent participant identity/index.
    pub participant_id: ParticipantId,
    /// Conversation containing the tombstone.
    pub conversation_id: ConversationId,
    /// Permanent retired generation.
    pub retired_generation: Generation,
    /// Permanent enrollment-token fingerprint.
    pub enrollment_fingerprint: EnrollmentFingerprint<EF>,
    /// Permanent committing Leave token.
    pub leave_attempt_token: LeaveAttemptToken,
    /// Stored non-reversible Leave-request verifier.
    pub leave_request_verifier: V,
    /// Stored canonical Leave fingerprint.
    pub leave_fingerprint: LeaveFingerprint<LF>,
    /// Immutable transaction-order major of the permanent `Left` record.
    pub left_transaction_order: TransactionOrder,
    /// Complete canonical committed result.
    pub committed_result: LeaveCommittedRestore,
}

impl<EF, V, LF> RetiredIdentityRestore<EF, V, LF> {
    fn restore(self) -> Result<RetiredIdentity<EF, V, LF>, StorageRestoreError> {
        let result = self.committed_result.restore()?;
        RetiredIdentity::restore(
            self.participant_id,
            self.conversation_id,
            self.retired_generation,
            self.enrollment_fingerprint,
            self.leave_attempt_token,
            self.leave_request_verifier,
            self.leave_fingerprint,
            self.left_transaction_order,
            result,
        )
        .map_err(|_| StorageRestoreError::RetiredIdentity)
    }
}

/// Exact four-state durable detach replay cell.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DetachCellRestore<V> {
    /// No detach replay state.
    Empty,
    /// Accepted detach whose terminal append remains pending.
    Pending {
        /// Stable attempt token.
        token: DetachAttemptToken,
        /// Cell owner.
        participant_id: ParticipantId,
        /// Request generation.
        request_generation: Generation,
        /// Non-reversible exact-request verifier.
        request_verifier: V,
        /// Binding epoch ended by detach.
        committed_binding_epoch: BindingEpoch,
        /// Immutable binding-terminal admission position.
        admission_order: AdmissionOrder,
        /// Observer refusal epoch.
        refused_epoch: ObserverEpoch,
    },
    /// Committed detach retaining its exact terminal sequence.
    Committed {
        /// Stable attempt token.
        token: DetachAttemptToken,
        /// Cell owner.
        participant_id: ParticipantId,
        /// Request generation.
        request_generation: Generation,
        /// Non-reversible exact-request verifier.
        request_verifier: V,
        /// Binding epoch ended by detach.
        committed_binding_epoch: BindingEpoch,
        /// Committed `Detached` delivery sequence.
        detached_delivery_seq: DeliverySeq,
    },
    /// Post-attach replay state retaining the old binding epoch.
    Terminalized {
        /// Stable old detach token.
        token: DetachAttemptToken,
        /// Cell owner.
        participant_id: ParticipantId,
        /// Old request generation.
        request_generation: Generation,
        /// Non-reversible exact-request verifier.
        request_verifier: V,
        /// Old binding epoch ended by detach.
        committed_binding_epoch: BindingEpoch,
    },
}

impl<V> DetachCellRestore<V> {
    fn restore(self) -> Result<DetachCell<V>, StorageRestoreError> {
        match self {
            Self::Empty => Ok(DetachCell::Empty(EmptyDetach)),
            Self::Pending {
                token,
                participant_id,
                request_generation,
                request_verifier,
                committed_binding_epoch,
                admission_order,
                refused_epoch,
            } => restore_pending_detach(
                token,
                participant_id,
                request_generation,
                request_verifier,
                committed_binding_epoch,
                admission_order,
                refused_epoch,
            )
            .map(DetachCell::Pending)
            .ok_or(StorageRestoreError::DetachCell),
            Self::Committed {
                token,
                participant_id,
                request_generation,
                request_verifier,
                committed_binding_epoch,
                detached_delivery_seq,
            } => restore_committed_detach(
                token,
                participant_id,
                request_generation,
                request_verifier,
                committed_binding_epoch,
                detached_delivery_seq,
            )
            .map(DetachCell::Committed)
            .ok_or(StorageRestoreError::DetachCell),
            Self::Terminalized {
                token,
                participant_id,
                request_generation,
                request_verifier,
                committed_binding_epoch,
            } => restore_terminalized_detach(
                token,
                participant_id,
                request_generation,
                request_verifier,
                committed_binding_epoch,
            )
            .map(DetachCell::Terminalized)
            .ok_or(StorageRestoreError::DetachCell),
        }
    }
}

/// Complete event-replayed participant state, with tombstone precedence in the type.
#[allow(
    clippy::large_enum_variant,
    reason = "the live storage capsule remains inline so its atomic slots cannot be restored separately"
)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParticipantLifecycleRestore<EF, V, LF, D> {
    /// Live identity and its atomically paired binding and detach slots.
    Live {
        /// Membership and terminal history.
        identity: LiveIdentityRestore<EF>,
        /// Binding slot.
        binding: BindingStateRestore,
        /// Current or last binding's producer-emitted origin capsule.
        binding_origin: Option<BindingOrigin>,
        /// Four-state detach replay cell.
        detach_cell: DetachCellRestore<D>,
    },
    /// Permanent tombstone; no live binding or detach slot can accompany it.
    Retired(RetiredIdentityRestore<EF, V, LF>),
}

/// Validated runtime participant state restored from durable data.
#[allow(
    clippy::large_enum_variant,
    reason = "the validated live capsule remains inline as one atomic lifecycle result"
)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RestoredParticipantLifecycle<EF, V, LF, D> {
    /// Valid live membership and its paired slots.
    Live {
        /// Validated live member.
        member: LiveMember<EF>,
        /// Validated binding state.
        binding: BindingState,
        /// Validated current or last binding origin, when a binding has existed.
        binding_origin: Option<BindingOrigin>,
        /// Validated detach cell.
        detach_cell: DetachCell<D>,
    },
    /// Permanent retired identity with no remaining live slots.
    Retired(RetiredIdentity<EF, V, LF>),
}

impl<EF, V, LF, D> ParticipantLifecycleRestore<EF, V, LF, D> {
    /// Validates one complete atomic participant snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError`] when any raw state is invalid or the
    /// membership, binding, terminal history, and detach-cell variants disagree.
    pub fn restore(
        self,
    ) -> Result<RestoredParticipantLifecycle<EF, V, LF, D>, StorageRestoreError> {
        match self {
            Self::Retired(identity) => identity
                .restore()
                .map(RestoredParticipantLifecycle::Retired),
            Self::Live {
                identity,
                binding,
                binding_origin,
                detach_cell,
            } => {
                let member = identity.restore()?;
                let binding = binding.restore_for(&member)?;
                let binding_origin = binding_origin
                    .map(|origin| validate_binding_origin(origin, &member, binding))
                    .transpose()?;
                let origin_required = !matches!(binding, BindingState::Detached)
                    || member.latest_terminal().is_some();
                if origin_required != binding_origin.is_some() {
                    return Err(StorageRestoreError::BindingAuthority);
                }
                let detach_cell = detach_cell.restore()?;
                validate_live_pair(&member, binding, &detach_cell)?;
                Ok(RestoredParticipantLifecycle::Live {
                    member,
                    binding,
                    binding_origin,
                    detach_cell,
                })
            }
        }
    }
}

fn validate_binding_origin<EF>(
    origin: BindingOrigin,
    member: &LiveMember<EF>,
    binding_state: BindingState,
) -> Result<BindingOrigin, StorageRestoreError> {
    let expected_epoch = match binding_state {
        BindingState::Bound(current) => Some(current.binding_epoch),
        BindingState::PendingFinalization(pending) => Some(pending.binding_epoch()),
        BindingState::Detached => member
            .latest_terminal()
            .map(CommittedBindingTerminal::binding_epoch),
    };
    let attached = origin.attached();
    if origin.participant_id() != member.participant_id()
        || origin.conversation_id() != member.conversation_id()
        || expected_epoch != Some(origin.binding_epoch())
        || attached.participant_id() != member.participant_id()
        || attached.conversation_id() != member.conversation_id()
    {
        Err(StorageRestoreError::BindingAuthority)
    } else {
        Ok(origin)
    }
}

impl<EF, V, LF, D> RestoredParticipantLifecycle<EF, V, LF, D> {
    /// Consumes the restored snapshot into the crate's identity and optional live slots.
    #[must_use]
    #[allow(clippy::type_complexity)]
    pub fn into_parts(
        self,
    ) -> (
        IdentityState<EF, V, LF>,
        Option<BindingState>,
        Option<DetachCell<D>>,
    ) {
        match self {
            Self::Live {
                member,
                binding,
                binding_origin: _,
                detach_cell,
            } => (
                IdentityState::Live(member),
                Some(binding),
                Some(detach_cell),
            ),
            Self::Retired(identity) => (IdentityState::Retired(identity), None, None),
        }
    }
}

impl<EF, V, LF, D> ParticipantConversationRestore<EF, V, LF, D> {
    /// Restores participant lifecycle, sealed history/origins, frontiers, and
    /// closure as one total conversation snapshot.
    ///
    /// The conversation history backing frontier and closure validation is
    /// derived exclusively from the participants restored in this same call —
    /// never from an empty placeholder — so raw causal rows, binding origins,
    /// and marker ownership must be proven by the exact membership and
    /// tombstone capsules supplied alongside them.
    ///
    /// # Errors
    ///
    /// Returns a storage error when participant snapshots or binding origins
    /// disagree, and a claim-frontier error when the exact participant-derived
    /// history does not back raw causal rows and marker ownership.
    pub fn restore(
        self,
    ) -> Result<ParticipantConversationState<EF, V, LF, D>, ConversationStateRestoreError> {
        let participants = self
            .participants
            .into_iter()
            .map(ParticipantLifecycleRestore::restore)
            .collect::<Result<Vec<_>, _>>()
            .map_err(ConversationStateRestoreError::Storage)?;
        validate_participant_frontier_projection(
            &participants,
            self.frontiers.conversation_id,
            &self.frontiers.active_identities,
        )?;
        let history = validated_conversation_history(&participants)?;
        let restored = restore_conversation_with_history(
            self.frontiers,
            self.sequence_ledger,
            self.order_ledger,
            &self.closure,
            &history,
        )?;
        let (frontiers, closure) = restored.into_parts();
        Ok(ParticipantConversationState {
            participants,
            frontiers,
            closure,
        })
    }
}

fn validated_conversation_history<EF, V, LF, D>(
    participants: &[RestoredParticipantLifecycle<EF, V, LF, D>],
) -> Result<ValidatedConversationHistory, ConversationStateRestoreError> {
    let mut causal_authorities = Vec::new();
    let mut binding_origins = Vec::new();
    let mut seen = Vec::with_capacity(participants.len());
    for participant in participants {
        let participant_id = match participant {
            RestoredParticipantLifecycle::Live {
                member,
                binding_origin,
                ..
            } => {
                if let Some(terminal) = member.latest_terminal() {
                    causal_authorities
                        .push(HistoricalCausalAuthority::from_committed_terminal(terminal));
                }
                if let Some(origin) = binding_origin {
                    binding_origins.push(*origin);
                }
                member.participant_id()
            }
            RestoredParticipantLifecycle::Retired(retired) => {
                causal_authorities.push(HistoricalCausalAuthority::from_retired(retired));
                retired.participant_id()
            }
        };
        seen.push(participant_id);
    }
    // Conversations carry no participant-count cap, so the duplicate check is
    // sort-and-scan (O(n log n)) rather than a per-participant linear scan
    // (O(n^2)) over the whole-conversation cold-restore path.
    seen.sort_unstable();
    let has_duplicate = seen
        .iter()
        .zip(seen.iter().skip(1))
        .any(|(current, next)| current == next);
    if has_duplicate {
        return Err(ConversationStateRestoreError::Storage(
            StorageRestoreError::MembershipInvariant,
        ));
    }
    Ok(ValidatedConversationHistory::new(
        causal_authorities,
        binding_origins,
    ))
}

fn validate_participant_frontier_projection<EF, V, LF, D>(
    participants: &[RestoredParticipantLifecycle<EF, V, LF, D>],
    conversation_id: ConversationId,
    frontier: &[super::FrontierParticipant],
) -> Result<(), ConversationStateRestoreError> {
    let mut projected = Vec::new();
    for participant in participants {
        match participant {
            RestoredParticipantLifecycle::Live {
                member, binding, ..
            } => {
                if member.conversation_id() != conversation_id {
                    return Err(ConversationStateRestoreError::Storage(
                        StorageRestoreError::MembershipInvariant,
                    ));
                }
                let binding = match binding {
                    BindingState::Bound(binding) => FrontierBinding::Bound(binding.binding_epoch),
                    BindingState::PendingFinalization(pending) => {
                        FrontierBinding::Detached(pending.binding_epoch())
                    }
                    BindingState::Detached => {
                        let Some(terminal) = member.latest_terminal() else {
                            return Err(ConversationStateRestoreError::Storage(
                                StorageRestoreError::BindingAuthority,
                            ));
                        };
                        FrontierBinding::Detached(terminal.binding_epoch())
                    }
                };
                projected.push(super::FrontierParticipant::new(
                    member.participant_id(),
                    member.cursor(),
                    binding,
                ));
            }
            RestoredParticipantLifecycle::Retired(retired) => {
                if retired.conversation_id() != conversation_id {
                    return Err(ConversationStateRestoreError::Storage(
                        StorageRestoreError::MembershipInvariant,
                    ));
                }
            }
        }
    }
    projected.sort_by_key(|participant| participant.participant_index());
    if projected == frontier {
        Ok(())
    } else {
        Err(ConversationStateRestoreError::Storage(
            StorageRestoreError::MembershipInvariant,
        ))
    }
}

#[allow(clippy::suspicious_operation_groupings)]
fn validate_live_pair<EF, D>(
    member: &LiveMember<EF>,
    binding: BindingState,
    detach_cell: &DetachCell<D>,
) -> Result<(), StorageRestoreError> {
    match detach_cell {
        DetachCell::Empty(_) => Ok(()),
        DetachCell::Pending(cell) => {
            if cell.participant_id() != member.participant_id()
                || cell.request_generation() != member.generation()
                || validate_pending_pair(binding, cell, Some(member.conversation_id())).is_err()
            {
                Err(StorageRestoreError::DetachBindingPair)
            } else {
                Ok(())
            }
        }
        DetachCell::Committed(cell) => {
            let terminal_matches = member.latest_terminal().is_some_and(|terminal| {
                terminal.participant_id() == cell.participant_id()
                    && terminal.conversation_id() == member.conversation_id()
                    && terminal.binding_epoch() == cell.committed_binding_epoch()
                    && terminal.delivery_seq() == cell.detached_delivery_seq()
                    && terminal.detached_cause()
                        == Some(crate::wire::DetachedCause::CleanDeregister)
            });
            if cell.participant_id() != member.participant_id()
                || cell.request_generation() != member.generation()
                || binding != BindingState::Detached
                || !terminal_matches
            {
                Err(StorageRestoreError::DetachBindingPair)
            } else {
                Ok(())
            }
        }
        DetachCell::Terminalized(cell) => {
            if cell.participant_id() != member.participant_id()
                || cell.request_generation().get() >= member.generation().get()
            {
                Err(StorageRestoreError::DetachBindingPair)
            } else {
                Ok(())
            }
        }
    }
}

/// Complete raw state for one participant-scoped nonzero-debt cursor episode.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CursorEpisodeRestore {
    /// Owning conversation.
    pub conversation_id: ConversationId,
    /// Raw componentwise closure debt, validated nonzero during restoration.
    pub debt: WideResourceVector,
    /// Durable hard-observer progress `o`.
    pub observer_progress: DeliverySeq,
    /// Candidate high watermark `H'`.
    pub candidate_high_watermark: DeliverySeq,
    /// Current durable floor `F`.
    pub current_floor: u128,
    /// Current append-free class capacity floor.
    pub cap_floor: u128,
    /// Bound participant cursors keyed by their embedded permanent ids.
    pub participants: Vec<BoundParticipantCursor>,
    /// Variable facts keyed by `(participant_index, boundary)`.
    pub facts: Vec<(CursorProgressKey, CursorProgressFact)>,
}

impl CursorEpisodeRestore {
    /// Validates and rebuilds one cursor episode and all variable facts.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::CursorEpisode`] for an invalid floor,
    /// duplicate/unknown participant, duplicate fact, out-of-range boundary, or
    /// fact state inconsistent with the participant cursor.
    pub fn restore(self) -> Result<NonzeroDebtCursorEpisode, StorageRestoreError> {
        let debt = ClosureDebt::new(self.debt).ok_or(StorageRestoreError::ClosureDebt)?;
        NonzeroDebtCursorEpisode::restore(
            self.conversation_id,
            debt,
            self.observer_progress,
            self.candidate_high_watermark,
            self.current_floor,
            self.cap_floor,
            self.participants,
            self.facts,
        )
        .ok_or(StorageRestoreError::CursorEpisode)
    }
}

/// Raw predecessor fields for an ordinary-attach binding authority.
///
/// Raw fields are not executable provenance. Standalone restoration is absent:
/// total participant-conversation restore must first prove an exact unfenced
/// binding-origin capsule.
///
/// ```compile_fail
/// use liminal_protocol::lifecycle::OrdinaryBindingAuthorityRestore;
///
/// fn bypass(raw: OrdinaryBindingAuthorityRestore) {
///     let _ = raw.restore();
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OrdinaryBindingAuthorityRestore {
    /// Exact binding installed by ordinary attach.
    pub binding: ActiveBinding,
    /// Durable no-marker cursor carried through the attach.
    pub through_seq: DeliverySeq,
}

impl OrdinaryBindingAuthorityRestore {
    fn restore_with_origin(
        self,
        origin: &BindingOrigin,
    ) -> Result<OrdinaryBindingAuthority, StorageRestoreError> {
        if !origin.is_unfenced()
            || origin.conversation_id() != self.binding.conversation_id
            || origin.participant_id() != self.binding.participant_id
            || origin.binding_epoch() != self.binding.binding_epoch
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        Ok(OrdinaryBindingAuthority::new(
            self.binding,
            self.through_seq,
        ))
    }
}

/// Raw predecessor fields proving exact marker delivery.
///
/// A retained-record authority is mandatory and cannot be constructed by a
/// storage binding. Raw edge fields alone therefore fail at compile time.
///
/// ```compile_fail
/// use liminal_protocol::{
///     lifecycle::MarkerDeliveryRestore,
///     wire::BindingEpoch,
/// };
///
/// fn raw_restore(epoch: BindingEpoch) {
///     let raw = MarkerDeliveryRestore {
///         participant_id: 7,
///         binding_epoch: epoch,
///         marker_delivery_seq: 11,
///     };
///     let _ = raw.restore_bound(1);
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MarkerDeliveryRestore {
    /// Participant that received the marker.
    pub participant_id: ParticipantId,
    /// Exact receiving binding epoch.
    pub binding_epoch: BindingEpoch,
    /// Exact delivered marker sequence.
    pub marker_delivery_seq: DeliverySeq,
}

impl MarkerDeliveryRestore {
    /// Rebuilds a live marker-delivery witness after exact record-field matching.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::StoredEdgeProvenance`] when the authority
    /// belongs to another conversation, names a detached target, or disagrees
    /// with any raw edge field.
    #[cfg(test)]
    pub(super) fn restore_bound(
        self,
        conversation_id: ConversationId,
        record_authority: ValidatedMarkerRecord,
    ) -> Result<MarkerDelivery, StorageRestoreError> {
        let restored = self.restore_with_target(
            conversation_id,
            &record_authority,
            MarkerRecordTarget::Bound,
            MarkerRecordOccurrence::Undelivered,
        );
        record_authority.consume();
        restored
    }

    /// Exercises the delivered detached-record gate for adversarial tests.
    #[cfg(test)]
    pub(super) fn restore_detached_delivered_for_test(
        self,
        conversation_id: ConversationId,
        record_authority: ValidatedMarkerRecord,
    ) -> Result<MarkerDelivery, StorageRestoreError> {
        let restored = self.restore_with_target(
            conversation_id,
            &record_authority,
            MarkerRecordTarget::Detached,
            MarkerRecordOccurrence::Delivered,
        );
        record_authority.consume();
        restored
    }

    fn restore_detached(
        self,
        conversation_id: ConversationId,
        record_authority: &ValidatedMarkerRecord,
    ) -> Result<MarkerDelivery, StorageRestoreError> {
        self.restore_with_target(
            conversation_id,
            record_authority,
            MarkerRecordTarget::Detached,
            MarkerRecordOccurrence::Undelivered,
        )
    }

    fn restore_with_target(
        self,
        conversation_id: ConversationId,
        record_authority: &ValidatedMarkerRecord,
        target: MarkerRecordTarget,
        occurrence: MarkerRecordOccurrence,
    ) -> Result<MarkerDelivery, StorageRestoreError> {
        if record_authority.conversation_id() != conversation_id
            || !target.matches(record_authority.target_binding(), self.binding_epoch)
            || record_authority.occurrence() != occurrence
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        let delivery = MarkerDelivery::from_validated_record(record_authority);
        if delivery.participant_id() != self.participant_id
            || delivery.binding_epoch() != self.binding_epoch
            || delivery.marker_delivery_seq() != self.marker_delivery_seq
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        Ok(delivery)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MarkerRecordTarget {
    Bound,
    Detached,
}

impl MarkerRecordTarget {
    fn matches(self, target: super::FrontierBinding, epoch: BindingEpoch) -> bool {
        matches!(
            (self, target),
            (Self::Bound, super::FrontierBinding::Bound(actual))
                | (Self::Detached, super::FrontierBinding::Detached(actual))
                if actual == epoch
        )
    }
}

#[derive(Debug)]
enum MarkerRestoreAuthority<'a> {
    Absent,
    Record {
        conversation_id: ConversationId,
        record: &'a ValidatedMarkerRecord,
    },
}

impl MarkerRestoreAuthority<'_> {
    const fn require_absent(&self) -> Result<(), StorageRestoreError> {
        match self {
            Self::Absent => Ok(()),
            Self::Record { .. } => Err(StorageRestoreError::StoredEdgeProvenance),
        }
    }

    const fn require_record(
        &self,
    ) -> Result<(ConversationId, &ValidatedMarkerRecord), StorageRestoreError> {
        match self {
            Self::Record {
                conversation_id,
                record,
            } if record.conversation_id() == *conversation_id => Ok((*conversation_id, record)),
            Self::Absent | Self::Record { .. } => Err(StorageRestoreError::StoredEdgeProvenance),
        }
    }

    fn record_for(
        &self,
        expected_conversation_id: ConversationId,
    ) -> Result<&ValidatedMarkerRecord, StorageRestoreError> {
        let (conversation_id, record) = self.require_record()?;
        if conversation_id == expected_conversation_id {
            Ok(record)
        } else {
            Err(StorageRestoreError::StoredEdgeProvenance)
        }
    }
}

/// Marker-backed cursor provenance retaining its exact delivery predecessor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MarkerCursorProgressRestore {
    /// Conversation key under which the cursor witness is stored.
    pub conversation_id: ConversationId,
    /// Cursor witness participant.
    pub participant_id: ParticipantId,
    /// Cursor witness binding epoch.
    pub binding_epoch: BindingEpoch,
    /// Required cumulative cursor boundary.
    pub through_seq: DeliverySeq,
    /// Exact marker accepted by this cursor witness.
    pub marker_delivery_seq: DeliverySeq,
    /// Exact predecessor delivery proof.
    pub delivery: MarkerDeliveryRestore,
}

impl MarkerCursorProgressRestore {
    fn restore_with_debt(
        self,
        debt: ClosureDebt,
        record_authority: &ValidatedMarkerRecord,
        target: MarkerRecordTarget,
    ) -> Result<ParticipantCursorProgress, StorageRestoreError> {
        if self.participant_id != self.delivery.participant_id
            || self.binding_epoch != self.delivery.binding_epoch
            || self.marker_delivery_seq != self.delivery.marker_delivery_seq
            || self.through_seq != self.marker_delivery_seq
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        let marker = self.delivery.restore_with_target(
            self.conversation_id,
            record_authority,
            target,
            MarkerRecordOccurrence::Delivered,
        )?;
        let state = marker
            .delivered(
                debt,
                Event::marker_delivered(
                    self.participant_id,
                    self.binding_epoch,
                    self.marker_delivery_seq,
                ),
            )
            .map_err(|_| StorageRestoreError::StoredEdgeProvenance)?;
        match state {
            ClosureState::Owed {
                edge: StoredEdge::ParticipantCursorProgress(progress),
                ..
            } => Ok(progress),
            ClosureState::Clear | ClosureState::Owed { .. } => {
                Err(StorageRestoreError::StoredEdgeProvenance)
            }
        }
    }
}

/// Marker-backed detached credential-recovery provenance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DetachedCredentialRecoveryRestore {
    /// Detached participant.
    pub participant_id: ParticipantId,
    /// Delivered recovery marker.
    pub marker_delivery_seq: DeliverySeq,
    /// Dead binding epoch that received the marker.
    pub prior_binding_epoch: BindingEpoch,
    /// Floor measured by the binding-fate transaction that selected DCR.
    pub resulting_floor: DeliverySeq,
    /// Exact committed or pending terminal proving the binding fate occurred.
    pub terminal: BindingFateTerminalRestore,
    /// Exact marker-backed cursor predecessor.
    pub progress: MarkerCursorProgressRestore,
}

impl DetachedCredentialRecoveryRestore {
    fn restore_with_debt(
        self,
        debt: ClosureDebt,
        record_authority: &ValidatedMarkerRecord,
    ) -> Result<DetachedCredentialRecovery, StorageRestoreError> {
        if self.participant_id != self.progress.participant_id
            || self.marker_delivery_seq != self.progress.marker_delivery_seq
            || self.prior_binding_epoch != self.progress.binding_epoch
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        let terminal = self.terminal.restore()?;
        if terminal.participant_id() != self.participant_id
            || terminal.binding_epoch() != self.prior_binding_epoch
            || terminal.conversation_id() != self.progress.conversation_id
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        let progress = self.progress.restore_with_debt(
            debt,
            record_authority,
            MarkerRecordTarget::Detached,
        )?;
        let successor = progress
            .binding_fate(
                debt,
                Event::binding_fate_observed(
                    self.participant_id,
                    self.prior_binding_epoch,
                    self.resulting_floor,
                ),
            )
            .map_err(|_| StorageRestoreError::StoredEdgeProvenance)?;
        match successor.into_stored_edge() {
            StoredEdge::DetachedCredentialRecovery(edge) => Ok(edge),
            _ => Err(StorageRestoreError::StoredEdgeProvenance),
        }
    }
}

/// Undelivered-marker release provenance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DetachedMarkerReleaseRestore {
    /// Conversation key under which the release is stored.
    pub conversation_id: ConversationId,
    /// Detached participant.
    pub participant_id: ParticipantId,
    /// Undelivered marker sequence.
    pub marker_delivery_seq: DeliverySeq,
    /// Dead binding epoch.
    pub last_dead_binding_epoch: BindingEpoch,
    /// Floor measured by the binding-fate transaction that selected DMR.
    pub resulting_floor: DeliverySeq,
    /// Exact committed or pending terminal proving the binding fate occurred.
    pub terminal: BindingFateTerminalRestore,
    /// Exact undelivered marker predecessor.
    pub delivery: MarkerDeliveryRestore,
}

impl DetachedMarkerReleaseRestore {
    fn restore_with_debt(
        self,
        debt: ClosureDebt,
        record_authority: &ValidatedMarkerRecord,
    ) -> Result<DetachedMarkerRelease, StorageRestoreError> {
        if self.participant_id != self.delivery.participant_id
            || self.marker_delivery_seq != self.delivery.marker_delivery_seq
            || self.last_dead_binding_epoch != self.delivery.binding_epoch
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        let terminal = self.terminal.restore()?;
        if terminal.participant_id() != self.participant_id
            || terminal.binding_epoch() != self.last_dead_binding_epoch
            || terminal.conversation_id() != self.conversation_id
        {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        }
        let marker = self
            .delivery
            .restore_detached(self.conversation_id, record_authority)?;
        let state = marker
            .binding_fate(
                debt,
                Event::binding_fate_observed(
                    self.participant_id,
                    self.last_dead_binding_epoch,
                    self.resulting_floor,
                ),
            )
            .map_err(|_| StorageRestoreError::StoredEdgeProvenance)?;
        match state {
            ClosureState::Owed {
                edge: StoredEdge::DetachedMarkerRelease(edge),
                ..
            } => Ok(edge),
            ClosureState::Clear | ClosureState::Owed { .. } => {
                Err(StorageRestoreError::StoredEdgeProvenance)
            }
        }
    }
}

/// Exact ordinary-binding fate provenance for cursor release.
///
/// Raw fields are deliberately not independently restorable. The participant's
/// total snapshot must first prove its unfenced binding origin.
///
/// ```compile_fail
/// use liminal_protocol::lifecycle::OrdinaryBindingFateRestore;
///
/// fn bypass(raw: OrdinaryBindingFateRestore) {
///     let _ = raw.restore();
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OrdinaryBindingFateRestore {
    /// Ordinary-attach authority that owned the no-marker cursor.
    pub authority: OrdinaryBindingAuthorityRestore,
    /// Exact committed `Died` terminal for that authority.
    pub terminal: CommittedBindingTerminalRestore,
    /// Floor measured in the binding-fate transaction.
    pub resulting_floor: DeliverySeq,
}

impl OrdinaryBindingFateRestore {
    /// Validates the ordinary attach and exact committed-death provenance.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::StoredEdgeProvenance`] unless the terminal
    /// is a `Died` terminal for the exact participant, conversation, and epoch.
    fn restore_with_origin(
        self,
        origin: &BindingOrigin,
    ) -> Result<OrdinaryBindingFate, StorageRestoreError> {
        let authority = self.authority.restore_with_origin(origin)?;
        let terminal = self.terminal.restore()?;
        let CommittedBindingTerminal::Died(terminal) = terminal else {
            return Err(StorageRestoreError::StoredEdgeProvenance);
        };
        authority
            .binding_fate(terminal, self.resulting_floor)
            .map_err(|_| StorageRestoreError::StoredEdgeProvenance)
    }
}

/// Raw durable successor class accepted by detached Leave or fenced attach.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DebtCompletionRestore {
    /// Debt cleared completely.
    Clear,
    /// Nonzero debt with an independent observer-projection successor.
    ObserverProjection {
        /// Raw nonzero debt vector.
        debt: WideResourceVector,
        /// Projection boundary.
        through_seq: DeliverySeq,
    },
    /// Nonzero debt with an independent physical-compaction successor.
    PhysicalCompaction {
        /// Raw nonzero debt vector.
        debt: WideResourceVector,
        /// First sequence in the compaction range.
        from_floor: DeliverySeq,
        /// Inclusive compaction boundary.
        through_seq: DeliverySeq,
    },
}

impl DebtCompletionRestore {
    /// Validates and rebuilds the restricted clear/OP/PC successor.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError`] for zero debt or an inverted compaction range.
    pub fn restore(self) -> Result<DebtCompletion, StorageRestoreError> {
        match self {
            Self::Clear => Ok(DebtCompletion::clear()),
            Self::ObserverProjection { debt, through_seq } => {
                let debt = ClosureDebt::new(debt).ok_or(StorageRestoreError::ClosureDebt)?;
                Ok(DebtCompletion::observer_projection(
                    debt,
                    ObserverProjection::new(through_seq),
                ))
            }
            Self::PhysicalCompaction {
                debt,
                from_floor,
                through_seq,
            } => {
                let debt = ClosureDebt::new(debt).ok_or(StorageRestoreError::ClosureDebt)?;
                let edge = PhysicalCompaction::new(from_floor, through_seq)
                    .ok_or(StorageRestoreError::StoredEdgeProvenance)?;
                Ok(DebtCompletion::physical_compaction(debt, edge))
            }
        }
    }
}

/// Complete predecessor and event fields for a committed fenced attach.
///
/// Raw fields remain serializable, but their executable restoration entry point
/// is crate-private. Public callers cannot combine them with an occurrence token
/// obtained from another transition.
///
/// ```compile_fail
/// use liminal_protocol::lifecycle::FencedAttachCommitRestore;
///
/// fn bypass() {
///     let _ = FencedAttachCommitRestore::restore;
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FencedAttachCommitRestore {
    /// Exact DCR predecessor.
    pub predecessor: DetachedCredentialRecoveryRestore,
    /// Raw nonzero debt carried by the DCR predecessor.
    pub predecessor_debt: WideResourceVector,
    /// Event participant; must equal the DCR owner.
    pub participant_id: ParticipantId,
    /// Event marker; must equal the DCR recovery marker.
    pub marker_delivery_seq: DeliverySeq,
    /// Event prior epoch; must equal the DCR prior epoch.
    pub prior_binding_epoch: BindingEpoch,
    /// Newly committed immediately-next binding epoch.
    pub new_binding_epoch: BindingEpoch,
    /// Floor measured by the fenced-attach transaction.
    pub resulting_floor: DeliverySeq,
    /// Restricted post-attach closure state.
    pub successor: DebtCompletionRestore,
}

impl FencedAttachCommitRestore {
    /// Replays validation from the exact DCR predecessor to the fenced commit.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError`] for any participant, marker, epoch,
    /// generation, debt, or successor mismatch.
    #[cfg(test)]
    pub(super) fn restore(
        self,
        record_authority: ValidatedMarkerRecord,
    ) -> Result<FencedAttachCommit, StorageRestoreError> {
        let restored = self.restore_with_record(&record_authority);
        record_authority.consume();
        restored
    }

    fn restore_with_record(
        self,
        record_authority: &ValidatedMarkerRecord,
    ) -> Result<FencedAttachCommit, StorageRestoreError> {
        let debt =
            ClosureDebt::new(self.predecessor_debt).ok_or(StorageRestoreError::ClosureDebt)?;
        let predecessor = self.predecessor.restore_with_debt(debt, record_authority)?;
        predecessor
            .fenced_attach(
                debt,
                Event::fenced_recovery_committed(
                    self.participant_id,
                    self.marker_delivery_seq,
                    self.prior_binding_epoch,
                    self.new_binding_epoch,
                    self.resulting_floor,
                ),
                self.successor.restore()?,
            )
            .map_err(|_| StorageRestoreError::StoredEdgeProvenance)
    }
}

/// Complete fenced-attach predecessor for a recovered binding-fate authority.
///
/// ```compile_fail
/// use liminal_protocol::lifecycle::RecoveredBindingFateRestore;
///
/// fn bypass() {
///     let _ = RecoveredBindingFateRestore::restore;
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RecoveredBindingFateRestore {
    /// Exact fenced-attach commit that installed the recovered epoch.
    pub fenced_attach: FencedAttachCommitRestore,
    /// Fate event participant.
    pub participant_id: ParticipantId,
    /// Fate event epoch.
    pub binding_epoch: BindingEpoch,
    /// Floor measured in the fate transaction.
    pub resulting_floor: DeliverySeq,
}

impl RecoveredBindingFateRestore {
    /// Replays the fenced commit and validates exact recovered-epoch fate.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::StoredEdgeProvenance`] for a wrong
    /// participant/epoch or a fenced attach whose successor was already clear.
    #[cfg(test)]
    pub(super) fn restore(
        self,
        record_authority: ValidatedMarkerRecord,
    ) -> Result<RecoveredBindingFate, StorageRestoreError> {
        let restored = self.restore_with_record(&record_authority);
        record_authority.consume();
        restored
    }

    fn restore_with_record(
        self,
        record_authority: &ValidatedMarkerRecord,
    ) -> Result<RecoveredBindingFate, StorageRestoreError> {
        let commit = self.fenced_attach.restore_with_record(record_authority)?;
        commit
            .recovered_binding_fate(Event::binding_fate_observed(
                self.participant_id,
                self.binding_epoch,
                self.resulting_floor,
            ))
            .map_err(|_| StorageRestoreError::StoredEdgeProvenance)
    }
}

/// Durable latent cursor-release suffix while an OP/PC predecessor remains stored.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingRecoveredCursorReleaseRestore {
    /// Exact fenced-attach and recovered-fate predecessor.
    pub fate: RecoveredBindingFateRestore,
    /// Raw nonzero debt remaining after the fate transaction.
    pub resulting_debt: WideResourceVector,
}

impl PendingRecoveredCursorReleaseRestore {
    /// Rebuilds the latent suffix only when the exact OP/PC remains current.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError`] if provenance mismatches or the fate
    /// covers physical compaction immediately instead of leaving it pending.
    #[cfg(test)]
    pub(super) fn restore(
        self,
        record_authority: ValidatedMarkerRecord,
    ) -> Result<PendingRecoveredCursorRelease, StorageRestoreError> {
        let restored = self.restore_with_record(&record_authority);
        record_authority.consume();
        restored
    }

    fn restore_with_record(
        self,
        record_authority: &ValidatedMarkerRecord,
    ) -> Result<PendingRecoveredCursorRelease, StorageRestoreError> {
        let authority = self.fate.restore_with_record(record_authority)?;
        let predecessor_state = authority.predecessor_state();
        let resulting_debt =
            ClosureDebt::new(self.resulting_debt).ok_or(StorageRestoreError::ClosureDebt)?;
        let transition = match predecessor_state {
            ClosureState::Owed {
                debt,
                edge: StoredEdge::ObserverProjection(edge),
            } => edge.apply_recovered_binding_fate(debt, resulting_debt, authority),
            ClosureState::Owed {
                debt,
                edge: StoredEdge::PhysicalCompaction(edge),
            } => edge.apply_recovered_binding_fate(debt, resulting_debt, authority),
            ClosureState::Clear | ClosureState::Owed { .. } => {
                return Err(StorageRestoreError::StoredEdgeProvenance);
            }
        }
        .map_err(|_| StorageRestoreError::StoredEdgeProvenance)?;
        match transition {
            RecoveredBindingFateTransition::PendingStorage(pending) => Ok(pending),
            RecoveredBindingFateTransition::DetachedCursorRelease(_) => {
                Err(StorageRestoreError::StoredEdgeProvenance)
            }
        }
    }
}

/// Exact completion event consuming a latent OP/PC predecessor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecoveredStorageCompletionRestore {
    /// Observer projection completed through this boundary.
    ObserverProjection {
        /// Completion boundary.
        through_seq: DeliverySeq,
        /// Remaining debt, or `None` when closure clears.
        resulting_debt: Option<WideResourceVector>,
    },
    /// Physical compaction completed this exact range.
    PhysicalCompaction {
        /// First compacted sequence.
        from_floor: DeliverySeq,
        /// Inclusive compaction boundary.
        through_seq: DeliverySeq,
        /// Resulting first-retained floor.
        resulting_floor: DeliverySeq,
        /// Remaining debt, or `None` when closure clears.
        resulting_debt: Option<WideResourceVector>,
    },
}

impl RecoveredStorageCompletionRestore {
    fn restore(
        self,
        pending: PendingRecoveredCursorRelease,
    ) -> Result<ClosureState, StorageRestoreError> {
        let current = pending.current_state();
        match (current, self) {
            (
                ClosureState::Owed {
                    edge: StoredEdge::ObserverProjection(edge),
                    ..
                },
                Self::ObserverProjection {
                    through_seq,
                    resulting_debt,
                },
            ) => edge
                .complete_after_recovered_binding_fate(
                    Event::projection_completed(through_seq),
                    optional_debt(resulting_debt)?,
                    pending,
                )
                .map_err(|_| StorageRestoreError::StoredEdgeProvenance),
            (
                ClosureState::Owed {
                    edge: StoredEdge::PhysicalCompaction(edge),
                    ..
                },
                Self::PhysicalCompaction {
                    from_floor,
                    through_seq,
                    resulting_floor,
                    resulting_debt,
                },
            ) => {
                let event = Event::compaction_completed(from_floor, through_seq, resulting_floor)
                    .ok_or(StorageRestoreError::StoredEdgeProvenance)?;
                edge.complete_after_recovered_binding_fate(
                    event,
                    optional_debt(resulting_debt)?,
                    pending,
                )
                .map_err(|_| StorageRestoreError::StoredEdgeProvenance)
            }
            _ => Err(StorageRestoreError::StoredEdgeProvenance),
        }
    }
}

/// Provenance alternatives capable of constructing `DetachedCursorRelease`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DetachedCursorReleaseProvenanceRestore {
    /// Direct release from an exact ordinary binding death.
    Ordinary(OrdinaryBindingFateRestore),
    /// Recovered fate immediately covered physical compaction.
    RecoveredDirect {
        /// Exact fenced-attach recovered fate.
        fate: RecoveredBindingFateRestore,
        /// Raw nonzero debt carried by the release.
        resulting_debt: WideResourceVector,
    },
    /// Recovered fate remained latent until exact OP/PC completion.
    RecoveredAfterStorage {
        /// Exact latent suffix capsule.
        pending: PendingRecoveredCursorReleaseRestore,
        /// Exact storage completion consuming the predecessor.
        completion: RecoveredStorageCompletionRestore,
    },
}

impl DetachedCursorReleaseProvenanceRestore {
    const fn ordinary_binding_request(self) -> Option<ActiveBinding> {
        match self {
            Self::Ordinary(fate) => Some(fate.authority.binding),
            Self::RecoveredDirect { .. } | Self::RecoveredAfterStorage { .. } => None,
        }
    }

    const fn marker_record_request(self) -> Option<MarkerRecordRequest> {
        match self {
            Self::Ordinary(_) => None,
            Self::RecoveredDirect { fate, .. } => Some(MarkerRecordRequest::recovered(
                fate.participant_id,
                fate.fenced_attach.marker_delivery_seq,
                fate.fenced_attach.prior_binding_epoch,
                fate.fenced_attach.new_binding_epoch,
            )),
            Self::RecoveredAfterStorage { pending, .. } => Some(MarkerRecordRequest::recovered(
                pending.fate.participant_id,
                pending.fate.fenced_attach.marker_delivery_seq,
                pending.fate.fenced_attach.prior_binding_epoch,
                pending.fate.fenced_attach.new_binding_epoch,
            )),
        }
    }

    fn restore_state(
        self,
        debt: ClosureDebt,
        marker_authority: &MarkerRestoreAuthority<'_>,
        ordinary_origin: Option<&BindingOrigin>,
    ) -> Result<ClosureState, StorageRestoreError> {
        match self {
            Self::Ordinary(provenance) => {
                marker_authority.require_absent()?;
                let origin = ordinary_origin.ok_or(StorageRestoreError::StoredEdgeProvenance)?;
                Ok(provenance
                    .restore_with_origin(origin)?
                    .into_direct_state(debt))
            }
            Self::RecoveredDirect {
                fate,
                resulting_debt,
            } => {
                let (_, record_authority) = marker_authority.require_record()?;
                let authority = fate.restore_with_record(record_authority)?;
                let predecessor = authority.predecessor_state();
                let resulting_debt =
                    ClosureDebt::new(resulting_debt).ok_or(StorageRestoreError::ClosureDebt)?;
                let transition = match predecessor {
                    ClosureState::Owed {
                        debt: predecessor_debt,
                        edge: StoredEdge::PhysicalCompaction(edge),
                    } => edge.apply_recovered_binding_fate(
                        predecessor_debt,
                        resulting_debt,
                        authority,
                    ),
                    ClosureState::Clear | ClosureState::Owed { .. } => {
                        return Err(StorageRestoreError::StoredEdgeProvenance);
                    }
                }
                .map_err(|_| StorageRestoreError::StoredEdgeProvenance)?;
                match transition {
                    RecoveredBindingFateTransition::DetachedCursorRelease(release)
                        if release.debt() == debt =>
                    {
                        Ok(release.into_state())
                    }
                    RecoveredBindingFateTransition::PendingStorage(_)
                    | RecoveredBindingFateTransition::DetachedCursorRelease(_) => {
                        Err(StorageRestoreError::StoredEdgeProvenance)
                    }
                }
            }
            Self::RecoveredAfterStorage {
                pending,
                completion,
            } => {
                let (_, record_authority) = marker_authority.require_record()?;
                let state = completion.restore(pending.restore_with_record(record_authority)?)?;
                match state {
                    ClosureState::Owed {
                        debt: restored_debt,
                        edge: StoredEdge::DetachedCursorRelease(_),
                    } if restored_debt == debt => Ok(state),
                    ClosureState::Clear | ClosureState::Owed { .. } => {
                        Err(StorageRestoreError::StoredEdgeProvenance)
                    }
                }
            }
        }
    }
}

/// Exact seven-kind stored-edge representation with provenance where required.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StoredEdgeRestore {
    /// Observer projection.
    ObserverProjection {
        /// Projection boundary.
        through_seq: DeliverySeq,
    },
    /// Physical compaction.
    PhysicalCompaction {
        /// First compacted sequence.
        from_floor: DeliverySeq,
        /// Inclusive compaction boundary.
        through_seq: DeliverySeq,
    },
    /// Planned exact marker delivery.
    MarkerDelivery(MarkerDeliveryRestore),
    /// Continuous cursor witness carrying ordinary-attach provenance.
    ParticipantCursorProgressContinuous {
        /// Stored edge participant.
        participant_id: ParticipantId,
        /// Stored edge binding epoch.
        binding_epoch: BindingEpoch,
        /// Stored required cursor boundary.
        through_seq: DeliverySeq,
        /// Exact ordinary-attach predecessor.
        authority: OrdinaryBindingAuthorityRestore,
    },
    /// Marker-backed cursor witness carrying delivery provenance.
    ParticipantCursorProgressMarker(MarkerCursorProgressRestore),
    /// Detached credential recovery carrying marker-ack provenance.
    DetachedCredentialRecovery(DetachedCredentialRecoveryRestore),
    /// Detached undelivered-marker release carrying delivery provenance.
    DetachedMarkerRelease(DetachedMarkerReleaseRestore),
    /// Detached cursor release carrying ordinary or fenced provenance.
    DetachedCursorRelease {
        /// Stored edge participant.
        participant_id: ParticipantId,
        /// Stored edge dead binding epoch.
        last_dead_binding_epoch: BindingEpoch,
        /// Provenance path that alone can construct the release.
        provenance: DetachedCursorReleaseProvenanceRestore,
    },
}

impl StoredEdgeRestore {
    const fn ordinary_binding_request(self) -> Option<ActiveBinding> {
        match self {
            Self::ParticipantCursorProgressContinuous { authority, .. } => Some(authority.binding),
            Self::DetachedCursorRelease { provenance, .. } => provenance.ordinary_binding_request(),
            Self::ObserverProjection { .. }
            | Self::PhysicalCompaction { .. }
            | Self::MarkerDelivery(_)
            | Self::ParticipantCursorProgressMarker(_)
            | Self::DetachedCredentialRecovery(_)
            | Self::DetachedMarkerRelease(_) => None,
        }
    }

    const fn marker_record_request(self) -> Option<MarkerRecordRequest> {
        match self {
            Self::MarkerDelivery(value) => Some(MarkerRecordRequest::planned(
                value.participant_id,
                value.marker_delivery_seq,
                super::FrontierBinding::Bound(value.binding_epoch),
            )),
            Self::ParticipantCursorProgressMarker(value) => Some(MarkerRecordRequest::delivered(
                value.participant_id,
                value.marker_delivery_seq,
                super::FrontierBinding::Bound(value.binding_epoch),
            )),
            Self::DetachedCredentialRecovery(value) => Some(MarkerRecordRequest::delivered(
                value.participant_id,
                value.marker_delivery_seq,
                super::FrontierBinding::Detached(value.prior_binding_epoch),
            )),
            Self::DetachedMarkerRelease(value) => Some(MarkerRecordRequest::planned(
                value.participant_id,
                value.marker_delivery_seq,
                super::FrontierBinding::Detached(value.last_dead_binding_epoch),
            )),
            Self::DetachedCursorRelease { provenance, .. } => provenance.marker_record_request(),
            Self::ObserverProjection { .. }
            | Self::PhysicalCompaction { .. }
            | Self::ParticipantCursorProgressContinuous { .. } => None,
        }
    }

    fn restore_with_debt(
        self,
        debt: ClosureDebt,
        marker_authority: &MarkerRestoreAuthority<'_>,
        ordinary_origin: Option<&BindingOrigin>,
    ) -> Result<StoredEdge, StorageRestoreError> {
        match self {
            Self::ObserverProjection { through_seq } => {
                marker_authority.require_absent()?;
                Ok(StoredEdge::ObserverProjection(ObserverProjection::new(
                    through_seq,
                )))
            }
            Self::PhysicalCompaction {
                from_floor,
                through_seq,
            } => {
                marker_authority.require_absent()?;
                PhysicalCompaction::new(from_floor, through_seq)
                    .map(StoredEdge::PhysicalCompaction)
                    .ok_or(StorageRestoreError::StoredEdgeProvenance)
            }
            Self::MarkerDelivery(value) => {
                let (conversation_id, record_authority) = marker_authority.require_record()?;
                value
                    .restore_with_target(
                        conversation_id,
                        record_authority,
                        MarkerRecordTarget::Bound,
                        MarkerRecordOccurrence::Undelivered,
                    )
                    .map(StoredEdge::MarkerDelivery)
            }
            Self::ParticipantCursorProgressContinuous {
                participant_id,
                binding_epoch,
                through_seq,
                authority,
            } => {
                marker_authority.require_absent()?;
                let origin = ordinary_origin.ok_or(StorageRestoreError::StoredEdgeProvenance)?;
                ParticipantCursorProgress::restore_continuous(
                    authority.restore_with_origin(origin)?,
                    participant_id,
                    binding_epoch,
                    through_seq,
                )
                .map(StoredEdge::ParticipantCursorProgress)
                .ok_or(StorageRestoreError::StoredEdgeProvenance)
            }
            Self::ParticipantCursorProgressMarker(value) => {
                let record_authority = marker_authority.record_for(value.conversation_id)?;
                value
                    .restore_with_debt(debt, record_authority, MarkerRecordTarget::Bound)
                    .map(StoredEdge::ParticipantCursorProgress)
            }
            Self::DetachedCredentialRecovery(value) => {
                let record_authority =
                    marker_authority.record_for(value.progress.conversation_id)?;
                value
                    .restore_with_debt(debt, record_authority)
                    .map(StoredEdge::DetachedCredentialRecovery)
            }
            Self::DetachedMarkerRelease(value) => {
                let record_authority = marker_authority.record_for(value.conversation_id)?;
                value
                    .restore_with_debt(debt, record_authority)
                    .map(StoredEdge::DetachedMarkerRelease)
            }
            Self::DetachedCursorRelease {
                participant_id,
                last_dead_binding_epoch,
                provenance,
            } => {
                let state = provenance.restore_state(debt, marker_authority, ordinary_origin)?;
                match state {
                    ClosureState::Owed {
                        edge: StoredEdge::DetachedCursorRelease(edge),
                        ..
                    } if edge.participant_id() == participant_id
                        && edge.last_dead_binding_epoch() == last_dead_binding_epoch =>
                    {
                        Ok(StoredEdge::DetachedCursorRelease(edge))
                    }
                    ClosureState::Clear | ClosureState::Owed { .. } => {
                        Err(StorageRestoreError::StoredEdgeProvenance)
                    }
                }
            }
        }
    }
}

/// Raw closure state; a stored edge always carries a raw nonzero debt vector.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClosureStateRestore {
    /// No edge and zero debt.
    Clear,
    /// One exact stored edge and raw componentwise debt.
    Owed {
        /// Raw debt, validated nonzero during restoration.
        debt: WideResourceVector,
        /// Exact edge and required predecessor provenance.
        edge: StoredEdgeRestore,
    },
}

impl ClosureStateRestore {
    const fn ordinary_binding_request(self) -> Option<ActiveBinding> {
        match self {
            Self::Clear => None,
            Self::Owed { edge, .. } => edge.ordinary_binding_request(),
        }
    }

    const fn marker_record_request(self) -> Option<MarkerRecordRequest> {
        match self {
            Self::Clear => None,
            Self::Owed { edge, .. } => edge.marker_record_request(),
        }
    }

    /// Validates and rebuilds one closure state.
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError`] for zero owed debt, an invalid range, or
    /// any opaque edge whose supplied predecessor provenance does not match.
    pub fn restore(self) -> Result<ClosureState, StorageRestoreError> {
        self.restore_with_authority(&MarkerRestoreAuthority::Absent, None)
    }

    /// Restores exactly one marker-derived edge after claim/log prevalidation.
    ///
    /// The marker token is conversation-bound and fixes whether its current
    /// target is live (`MarkerDelivery`/marker PCP) or detached (DMR/DCR and
    /// recovered cursor-release history).
    ///
    /// # Errors
    ///
    /// Returns [`StorageRestoreError::StoredEdgeProvenance`] when the raw edge
    /// is not marker-derived, the token belongs to another conversation, or
    /// the retained record has the wrong target state, epoch, participant, or
    /// delivery sequence.
    pub(super) fn restore_with_marker_record(
        self,
        conversation_id: ConversationId,
        record: ValidatedMarkerRecord,
    ) -> Result<ClosureState, StorageRestoreError> {
        let restored = self.restore_with_authority(
            &MarkerRestoreAuthority::Record {
                conversation_id,
                record: &record,
            },
            None,
        );
        record.consume();
        restored
    }

    fn restore_with_binding_origin(
        self,
        origin: &BindingOrigin,
    ) -> Result<ClosureState, StorageRestoreError> {
        self.restore_with_authority(&MarkerRestoreAuthority::Absent, Some(origin))
    }

    fn restore_with_authority(
        self,
        marker_authority: &MarkerRestoreAuthority<'_>,
        ordinary_origin: Option<&BindingOrigin>,
    ) -> Result<ClosureState, StorageRestoreError> {
        match self {
            Self::Clear => {
                marker_authority.require_absent()?;
                Ok(ClosureState::Clear)
            }
            Self::Owed { debt, edge } => {
                let debt = ClosureDebt::new(debt).ok_or(StorageRestoreError::ClosureDebt)?;
                Ok(ClosureState::Owed {
                    debt,
                    edge: edge.restore_with_debt(debt, marker_authority, ordinary_origin)?,
                })
            }
        }
    }
}

fn optional_debt(
    raw: Option<WideResourceVector>,
) -> Result<Option<ClosureDebt>, StorageRestoreError> {
    raw.map(|value| ClosureDebt::new(value).ok_or(StorageRestoreError::ClosureDebt))
        .transpose()
}