liminal-protocol 0.14.0

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
//! Pins for the lifecycle capsule's participants, frontiers and closure
//! sections: a live conversation describes itself and restores to itself, the
//! capsule round-trips it with and without the fenced-marker latch, a restored
//! latch refuses a second fenced take exactly as the live one does, a carried
//! latch no live take set is refused at restore, and every new refusal is
//! named.

use alloc::{vec, vec::Vec};

use proptest::prelude::*;

use crate::algebra::WideResourceVector;
use crate::wire::{AttachSecret, BindingEpoch, CloseCause};

use super::checkpoint::DigestParticipantView;
use super::checkpoint_codec::{DigestDescription, decode_description, encode_description};
use super::claim_frontier_tests::detached_dcr_fixture;
use super::conversation_tests::{CONVERSATION_ID as SHELL_CONVERSATION_ID, build_operation};
use super::storage::{ParticipantConversationDescription, describe_conversation};
use super::storage_tests::{
    PARTICIPANT_ID, binding, died_terminal, enrollment_bound_snapshot, epoch,
    ordinary_bound_conversation, ordinary_detached_conversation, owed,
    recovered_bound_with_active_quartet, recovered_conversation, replayed_enrollment_commit,
};
use super::{
    ActiveBinding, AttachedLifecycleRecord, AttachedRecordPosition, BindingFateTerminalRestore,
    BindingOrigin, BindingState, BindingStateRestore, CapsuleCaptureError, CapsuleDecodeError,
    CapsuleRestoreError, ClaimFrontiers, ClosureState, ClosureStateRestore,
    CommittedBindingTerminal, CommittedBindingTerminalRestore, ConversationDecision,
    ConversationDescribeError, ConversationGenesis, ConversationLifecycleView,
    ConversationStateRestoreError, DetachCellRestore, DetachedCredentialRecovery,
    DetachedCredentialRecoveryRestore, DetachedCursorReleaseProvenanceRestore,
    EnrollmentFingerprint, FrontierBinding, LifecycleCapsule, LifecycleView, LiveIdentityRestore,
    MarkerCursorProgressRestore, MarkerDeliveryRestore, OrdinaryBindingAuthorityRestore,
    OrdinaryBindingFateRestore, ParticipantConversation, ParticipantConversationRestore,
    ParticipantLifecycleRestore, RestoredParticipantLifecycle, StorageRestoreError, StoredEdge,
    StoredEdgeRestore,
};

type Digest = crate::wire::CredentialDigest;
type DigestRestore<D> = ParticipantConversationRestore<D, D, D, D>;
type DigestParticipant<D> = RestoredParticipantLifecycle<D, D, D, D>;

/// The detached participant of the recovery fixture.
const PARTICIPANT: u64 = 0;
/// The recovery fixture's delivered marker.
const MARKER: u64 = 1;

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// A whole detached-credential-recovery conversation: participant 0 died on
/// its one epoch after a marker was delivered to it, and the closure stands
/// on the recovery that delivery and that death selected. Built for any
/// conversation, so it can sit under any shell.
fn dcr_restore(conversation_id: u64) -> Result<DigestRestore<Digest>, &'static str> {
    let (mut frontiers, sequence_ledger, order_ledger, _, binding_epoch) = detached_dcr_fixture()?;
    frontiers.conversation_id = conversation_id;
    for fact in &mut frontiers.historical_marker_deliveries {
        fact.conversation_id = conversation_id;
    }
    let ended = ActiveBinding {
        participant_id: PARTICIPANT,
        conversation_id,
        binding_epoch,
    };
    let terminal = CommittedBindingTerminalRestore {
        binding: ended,
        cause: CloseCause::ConnectionLost,
        transaction_order: 1,
        delivery_seq: 2,
    };
    let delivery = MarkerDeliveryRestore {
        participant_id: PARTICIPANT,
        binding_epoch,
        marker_delivery_seq: MARKER,
    };
    Ok(ParticipantConversationRestore {
        participants: vec![ParticipantLifecycleRestore::Live {
            identity: LiveIdentityRestore {
                participant_id: PARTICIPANT,
                conversation_id,
                generation: binding_epoch.capability_generation,
                attach_secret: AttachSecret::new([0xA1; 32]),
                cursor: 0,
                enrollment_fingerprint: EnrollmentFingerprint::new(Digest::new([0xE1; 32])),
                latest_terminal: Some(terminal),
            },
            binding: BindingStateRestore::Detached,
            binding_origin: Some(BindingOrigin::unfenced(
                AttachedLifecycleRecord::from_binding(ended, AttachedRecordPosition::new(0, 0)),
            )),
            detach_cell: DetachCellRestore::Empty,
        }],
        frontiers,
        sequence_ledger,
        order_ledger,
        closure: ClosureStateRestore::Owed {
            debt: WideResourceVector::new(1, 1),
            edge: StoredEdgeRestore::DetachedCredentialRecovery(
                DetachedCredentialRecoveryRestore {
                    participant_id: PARTICIPANT,
                    marker_delivery_seq: MARKER,
                    prior_binding_epoch: binding_epoch,
                    resulting_floor: 1,
                    terminal: BindingFateTerminalRestore::Committed(terminal),
                    progress: MarkerCursorProgressRestore {
                        conversation_id,
                        participant_id: PARTICIPANT,
                        binding_epoch,
                        through_seq: MARKER,
                        marker_delivery_seq: MARKER,
                        delivery,
                    },
                },
            ),
        },
    })
}

/// The live values a binding would hold for the recovery conversation.
struct LiveDcr {
    participants: Vec<DigestParticipant<Digest>>,
    frontiers: ClaimFrontiers,
    closure: ClosureState,
    recovery: DetachedCredentialRecovery,
    retained_record_limit: u64,
}

/// Restores the recovery conversation and, when `latched`, takes its one
/// fenced marker as a fenced attach mint would, setting the issuance latch.
fn live_dcr(conversation_id: u64, latched: bool) -> Result<LiveDcr, &'static str> {
    let restore = dcr_restore(conversation_id)?;
    let retained_record_limit = restore.frontiers.retained_record_limit;
    let (participants, mut frontiers, closure) = restore
        .restore()
        .map_err(|_| "the joint recovery conversation restores")?
        .into_parts();
    let ClosureState::Owed {
        edge: StoredEdge::DetachedCredentialRecovery(recovery),
        ..
    } = closure
    else {
        return Err("the recovery conversation stands on its recovery");
    };
    if latched {
        frontiers
            .take_fenced_marker_record(recovery)
            .ok_or("the recovery takes its one fenced marker")?
            .consume();
    }
    Ok(LiveDcr {
        participants,
        frontiers,
        closure,
        recovery,
        retained_record_limit,
    })
}

/// A shell whose genesis validation committed.
fn validated_shell(conversation_id: u64) -> Result<ParticipantConversation, &'static str> {
    let fresh = ParticipantConversation::from_genesis(ConversationGenesis::new(conversation_id));
    let ConversationDecision::Commit(commit) = fresh.decide_genesis_validation() else {
        return Err("a fresh genesis selects its one-shot event");
    };
    Ok(commit.commit())
}

/// The shell after its genesis and the generated operations, through the live
/// path exactly as `any_prefix_replay_produces_a_valid_shell_state` builds it.
fn shell_after(operations: &[(u8, [u64; 5])]) -> Result<ParticipantConversation, &'static str> {
    let mut shell = validated_shell(SHELL_CONVERSATION_ID)?;
    for &(kind, values) in operations {
        let ConversationDecision::Commit(commit) =
            shell.decide_operation(build_operation(kind, values))
        else {
            return Err("a validated shell accepts every same-conversation operation");
        };
        shell = commit.commit();
    }
    Ok(shell)
}

/// The joint state a capsule restores.
type RestoredState = super::ParticipantConversationState<Digest, Digest, Digest, Digest>;

fn lifecycle_view(live: &LiveDcr) -> ConversationLifecycleView<'_> {
    ConversationLifecycleView {
        participants: live
            .participants
            .iter()
            .map(RestoredParticipantLifecycle::view)
            .collect(),
        frontiers: &live.frontiers,
        retained_record_limit: live.retained_record_limit,
        closure: &live.closure,
    }
}

fn capture(
    shell: &ParticipantConversation,
    live: &LiveDcr,
    covered: u64,
) -> Result<LifecycleCapsule, CapsuleCaptureError> {
    LifecycleCapsule::capture(&LifecycleView {
        sealed: None,
        conversation: shell,
        lifecycle: Some(lifecycle_view(live)),
        covered_log_sequence: covered,
    })
}

/// Describes the live recovery conversation, latch included.
fn describe_live(live: &LiveDcr) -> Result<DigestDescription<Digest>, &'static str> {
    let view = lifecycle_view(live);
    describe_conversation(
        &view.participants,
        view.frontiers,
        view.retained_record_limit,
        live.closure,
    )
    .map_err(|_| "the live recovery conversation describes itself")
}

/// The latch a fenced take of the recovery fixture's marker sets.
const fn expected_latch(live: &LiveDcr, latched: bool) -> Option<(u64, u64, BindingEpoch)> {
    if latched {
        Some((PARTICIPANT, MARKER, live.recovery.prior_binding_epoch()))
    } else {
        None
    }
}

/// Capture, encode, decode, restore; asserts the decoded capsule and its
/// bytes are the captured ones, and answers the restored shell and state.
fn capsule_round_trip(
    shell: &ParticipantConversation,
    live: &LiveDcr,
    covered: u64,
) -> Result<(ParticipantConversation, RestoredState), &'static str> {
    let captured = capture(shell, live, covered).map_err(|_| "the live lifecycle captures")?;
    let bytes = captured.encode_canonical();
    let decoded = LifecycleCapsule::decode_canonical(&bytes).map_err(|_| "the capsule decodes")?;
    assert_eq!(
        decoded, captured,
        "decode(encode(capture(x))) == capture(x)"
    );
    assert_eq!(decoded.encode_canonical(), bytes, "the bytes are canonical");
    let restored = decoded.restore().map_err(|_| "the capsule restores")?;
    assert_eq!(restored.covered_log_sequence(), covered);
    let parts = restored.into_parts();
    let lifecycle = parts.lifecycle.ok_or("the lifecycle comes back")?;
    Ok((parts.conversation, lifecycle))
}

/// Splits framed sections into `(tag, body)` pairs.
fn split_sections(mut bytes: &[u8]) -> Result<Vec<(u16, Vec<u8>)>, &'static str> {
    let mut sections = Vec::new();
    while !bytes.is_empty() {
        let tag = u16::from_be_bytes(
            bytes
                .get(0..2)
                .ok_or("tag")?
                .try_into()
                .map_err(|_| "tag width")?,
        );
        let len = u32::from_be_bytes(
            bytes
                .get(2..6)
                .ok_or("length")?
                .try_into()
                .map_err(|_| "length width")?,
        );
        let end = 6 + usize::try_from(len).map_err(|_| "length fits")?;
        sections.push((tag, bytes.get(6..end).ok_or("body")?.to_vec()));
        bytes = bytes.get(end..).ok_or("rest")?;
    }
    Ok(sections)
}

fn frame(tag: u16, body: &[u8]) -> Result<Vec<u8>, &'static str> {
    let mut framed = tag.to_be_bytes().to_vec();
    framed.extend_from_slice(
        &u32::try_from(body.len())
            .map_err(|_| "body fits")?
            .to_be_bytes(),
    );
    framed.extend_from_slice(body);
    Ok(framed)
}

/// A v1.0 capsule for a validated shell at ordinal 1, followed by `sections`.
fn envelope(conversation_id: u64, sections: &[u8]) -> Result<Vec<u8>, &'static str> {
    let mut body = frame(1, &[0, 0, 0, 0, 0, 0, 0, 1, 1])?;
    body.extend_from_slice(sections);
    let mut bytes = b"LPCK".to_vec();
    bytes.extend_from_slice(&1_u16.to_be_bytes());
    bytes.extend_from_slice(&0_u16.to_be_bytes());
    bytes.extend_from_slice(&conversation_id.to_be_bytes());
    bytes.extend_from_slice(&0_u64.to_be_bytes());
    bytes.extend_from_slice(
        &u32::try_from(body.len())
            .map_err(|_| "body fits")?
            .to_be_bytes(),
    );
    bytes.extend(body);
    Ok(bytes)
}

/// The three framed sections of a description, as `(tag, body)` pairs.
fn sections_of(
    description: &DigestDescription<Digest>,
) -> Result<Vec<(u16, Vec<u8>)>, &'static str> {
    split_sections(&encode_description(description).ok_or("the description encodes")?)
}

fn join(sections: &[(u16, Vec<u8>)]) -> Result<Vec<u8>, &'static str> {
    let mut joined = Vec::new();
    for (tag, body) in sections {
        joined.extend(frame(*tag, body)?);
    }
    Ok(joined)
}

fn decode(bytes: &[u8]) -> Option<CapsuleDecodeError> {
    LifecycleCapsule::decode_canonical(bytes).err()
}

/// Asserts one described participant equals the live getters it came from.
fn assert_participant_describes_live<D: PartialEq + Clone + core::fmt::Debug>(
    described: &ParticipantLifecycleRestore<D, D, D, D>,
    live: &DigestParticipant<D>,
) -> Result<(), &'static str> {
    match (described, live) {
        (
            ParticipantLifecycleRestore::Live {
                identity,
                binding,
                binding_origin,
                detach_cell,
            },
            RestoredParticipantLifecycle::Live {
                member,
                binding: live_binding,
                binding_origin: live_origin,
                detach_cell: live_cell,
            },
        ) => {
            assert_eq!(identity.participant_id, member.participant_id());
            assert_eq!(identity.conversation_id, member.conversation_id());
            assert_eq!(identity.generation, member.generation());
            assert_eq!(identity.attach_secret, member.attach_secret());
            assert_eq!(identity.cursor, member.cursor());
            assert_eq!(
                &identity.enrollment_fingerprint,
                member.enrollment_fingerprint()
            );
            assert_eq!(
                identity.latest_terminal,
                member
                    .latest_terminal()
                    .map(CommittedBindingTerminal::storage_description)
            );
            match (binding, live_binding) {
                (BindingStateRestore::Detached, BindingState::Detached) => {}
                (BindingStateRestore::Bound(described), BindingState::Bound(live)) => {
                    assert_eq!(described, live);
                }
                (
                    BindingStateRestore::PendingFinalization(described),
                    BindingState::PendingFinalization(live),
                ) => assert_eq!(*described, live.storage_description()),
                _ => return Err("the described binding slot is another variant"),
            }
            assert_eq!(binding_origin.as_ref(), live_origin.as_ref());
            assert_eq!(detach_cell, &live_cell.storage_description());
        }
        (
            ParticipantLifecycleRestore::Retired(described),
            RestoredParticipantLifecycle::Retired(live),
        ) => {
            assert_eq!(described.participant_id, live.participant_id());
            assert_eq!(described.conversation_id, live.conversation_id());
            assert_eq!(described.retired_generation, live.retired_generation());
            assert_eq!(
                &described.enrollment_fingerprint,
                live.enrollment_fingerprint()
            );
            assert_eq!(described.leave_attempt_token, live.leave_attempt_token());
            assert_eq!(
                &described.leave_request_verifier,
                live.leave_request_verifier()
            );
            assert_eq!(&described.leave_fingerprint, live.leave_fingerprint());
            assert_eq!(
                described.left_transaction_order,
                live.left_admission_order().transaction_order()
            );
            assert_eq!(
                described.committed_result.left_delivery_seq,
                live.committed_result().left_delivery_seq()
            );
        }
        _ => return Err("the described participant is another variant"),
    }
    Ok(())
}

/// Asserts every described field equals the live getter it was taken from.
fn assert_describes_live<D: PartialEq + Clone + core::fmt::Debug>(
    description: &ParticipantConversationDescription<D, D, D, D>,
    participants: &[DigestParticipant<D>],
    frontiers: &ClaimFrontiers,
    closure: ClosureState,
) -> Result<(), &'static str> {
    let restore = &description.restore;
    assert_eq!(restore.participants.len(), participants.len());
    for (described, live) in restore.participants.iter().zip(participants) {
        assert_participant_describes_live(described, live)?;
    }
    let described = &restore.frontiers;
    assert_eq!(described.conversation_id, frontiers.conversation_id());
    assert_eq!(
        described.active_identities.as_slice(),
        frontiers.active_identities().participants()
    );
    assert_eq!(
        described.identity_slot_limit,
        frontiers.identity_slot_limit()
    );
    assert_eq!(described.retained_floor, frontiers.retained_floor());
    assert_eq!(
        described.retained_records.as_slice(),
        frontiers.retained_records()
    );
    assert_eq!(restore.sequence_ledger, frontiers.sequence().ledger());
    assert_eq!(restore.order_ledger, frontiers.order().ledger());
    match (restore.closure, closure) {
        (ClosureStateRestore::Clear, ClosureState::Clear) => Ok(()),
        (ClosureStateRestore::Owed { debt, .. }, ClosureState::Owed { debt: live, .. }) => {
            assert_eq!(debt, live.value());
            Ok(())
        }
        _ => Err("the described closure is another variant"),
    }
}

// ---------------------------------------------------------------------------
// Pin (a): live -> describe -> restore == live
// ---------------------------------------------------------------------------

/// Every whole-conversation fixture `storage_tests` proves restorable, plus
/// the recovery conversation, in the digest width each was written for.
fn storage_fixtures() -> Vec<DigestRestore<[u8; 4]>> {
    let bound_epoch = epoch(2, 8);
    let recovered_epoch = epoch(3, 9);
    let continuous = StoredEdgeRestore::ParticipantCursorProgressContinuous {
        participant_id: PARTICIPANT_ID,
        binding_epoch: bound_epoch,
        through_seq: 12,
        authority: OrdinaryBindingAuthorityRestore {
            binding: binding(PARTICIPANT_ID, bound_epoch),
            through_seq: 12,
        },
    };
    let projection = ClosureStateRestore::Owed {
        debt: WideResourceVector::new(2, 16),
        edge: StoredEdgeRestore::ObserverProjection { through_seq: 14 },
    };
    let compaction = ClosureStateRestore::Owed {
        debt: WideResourceVector::new(2, 16),
        edge: StoredEdgeRestore::PhysicalCompaction {
            from_floor: 12,
            through_seq: 14,
        },
    };
    vec![
        ordinary_bound_conversation(owed(continuous)),
        enrollment_bound_snapshot(&replayed_enrollment_commit(AttachedRecordPosition::new(
            0, 1,
        ))),
        recovered_conversation(
            FrontierBinding::Bound(recovered_epoch),
            Some(bound_epoch),
            projection,
        ),
        recovered_bound_with_active_quartet(Some(bound_epoch), projection),
        recovered_bound_with_active_quartet(Some(bound_epoch), compaction),
    ]
}

#[test]
fn every_restorable_storage_fixture_describes_and_restores_to_itself() -> Result<(), &'static str> {
    for fixture in storage_fixtures() {
        let retained_record_limit = fixture.frontiers.retained_record_limit;
        let live = fixture
            .restore()
            .map_err(|_| "every storage fixture restores")?;
        let description = live
            .describe(retained_record_limit)
            .map_err(|_| "every storage fixture describes itself")?;
        assert_describes_live(
            &description,
            live.participants(),
            live.frontiers(),
            live.closure(),
        )?;
        assert_eq!(description.fenced_marker_issued, None);

        let sections =
            split_sections(&encode_description(&description).ok_or("the description encodes")?)?;
        let [(2, participants), (3, frontiers), (4, closure)] = sections.as_slice() else {
            return Err("three sections in their fixed order");
        };
        let decoded = decode_description::<4, [u8; 4]>(participants, frontiers, closure)
            .map_err(|_| "the encoded description decodes")?;
        assert_eq!(
            decoded, description,
            "the codec round-trips four-byte digests"
        );

        let restored = decoded
            .into_state()
            .map_err(|_| "the described fixture restores")?;
        assert_eq!(restored.participants(), live.participants());
        assert_eq!(restored.frontiers(), live.frontiers());
        assert_eq!(restored.closure(), live.closure());
        assert_eq!(restored, live);
    }
    Ok(())
}

#[test]
fn the_recovery_conversation_describes_its_exact_restore_input() -> Result<(), &'static str> {
    let input = dcr_restore(SHELL_CONVERSATION_ID)?;
    let retained_record_limit = input.frontiers.retained_record_limit;
    let live = input
        .clone()
        .restore()
        .map_err(|_| "the recovery conversation restores")?;
    let description = live
        .describe(retained_record_limit)
        .map_err(|_| "the recovery conversation describes itself")?;
    assert_describes_live(
        &description,
        live.participants(),
        live.frontiers(),
        live.closure(),
    )?;
    assert_eq!(description.restore, input, "the input comes back unchanged");
    assert_eq!(description.fenced_marker_issued, None);
    let restored = description
        .into_state()
        .map_err(|_| "the description restores")?;
    assert_eq!(restored, live);
    Ok(())
}

#[test]
fn a_latched_live_conversation_describes_and_restores_its_latch() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, true)?;
    let description = describe_live(&live)?;
    assert_describes_live(
        &description,
        &live.participants,
        &live.frontiers,
        live.closure,
    )?;
    assert_eq!(
        description.fenced_marker_issued,
        expected_latch(&live, true)
    );
    let restored = description
        .clone()
        .into_state()
        .map_err(|_| "the latched description restores")?;
    assert_eq!(restored.participants(), live.participants.as_slice());
    assert_eq!(
        restored.frontiers(),
        &live.frontiers,
        "the latch is installed"
    );
    assert_eq!(restored.closure(), live.closure);

    let public = description
        .restore
        .restore()
        .map_err(|_| "the public route restores the same input")?;
    assert_ne!(
        public.frontiers(),
        &live.frontiers,
        "the public route keeps its forced None"
    );
    Ok(())
}

#[test]
fn a_detached_cursor_release_without_its_source_cannot_be_described() -> Result<(), &'static str> {
    let bound_epoch = epoch(2, 8);
    let fixture = ordinary_detached_conversation(owed(StoredEdgeRestore::DetachedCursorRelease {
        participant_id: PARTICIPANT_ID,
        last_dead_binding_epoch: bound_epoch,
        provenance: DetachedCursorReleaseProvenanceRestore::Ordinary(OrdinaryBindingFateRestore {
            authority: OrdinaryBindingAuthorityRestore {
                binding: binding(PARTICIPANT_ID, bound_epoch),
                through_seq: 12,
            },
            terminal: died_terminal(PARTICIPANT_ID, bound_epoch, 9, 13),
            resulting_floor: 14,
        }),
    }));
    let retained_record_limit = fixture.frontiers.retained_record_limit;
    let live = fixture
        .restore()
        .map_err(|_| "the ordinary cursor release restores")?;
    let without_source = ordinary_detached_conversation(ClosureStateRestore::Clear)
        .restore()
        .map_err(|_| "the detached frontier without a release source restores")?;
    let views: Vec<_> = live
        .participants()
        .iter()
        .map(RestoredParticipantLifecycle::view)
        .collect();
    assert_eq!(
        describe_conversation(
            &views,
            without_source.frontiers(),
            retained_record_limit,
            live.closure()
        )
        .err(),
        Some(ConversationDescribeError::DetachedCursorReleaseProvenance)
    );
    Ok(())
}

#[test]
fn a_recovery_without_its_member_cannot_be_described() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let views: Vec<super::ParticipantLifecycleView<'_, Digest, Digest, Digest, Digest>> =
        Vec::new();
    assert_eq!(
        describe_conversation(
            &views,
            &live.frontiers,
            live.retained_record_limit,
            live.closure
        )
        .err(),
        Some(ConversationDescribeError::EdgeTerminal)
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Pin (b): decode(encode(capture(x))) == capture(x), restore == live
// ---------------------------------------------------------------------------

#[test]
fn the_recovery_lifecycle_round_trips_with_and_without_the_latch() -> Result<(), &'static str> {
    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    for latched in [false, true] {
        let live = live_dcr(SHELL_CONVERSATION_ID, latched)?;
        let (conversation, lifecycle) = capsule_round_trip(&shell, &live, 7)?;
        assert_eq!(conversation, shell);
        assert_eq!(lifecycle.participants(), live.participants.as_slice());
        assert_eq!(lifecycle.frontiers(), &live.frontiers);
        assert_eq!(lifecycle.closure(), live.closure);
        assert_eq!(
            lifecycle
                .frontiers()
                .describe(live.retained_record_limit)
                .fenced_marker_issued,
            expected_latch(&live, latched)
        );
    }
    Ok(())
}

proptest! {
    #[test]
    fn any_prefix_shell_with_the_recovery_lifecycle_round_trips_through_the_capsule(
        raw_operations in proptest::collection::vec(
            (0_u8..6, [any::<u64>(), any::<u64>(), any::<u64>(), any::<u64>(), any::<u64>()]),
            0..12,
        ),
        latched in any::<bool>(),
        covered in any::<u64>(),
    ) {
        let shell = shell_after(&raw_operations).map_err(TestCaseError::fail)?;
        let live = live_dcr(SHELL_CONVERSATION_ID, latched).map_err(TestCaseError::fail)?;
        let (conversation, lifecycle) =
            capsule_round_trip(&shell, &live, covered).map_err(TestCaseError::fail)?;
        prop_assert_eq!(&conversation, &shell);
        prop_assert_eq!(lifecycle.participants(), live.participants.as_slice());
        prop_assert_eq!(lifecycle.frontiers(), &live.frontiers);
        prop_assert_eq!(lifecycle.closure(), live.closure);
    }
}

// ---------------------------------------------------------------------------
// Pin (c): a restored latch refuses a second fenced take exactly as live
// ---------------------------------------------------------------------------

#[test]
fn a_carried_fenced_latch_refuses_a_second_fenced_take_after_restore() -> Result<(), &'static str> {
    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    let mut live = live_dcr(SHELL_CONVERSATION_ID, true)?;
    let (_, lifecycle) = capsule_round_trip(&shell, &live, 3)?;
    let (_, mut restored, _) = lifecycle.into_parts();
    let recovery = live.recovery;

    assert!(
        live.frontiers.take_fenced_marker_record(recovery).is_none(),
        "live refuses a second fenced take"
    );
    assert!(
        restored.take_fenced_marker_record(recovery).is_none(),
        "the restored latch refuses it the same way"
    );
    assert_eq!(
        restored, live.frontiers,
        "both refusals leave the same state"
    );

    // The same described input through the public route has no latch, so it
    // would grant the take: the carry is what refuses it.
    let mut public = describe_live(&live)?
        .restore
        .restore()
        .map_err(|_| "the public route restores")?
        .into_parts()
        .1;
    public
        .take_fenced_marker_record(recovery)
        .ok_or("without the carried latch the take is granted")?
        .consume();
    Ok(())
}

// ---------------------------------------------------------------------------
// Pin (c'): a carried latch is checked against the restored state
// ---------------------------------------------------------------------------

/// The latched recovery capsule's bytes with only the latch edited to `latch`.
///
/// The latch is the frontiers section's last field. Its option flag sits at the
/// offset where the unlatched encoding of the same state ends its frontiers
/// body with the absent flag, so the latched body is cut there and the
/// replacement latch's own encoded bytes are spliced in. Everything before the
/// flag is the real latched capsule's, byte for byte.
fn latched_bytes_with_latch(
    latch: Option<(u64, u64, BindingEpoch)>,
) -> Result<Vec<u8>, &'static str> {
    let described = describe_live(&live_dcr(SHELL_CONVERSATION_ID, true)?)?;
    let sections = sections_of(&described)?;
    let [participants, (3, frontiers), closure] = sections.as_slice() else {
        return Err("three sections with the frontiers second");
    };
    let mut unlatched = described.clone();
    unlatched.fenced_marker_issued = None;
    let flag = sections_of(&unlatched)?
        .get(1)
        .map(|(_, body)| body.len())
        .ok_or("the unlatched frontiers section")?
        .checked_sub(1)
        .ok_or("the unlatched frontiers body ends in its absent flag")?;
    assert_eq!(frontiers.get(flag), Some(&1), "the real latch is present");

    let mut replaced = described;
    replaced.fenced_marker_issued = latch;
    let replacement = sections_of(&replaced)?;
    let (_, replacement_body) = replacement.get(1).ok_or("the replacement frontiers")?;
    let mut body = frontiers
        .get(..flag)
        .ok_or("the frontiers before the latch")?
        .to_vec();
    assert_eq!(
        replacement_body.get(..flag),
        Some(body.as_slice()),
        "only the latch bytes are edited"
    );
    body.extend_from_slice(
        replacement_body
            .get(flag..)
            .ok_or("the replacement latch bytes")?,
    );
    envelope(
        SHELL_CONVERSATION_ID,
        &join(&[participants.clone(), (3, body), closure.clone()])?,
    )
}

fn restore_bytes(bytes: &[u8]) -> Result<Option<CapsuleRestoreError>, &'static str> {
    let capsule = LifecycleCapsule::decode_canonical(bytes)
        .map_err(|_| "a latch edit is not a byte fault")?;
    Ok(capsule.restore().err())
}

const LATCH_REFUSED: CapsuleRestoreError = CapsuleRestoreError::Lifecycle(
    ConversationStateRestoreError::Storage(StorageRestoreError::FencedMarkerLatch),
);

#[test]
fn a_foreign_fenced_latch_is_refused_by_name_at_restore() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, true)?;
    let genuine = expected_latch(&live, true).ok_or("the fixture is latched")?;
    let (participant, marker, prior_epoch) = genuine;

    // The genuine latch, spliced back through the same edit, restores.
    assert_eq!(
        restore_bytes(&latched_bytes_with_latch(Some(genuine))?)?,
        None
    );

    let mut foreign_epoch = prior_epoch;
    foreign_epoch.connection_incarnation.connection_ordinal ^= 1;
    assert_ne!(foreign_epoch, prior_epoch);
    for foreign in [
        (participant + 1, marker, prior_epoch),
        (participant, marker + 1, prior_epoch),
        (participant, marker, foreign_epoch),
    ] {
        assert_eq!(
            restore_bytes(&latched_bytes_with_latch(Some(foreign))?)?,
            Some(LATCH_REFUSED),
            "a latch no live take set is refused, not installed to refuse the real take"
        );
    }
    Ok(())
}

#[test]
fn a_fenced_latch_under_a_non_recovery_edge_is_refused_by_name() -> Result<(), &'static str> {
    let fixture = storage_fixtures()
        .into_iter()
        .next()
        .ok_or("the ordinary bound fixture")?;
    let description = ParticipantConversationDescription {
        restore: fixture,
        fenced_marker_issued: Some((PARTICIPANT_ID, 12, epoch(2, 8))),
    };
    assert_eq!(
        description.into_state().err(),
        Some(ConversationStateRestoreError::Storage(
            StorageRestoreError::FencedMarkerLatch
        ))
    );
    Ok(())
}

/// The residue: a latch flipped to `None` cannot be refused. A fenced take
/// writes nothing but the latch, so the flipped capsule is byte for byte the
/// capsule of the same state before any take, which is a legitimate capsule
/// and restores granting the take.
#[test]
fn a_latch_flipped_to_none_is_the_untaken_capsule_byte_for_byte() -> Result<(), &'static str> {
    let flipped = latched_bytes_with_latch(None)?;
    let untaken = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let untaken_bytes = envelope(
        SHELL_CONVERSATION_ID,
        &join(&sections_of(&describe_live(&untaken)?)?)?,
    )?;
    assert_eq!(flipped, untaken_bytes);

    let restored = LifecycleCapsule::decode_canonical(&flipped)
        .map_err(|_| "the flipped capsule decodes")?
        .restore()
        .map_err(|_| "the flipped capsule restores as the untaken state")?;
    let (_, mut frontiers, _) = restored
        .into_parts()
        .lifecycle
        .ok_or("the lifecycle comes back")?
        .into_parts();
    assert_eq!(frontiers, untaken.frontiers);
    frontiers
        .take_fenced_marker_record(untaken.recovery)
        .ok_or("the untaken state grants its one take")?
        .consume();
    Ok(())
}

// ---------------------------------------------------------------------------
// Pin (d): refusals by name
// ---------------------------------------------------------------------------

#[test]
fn every_malformed_lifecycle_section_is_refused_by_name() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let description = describe_live(&live)?;
    let sections = sections_of(&description)?;
    let [participants, frontiers, closure] = sections.as_slice() else {
        return Err("three sections");
    };
    let good = envelope(SHELL_CONVERSATION_ID, &join(&sections)?)?;
    assert!(decode(&good).is_none(), "the hand-built envelope decodes");

    let missing = envelope(
        SHELL_CONVERSATION_ID,
        &join(core::slice::from_ref(participants))?,
    )?;
    assert_eq!(
        decode(&missing),
        Some(CapsuleDecodeError::MissingSection { tag: 3 })
    );

    let swapped = envelope(
        SHELL_CONVERSATION_ID,
        &join(&[participants.clone(), closure.clone(), frontiers.clone()])?,
    )?;
    assert_eq!(
        decode(&swapped),
        Some(CapsuleDecodeError::SectionOutOfOrder { tag: 4 })
    );

    let unknown = envelope(
        SHELL_CONVERSATION_ID,
        &join(&[
            (9, participants.1.clone()),
            frontiers.clone(),
            closure.clone(),
        ])?,
    )?;
    assert_eq!(
        decode(&unknown),
        Some(CapsuleDecodeError::UnknownSection { tag: 9 })
    );

    let mut long_body = participants.1.clone();
    long_body.push(0);
    let declared = u32::try_from(long_body.len()).map_err(|_| "fits")?;
    let long = envelope(
        SHELL_CONVERSATION_ID,
        &join(&[(2, long_body), frontiers.clone(), closure.clone()])?,
    )?;
    assert_eq!(
        decode(&long),
        Some(CapsuleDecodeError::NonCanonicalSectionLength { tag: 2, declared })
    );

    let mut short_body = closure.1.clone();
    short_body.pop();
    let declared = u32::try_from(short_body.len()).map_err(|_| "fits")?;
    let short = envelope(
        SHELL_CONVERSATION_ID,
        &join(&[participants.clone(), frontiers.clone(), (4, short_body)])?,
    )?;
    assert_eq!(
        decode(&short),
        Some(CapsuleDecodeError::NonCanonicalSectionLength { tag: 4, declared })
    );

    Ok(())
}

#[test]
fn every_lifecycle_field_fault_is_refused_by_name() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let sections = sections_of(&describe_live(&live)?)?;
    let [participants, frontiers, closure] = sections.as_slice() else {
        return Err("three sections");
    };

    let bad_closure = envelope(
        SHELL_CONVERSATION_ID,
        &join(&[participants.clone(), frontiers.clone(), (4, vec![9])])?,
    )?;
    assert_eq!(
        decode(&bad_closure),
        Some(CapsuleDecodeError::NonCanonicalSection { tag: 4 })
    );

    // The latch is the frontiers section's last field; with no latch it is a
    // single absent byte, and only 0 or 1 is canonical.
    let mut bad_flag = frontiers.1.clone();
    *bad_flag.last_mut().ok_or("frontiers body")? = 2;
    let bad_latch = envelope(
        SHELL_CONVERSATION_ID,
        &join(&[participants.clone(), (3, bad_flag), closure.clone()])?,
    )?;
    assert_eq!(
        decode(&bad_latch),
        Some(CapsuleDecodeError::NonCanonicalSection { tag: 3 })
    );

    let foreign = envelope(SHELL_CONVERSATION_ID + 1, &join(&sections)?)?;
    assert_eq!(
        decode(&foreign),
        Some(CapsuleDecodeError::ForeignConversation { tag: 3 })
    );
    Ok(())
}

#[test]
fn participants_out_of_order_are_refused_at_capture_and_decode() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let mut doubled = describe_live(&live)?;
    let participant = doubled
        .restore
        .participants
        .first()
        .cloned()
        .ok_or("one participant")?;
    doubled.restore.participants.push(participant);
    let bytes = envelope(
        SHELL_CONVERSATION_ID,
        &encode_description(&doubled).ok_or("the doubled description encodes")?,
    )?;
    assert_eq!(
        decode(&bytes),
        Some(CapsuleDecodeError::ParticipantOutOfOrder {
            participant_id: PARTICIPANT
        })
    );

    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    let mut view = lifecycle_view(&live);
    let first = view
        .participants
        .first()
        .map(super::ParticipantLifecycleView::participant_id)
        .ok_or("one view")?;
    let again = live
        .participants
        .first()
        .map(RestoredParticipantLifecycle::view)
        .ok_or("one participant")?;
    view.participants.push(again);
    assert_eq!(
        LifecycleCapsule::capture(&LifecycleView {
            sealed: None,
            conversation: &shell,
            lifecycle: Some(view),
            covered_log_sequence: 0,
        })
        .err(),
        Some(CapsuleCaptureError::ParticipantOutOfOrder {
            participant_id: first
        })
    );
    Ok(())
}

#[test]
fn a_lifecycle_under_another_shell_is_refused_at_capture() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let other_shell = validated_shell(SHELL_CONVERSATION_ID + 1)?;
    assert_eq!(
        capture(&other_shell, &live, 0).err(),
        Some(CapsuleCaptureError::ForeignConversation)
    );
    Ok(())
}

#[test]
fn a_decoded_lifecycle_that_fails_joint_validation_is_refused_at_restore()
-> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let mut drifted = describe_live(&live)?;
    let Some(ParticipantLifecycleRestore::Live { identity, .. }) =
        drifted.restore.participants.first_mut()
    else {
        return Err("one live participant");
    };
    // The frontier still projects the participant at cursor 0.
    identity.cursor = 5;
    let bytes = envelope(
        SHELL_CONVERSATION_ID,
        &encode_description(&drifted).ok_or("the drifted description encodes")?,
    )?;
    let capsule =
        LifecycleCapsule::decode_canonical(&bytes).map_err(|_| "drift is not a byte fault")?;
    assert!(matches!(
        capsule.restore(),
        Err(CapsuleRestoreError::Lifecycle(_))
    ));
    Ok(())
}

#[test]
fn a_stable_detached_cursor_release_captures_its_complete_restore_provenance()
-> Result<(), &'static str> {
    let bound_epoch = epoch(2, 8);
    let expected_closure = owed(StoredEdgeRestore::DetachedCursorRelease {
        participant_id: PARTICIPANT_ID,
        last_dead_binding_epoch: bound_epoch,
        provenance: DetachedCursorReleaseProvenanceRestore::Ordinary(OrdinaryBindingFateRestore {
            authority: OrdinaryBindingAuthorityRestore {
                binding: binding(PARTICIPANT_ID, bound_epoch),
                through_seq: 12,
            },
            terminal: died_terminal(PARTICIPANT_ID, bound_epoch, 9, 13),
            resulting_floor: 14,
        }),
    });
    let fixture = ordinary_detached_conversation(expected_closure);
    let retained_record_limit = fixture.frontiers.retained_record_limit;
    let live = fixture
        .restore()
        .map_err(|_| "the stable release restores")?;
    let captured = live
        .describe(retained_record_limit)
        .map_err(|_| "the stable release must retain capture provenance")?;
    assert_eq!(captured.restore.closure, expected_closure);
    let restored = captured
        .restore
        .restore()
        .map_err(|_| "the complete release capture restores")?;
    let recaptured = restored
        .describe(retained_record_limit)
        .map_err(|_| "restored release retains the same provenance")?;
    assert_eq!(recaptured.restore.closure, expected_closure);
    Ok(())
}

#[test]
fn retained_binding_sources_are_exact_and_jointly_restored() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    let Some(RestoredParticipantLifecycle::Live {
        binding_origin: Some(origin),
        ..
    }) = live.participants.first()
    else {
        return Err("the fixture retains its original binding source");
    };
    let source = super::checkpoint_codec::encode_binding_origin_source(*origin);
    let bytes = capture(&shell, &live, 4)
        .map_err(|_| "the fixture captures")?
        .encode_canonical();
    let decode = || LifecycleCapsule::decode_canonical(&bytes).map_err(|_| "the fixture decodes");
    let restored = decode()?
        .restore_with_binding_sources(&[(PARTICIPANT, &source)])
        .map_err(|_| "the exact source jointly restores")?;
    assert_eq!(restored.covered_log_sequence(), 4);
    assert!(matches!(
        decode()?.restore_with_binding_sources(&[]),
        Err(super::BindingOriginSourceError::Association { .. })
    ));
    assert!(matches!(
        decode()?.restore_with_binding_sources(&[(PARTICIPANT + 1, &source)]),
        Err(super::BindingOriginSourceError::Association { .. })
    ));
    let mut trailing = source;
    trailing.push(0);
    assert!(matches!(
        decode()?.restore_with_binding_sources(&[(PARTICIPANT, &trailing)]),
        Err(super::BindingOriginSourceError::Decode { .. })
    ));
    Ok(())
}

#[test]
fn checkpoint_capture_from_retained_origin_bytes_is_identical() -> Result<(), &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    let Some(RestoredParticipantLifecycle::Live {
        binding_origin: Some(origin),
        ..
    }) = live.participants.first()
    else {
        return Err("fixture origin missing");
    };
    let source = super::checkpoint_codec::encode_binding_origin_source(*origin);
    let original = capture(&shell, &live, 4)
        .map_err(|_| "ordinary capture refused")?
        .encode_canonical();
    let participants = live
        .participants
        .iter()
        .map(|participant| match participant.view() {
            DigestParticipantView::Live {
                member,
                binding,
                detach_cell,
                ..
            } => DigestParticipantView::Live {
                member,
                binding,
                detach_cell,
                binding_origin: None,
            },
            DigestParticipantView::Retired(retired) => DigestParticipantView::Retired(retired),
        })
        .collect();
    let view = LifecycleView {
        sealed: None,
        conversation: &shell,
        covered_log_sequence: 4,
        lifecycle: Some(ConversationLifecycleView {
            participants,
            frontiers: &live.frontiers,
            retained_record_limit: live.retained_record_limit,
            closure: &live.closure,
        }),
    };
    let captured = LifecycleCapsule::capture_with_binding_sources(&view, &[(PARTICIPANT, &source)])
        .map_err(|_| "validated source capture refused")?;
    assert_eq!(captured.encode_canonical(), original);
    assert!(matches!(
        LifecycleCapsule::capture_with_binding_sources(&view, &[]),
        Err(super::BindingOriginCaptureError::Association { .. })
    ));
    assert!(matches!(
        LifecycleCapsule::capture_with_binding_sources(&view, &[(PARTICIPANT + 1, &source)]),
        Err(super::BindingOriginCaptureError::Association { .. })
    ));
    let mut trailing = source;
    trailing.push(0);
    assert!(matches!(
        LifecycleCapsule::capture_with_binding_sources(&view, &[(PARTICIPANT, &trailing)]),
        Err(super::BindingOriginCaptureError::Decode { .. })
    ));
    Ok(())
}

#[derive(Debug)]
struct FrontierRestoreFixture {
    capsule_bytes: Vec<u8>,
    accounting: super::ClosureAccounting,
    charges: Vec<super::RetainedRecordCharge>,
    accounting_bytes: Vec<u8>,
    charge_bytes: Vec<u8>,
    episode_bytes: Vec<u8>,
    retained_record_limit: u64,
}

impl FrontierRestoreFixture {
    fn parts(&self) -> Result<super::RestoredLifecycleParts, &'static str> {
        let capsule = LifecycleCapsule::decode_canonical(&self.capsule_bytes)
            .map_err(|_| "capsule decode refused")?;
        let restored = capsule
            .restore()
            .map_err(|_| "joint lifecycle restore refused")?;
        Ok(restored.into_parts())
    }

    fn saved(&self) -> super::FrontierCheckpointSource<'_> {
        super::FrontierCheckpointSource {
            closure_accounting: Some(&self.accounting_bytes),
            retained_charges: Some(&self.charge_bytes),
            cursor_episode: Some(&self.episode_bytes),
            observer_progress: 0,
            retained_record_limit: self.retained_record_limit,
            marker_max: crate::algebra::ResourceVector {
                entries: 1,
                bytes: 107,
            },
        }
    }
}

fn saved_frontier_episode_bytes(
    episode: &super::NonzeroDebtCursorEpisode,
) -> Result<Vec<u8>, &'static str> {
    let mut bytes = episode.encode().map_err(|_| "episode encoding refused")?;
    let count_start = bytes.len().checked_sub(4).ok_or("fact count missing")?;
    bytes.truncate(count_start);
    bytes.extend_from_slice(&2_u32.to_be_bytes());
    for (boundary, state) in [(0_u64, 1_u8), (1, 0)] {
        bytes.extend_from_slice(&PARTICIPANT.to_be_bytes());
        bytes.extend_from_slice(&boundary.to_be_bytes());
        bytes.push(state);
    }
    Ok(bytes)
}

fn frontier_restore_fixture() -> Result<FrontierRestoreFixture, &'static str> {
    use super::{ClosureAccounting, NonzeroDebtCursorEpisode, RetainedRecordCharge};
    use crate::algebra::ResourceVector;

    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    let capsule_bytes = capture(&shell, &live, 4)
        .map_err(|_| "capture refused")?
        .encode_canonical();
    let ClosureState::Owed { debt, .. } = live.closure else {
        return Err("fixture debt missing");
    };
    let accounting = ClosureAccounting::try_new(
        live.closure,
        1,
        1,
        2,
        2,
        ResourceVector {
            entries: 3,
            bytes: 5,
        },
        WideResourceVector {
            entries: 2,
            bytes: 214,
        },
        ResourceVector {
            entries: 100,
            bytes: 10_000,
        },
        7,
        11,
    )
    .map_err(|_| "fixture accounting refused")?;
    let charges: Vec<_> = live
        .frontiers
        .retained_records()
        .iter()
        .map(|record| {
            RetainedRecordCharge::new(
                record.delivery_seq,
                record.admission_order,
                ResourceVector {
                    entries: 1,
                    bytes: 107,
                },
            )
        })
        .collect();
    let accounting_bytes = super::checkpoint_codec::encode_accounting(&accounting);
    let charge_bytes =
        super::checkpoint_codec::encode_charges(&charges).ok_or("charge encoding refused")?;
    let episode = NonzeroDebtCursorEpisode::from_claim_frontiers(&live.frontiers, debt, 0)
        .map_err(|_| "fixture episode refused")?;
    let episode_bytes = saved_frontier_episode_bytes(&episode)?;
    Ok(FrontierRestoreFixture {
        capsule_bytes,
        accounting,
        charges,
        accounting_bytes,
        charge_bytes,
        episode_bytes,
        retained_record_limit: live.retained_record_limit,
    })
}

fn assert_frontier_restore_refusals(fixture: &FrontierRestoreFixture) -> Result<(), &'static str> {
    use super::{FrontierCheckpointSource, LiveFrontierOwner, LiveFrontierRestoreError};

    let saved = fixture.saved();
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            fixture.parts()?,
            FrontierCheckpointSource {
                closure_accounting: None,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::MissingClosureAccounting)
    ));
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            fixture.parts()?,
            FrontierCheckpointSource {
                retained_charges: None,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::MissingRetainedCharges)
    ));
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            fixture.parts()?,
            FrontierCheckpointSource {
                cursor_episode: None,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::MissingCursorEpisode)
    ));
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            fixture.parts()?,
            FrontierCheckpointSource {
                observer_progress: 1,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::CursorEpisode(_))
    ));
    Ok(())
}

#[test]
fn checkpoint_frontier_restore_preserves_saved_bytes_and_fact_states() -> Result<(), &'static str> {
    use super::LiveFrontierOwner;

    let fixture = frontier_restore_fixture()?;
    let saved = fixture.saved();
    let restored = LiveFrontierOwner::restore_checkpoint(fixture.parts()?, saved)
        .map_err(|_| "saved coupled frontier refused")?;
    assert_eq!(
        restored.owner.encode_closure_accounting_source(),
        fixture.accounting_bytes
    );
    assert_eq!(
        restored.owner.encode_retained_charge_source(),
        Some(fixture.charge_bytes.clone())
    );
    let conversation = restored
        .into_debt_dispatch()
        .map_err(|_| "saved dispatch coupling refused")?;
    let episode = conversation
        .dispatch
        .episode()
        .ok_or("saved owed episode missing")?;
    assert_eq!(episode.facts().len(), 2);
    assert_eq!(
        episode.encode().map_err(|_| "recaptured episode refused")?,
        fixture.episode_bytes
    );
    assert_eq!(
        conversation.dispatch.frontier().closure_accounting(),
        fixture.accounting
    );
    assert_eq!(
        conversation.dispatch.frontier().retained_charges(),
        fixture.charges
    );
    let reference_owner = LiveFrontierOwner::restore_checkpoint(fixture.parts()?, saved)
        .map_err(|_| "reference saved frontier refused")?
        .owner;
    let regenerated = super::ObligationDebtDispatchState::from_frontier(reference_owner, 0)
        .map_err(|_| "reference frontier episode refused")?;
    let regenerated = regenerated
        .episode()
        .ok_or("reference owed episode missing")?;
    assert_eq!(regenerated.facts().len(), 0);
    assert_ne!(
        regenerated
            .encode()
            .map_err(|_| "reference encoding refused")?,
        fixture.episode_bytes
    );
    assert_frontier_restore_refusals(&fixture)?;
    Ok(())
}

#[test]
fn checkpoint_owner_tokens_pin_canonical_bytes_and_refuse_mismatched_sources()
-> Result<(), &'static str> {
    let current = binding(PARTICIPANT_ID, epoch(2, 8));
    let origin = BindingOrigin::unfenced(AttachedLifecycleRecord::from_binding(
        current,
        AttachedRecordPosition::new(7, 11),
    ));
    let raw = OrdinaryBindingFateRestore {
        authority: OrdinaryBindingAuthorityRestore {
            binding: current,
            through_seq: 12,
        },
        terminal: died_terminal(PARTICIPANT_ID, current.binding_epoch, 9, 13),
        resulting_floor: 14,
    };
    let body = raw.encode_checkpoint();
    assert_eq!(
        super::checkpoint_codec::decode_ordinary_fate(&body),
        Ok(raw)
    );
    let fate = OrdinaryBindingFateRestore::restore_checkpoint(&body, &origin)
        .map_err(|_| "ordinary fate refused")?;
    assert_eq!(fate.resulting_floor(), 14);
    let mut bad = body.clone();
    bad.push(0);
    assert!(OrdinaryBindingFateRestore::restore_checkpoint(&bad, &origin).is_err());
    let wrong_origin = BindingOrigin::unfenced(AttachedLifecycleRecord::from_binding(
        binding(PARTICIPANT_ID, epoch(3, 8)),
        AttachedRecordPosition::new(7, 11),
    ));
    assert!(OrdinaryBindingFateRestore::restore_checkpoint(&body, &wrong_origin).is_err());

    let ordinary = raw
        .authority
        .restore_with_origin(&origin)
        .map_err(|_| "ordinary authority refused")?;
    let token = super::SealedBindingFateToken {
        ordinary: Some(ordinary),
        recovered: None,
        cursor: 12,
    };
    let token_body = token
        .encode_checkpoint()
        .map_err(|_| "token capture refused")?;
    let restored =
        super::SealedBindingFateToken::restore_checkpoint(&token_body, &origin, 12, None)
            .map_err(|_| "token restore refused")?;
    assert_eq!(token, restored);
    assert_eq!(
        restored
            .encode_checkpoint()
            .map_err(|_| "restored capture refused")?,
        token_body
    );
    assert!(
        super::SealedBindingFateToken::restore_checkpoint(&token_body, &origin, 13, None).is_err()
    );
    assert!(
        super::SealedBindingFateToken::restore_checkpoint(&token_body, &wrong_origin, 12, None)
            .is_err()
    );

    let finalizer =
        super::PendingDiedOrdinaryFinalizer::restore_checkpoint(&14_u64.to_be_bytes(), &fate)
            .map_err(|_| "finalizer restore refused")?;
    assert_eq!(finalizer.encode_checkpoint(), 14_u64.to_be_bytes());
    assert!(
        super::PendingDiedOrdinaryFinalizer::restore_checkpoint(&15_u64.to_be_bytes(), &fate)
            .is_err()
    );
    assert!(super::PendingDiedOrdinaryFinalizer::restore_checkpoint(&[0; 7], &fate).is_err());

    let projection = fate.observer_progress_projection();
    let projection_body = projection.encode_checkpoint();
    let mut expected = [0; 16];
    expected[..8].copy_from_slice(&fate.conversation_id().to_be_bytes());
    expected[8..].copy_from_slice(&14_u64.to_be_bytes());
    assert_eq!(projection_body, expected);
    let restored_projection =
        super::ObserverProgressProjection::restore_checkpoint(&projection_body, projection)
            .map_err(|_| "projection restore refused")?;
    assert_eq!(restored_projection.encode_checkpoint(), projection_body);
    let mut mismatch = projection_body;
    mismatch[15] ^= 1;
    assert!(
        super::ObserverProgressProjection::restore_checkpoint(
            &mismatch,
            fate.observer_progress_projection()
        )
        .is_err()
    );
    Ok(())
}

use super::{
    ClosureAccounting, FrontierCheckpointSource, LiveFrontierOwner, LiveFrontierRestoreError,
    NonzeroDebtCursorEpisode, RetainedRecordCharge,
};
use crate::algebra::ResourceVector;

struct CheckpointFrontierFixture {
    capsule_bytes: Vec<u8>,
    accounting: ClosureAccounting,
    charges: Vec<RetainedRecordCharge>,
    accounting_bytes: Vec<u8>,
    charge_bytes: Vec<u8>,
    episode_bytes: Vec<u8>,
    retained_record_limit: u64,
}

impl CheckpointFrontierFixture {
    fn parts(&self) -> Result<super::RestoredLifecycleParts, &'static str> {
        Ok(LifecycleCapsule::decode_canonical(&self.capsule_bytes)
            .map_err(|_| "capsule decode refused")?
            .restore()
            .map_err(|_| "joint lifecycle restore refused")?
            .into_parts())
    }

    const fn saved(&self) -> FrontierCheckpointSource<'_> {
        FrontierCheckpointSource {
            closure_accounting: Some(self.accounting_bytes.as_slice()),
            retained_charges: Some(self.charge_bytes.as_slice()),
            cursor_episode: Some(self.episode_bytes.as_slice()),
            observer_progress: 0,
            retained_record_limit: self.retained_record_limit,
            marker_max: ResourceVector {
                entries: 1,
                bytes: 107,
            },
        }
    }
}

fn checkpoint_frontier_fixture() -> Result<&'static CheckpointFrontierFixture, &'static str> {
    static FIXTURE: std::sync::OnceLock<Result<CheckpointFrontierFixture, &'static str>> =
        std::sync::OnceLock::new();
    FIXTURE
        .get_or_init(build_checkpoint_frontier_fixture)
        .as_ref()
        .map_err(|error| *error)
}

fn checkpoint_frontier_fixture_accounting(
    closure: ClosureState,
) -> Result<ClosureAccounting, &'static str> {
    ClosureAccounting::try_new(
        closure,
        1,
        1,
        2,
        2,
        ResourceVector {
            entries: 3,
            bytes: 5,
        },
        WideResourceVector {
            entries: 2,
            bytes: 214,
        },
        ResourceVector {
            entries: 100,
            bytes: 10_000,
        },
        7,
        11,
    )
    .map_err(|_| "fixture accounting refused")
}

fn build_checkpoint_frontier_fixture() -> Result<CheckpointFrontierFixture, &'static str> {
    let live = live_dcr(SHELL_CONVERSATION_ID, false)?;
    let shell = validated_shell(SHELL_CONVERSATION_ID)?;
    let capsule_bytes = capture(&shell, &live, 4)
        .map_err(|_| "capture refused")?
        .encode_canonical();
    let ClosureState::Owed { debt, .. } = live.closure else {
        return Err("fixture debt missing");
    };
    let accounting = checkpoint_frontier_fixture_accounting(live.closure)?;
    let charges: Vec<_> = live
        .frontiers
        .retained_records()
        .iter()
        .map(|record| {
            RetainedRecordCharge::new(
                record.delivery_seq,
                record.admission_order,
                ResourceVector {
                    entries: 1,
                    bytes: 107,
                },
            )
        })
        .collect();
    let accounting_bytes = super::checkpoint_codec::encode_accounting(&accounting);
    let charge_bytes =
        super::checkpoint_codec::encode_charges(&charges).ok_or("charge encoding refused")?;
    let episode = NonzeroDebtCursorEpisode::from_claim_frontiers(&live.frontiers, debt, 0)
        .map_err(|_| "fixture episode refused")?;
    let mut episode_bytes = episode.encode().map_err(|_| "episode encoding refused")?;
    let count_start = episode_bytes
        .len()
        .checked_sub(4)
        .ok_or("fact count missing")?;
    episode_bytes.truncate(count_start);
    episode_bytes.extend_from_slice(&2_u32.to_be_bytes());
    for (boundary, state) in [(0_u64, 1_u8), (1, 0)] {
        episode_bytes.extend_from_slice(&PARTICIPANT.to_be_bytes());
        episode_bytes.extend_from_slice(&boundary.to_be_bytes());
        episode_bytes.push(state);
    }
    Ok(CheckpointFrontierFixture {
        capsule_bytes,
        accounting,
        charges,
        accounting_bytes,
        charge_bytes,
        episode_bytes,
        retained_record_limit: live.retained_record_limit,
    })
}

#[test]
fn checkpoint_frontier_restore_preserves_pending_and_consumed_fact_bytes()
-> Result<(), &'static str> {
    let fixture = checkpoint_frontier_fixture()?;
    let parts = || fixture.parts();
    let saved = fixture.saved();
    let accounting_bytes = fixture.accounting_bytes.clone();
    let charge_bytes = fixture.charge_bytes.clone();
    let episode_bytes = fixture.episode_bytes.clone();
    let accounting = fixture.accounting;
    let charges = fixture.charges.clone();
    let restored = LiveFrontierOwner::restore_checkpoint(parts()?, saved)
        .map_err(|_| "saved coupled frontier refused")?;
    assert_eq!(
        restored.owner.encode_closure_accounting_source(),
        accounting_bytes
    );
    assert_eq!(
        restored.owner.encode_retained_charge_source(),
        Some(charge_bytes)
    );
    let conversation = restored
        .into_debt_dispatch()
        .map_err(|_| "saved dispatch coupling refused")?;
    let episode = conversation
        .dispatch
        .episode()
        .ok_or("saved owed episode missing")?;
    assert_eq!(episode.facts().len(), 2);
    assert_eq!(
        episode.encode().map_err(|_| "recaptured episode refused")?,
        episode_bytes
    );
    assert_eq!(
        conversation.dispatch.frontier().closure_accounting(),
        accounting
    );
    assert_eq!(conversation.dispatch.frontier().retained_charges(), charges);
    Ok(())
}

#[test]
fn checkpoint_frontier_restore_does_not_regenerate_saved_facts() -> Result<(), &'static str> {
    let fixture = checkpoint_frontier_fixture()?;
    let parts = || fixture.parts();
    let saved = fixture.saved();
    let episode_bytes = fixture.episode_bytes.clone();
    let reference_owner = LiveFrontierOwner::restore_checkpoint(parts()?, saved)
        .map_err(|_| "reference saved frontier refused")?
        .owner;
    let regenerated = super::ObligationDebtDispatchState::from_frontier(reference_owner, 0)
        .map_err(|_| "reference frontier episode refused")?;
    let regenerated = regenerated
        .episode()
        .ok_or("reference owed episode missing")?;
    assert_eq!(regenerated.facts().len(), 0);
    assert_ne!(
        regenerated
            .encode()
            .map_err(|_| "reference encoding refused")?,
        episode_bytes
    );
    Ok(())
}

#[test]
fn checkpoint_frontier_restore_refuses_missing_owed_state_sources() -> Result<(), &'static str> {
    let fixture = checkpoint_frontier_fixture()?;
    let parts = || fixture.parts();
    let saved = fixture.saved();
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            parts()?,
            FrontierCheckpointSource {
                closure_accounting: None,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::MissingClosureAccounting)
    ));
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            parts()?,
            FrontierCheckpointSource {
                retained_charges: None,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::MissingRetainedCharges)
    ));
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            parts()?,
            FrontierCheckpointSource {
                cursor_episode: None,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::MissingCursorEpisode)
    ));
    Ok(())
}

#[test]
fn checkpoint_frontier_restore_refuses_foreign_observer_progress() -> Result<(), &'static str> {
    let fixture = checkpoint_frontier_fixture()?;
    let parts = || fixture.parts();
    let saved = fixture.saved();
    assert!(matches!(
        LiveFrontierOwner::restore_checkpoint(
            parts()?,
            FrontierCheckpointSource {
                observer_progress: 1,
                ..saved
            }
        ),
        Err(LiveFrontierRestoreError::CursorEpisode(_))
    ));
    Ok(())
}